NumeRe v1.1.4
NumeRe: Framework für Numerische Rechnungen
fileops.cpp
Go to the documentation of this file.
1/*****************************************************************************
2 NumeRe: Framework fuer Numerische Rechnungen
3 Copyright (C) 2018 Erik Haenel et al.
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17******************************************************************************/
18
19#include "fileops.hpp"
20#include "../utils/tools.hpp"
21#include "../maths/parser_functions.hpp"
22#include "../../kernel.hpp"
23#include "../ui/language.hpp"
24
25extern Language _lang;
26
27std::string removeQuotationMarks(const std::string&);
28
38{
39 if (!cmdParser.getExpr().length())
40 return false;
41
42 bool bIgnore = cmdParser.hasParam("ignore") || cmdParser.hasParam("i");
43 bool bAll = cmdParser.hasParam("all") || cmdParser.hasParam("a");
44 std::string _sCmd = "";
45 FileSystem _fSys;
47
48 //sCmd = fromSystemCodePage(sCmd);
49
50 // Get all relevant files
51 std::vector<std::string> vFiles = getFileList(cmdParser.parseExprAsString(), NumeReKernel::getInstance()->getSettings(), 1);
52
53 // No files -> No deletion needed
54 if (!vFiles.size())
55 return bIgnore; // return true, if ignored, false otherwise
56
57 // Delete the first or every file
58 for (const std::string& sFile : vFiles)
59 {
60 if (sFile.substr(sFile.rfind('.')) == ".exe"
61 || sFile.substr(sFile.rfind('.')) == ".dll"
62 || sFile.substr(sFile.rfind('.')) == ".sys"
63 || sFile.substr(sFile.rfind('.')) == ".vfm")
64 return false;
65
66 if (!bIgnore)
67 {
68 std::string c = "";
69 NumeReKernel::print(LineBreak( _lang.get("BUILTIN_REMOVEFILE_CONFIRM", _sCmd), NumeReKernel::getInstance()->getSettings()) );
72
73 if (c != _lang.YES())
74 return false;
75 }
76
77 // Delete it
78 remove(sFile.c_str());
79
80 // Delete only the first one
81 if (!bAll)
82 return true;
83 }
84
85 return true;
86}
87
88
99{
100 if (!cmdParser.getExpr().length())
101 return false;
102
103 std::string sSource = cmdParser.getExpr();
104 std::string sTarget = "";
105 std::string _sTarget = "";
106 std::string sDummy = "";
107 std::string sFile = "";
108 std::vector<std::string> vFileList;
109
110 unsigned int nthFile = 1;
111 bool bAll = cmdParser.hasParam("all") || cmdParser.hasParam("a");
112 bool bSuccess = false;
113
114 FileSystem _fSys;
115 _fSys.initializeFromKernel();
116 cmdParser.clearReturnValue();
117
118 //sCmd = fromSystemCodePage(sCmd);
119
120 // Get the target
121 if (cmdParser.hasParam("target") || cmdParser.hasParam("t"))
122 {
123 if (cmdParser.hasParam("target"))
124 sTarget = cmdParser.getParameterValueAsString("target", "");
125 else
126 sTarget = cmdParser.getParameterValueAsString("t", "");
127
128 StripSpaces(sTarget);
129 }
130 else
132
133 // Clean source and target paths
134 sSource = replacePathSeparator(sSource);
135 sTarget = replacePathSeparator(sTarget);
136
137 if (NumeReKernel::getInstance()->getStringParser().isStringExpression(sSource))
138 NumeReKernel::getInstance()->getStringParser().evalAndFormat(sSource, sDummy, true);
139
140 sSource = removeQuotationMarks(sSource);
141
142 // In 'all' case it is necessary to set the return value
143 // from the source string
144 if (bAll)
145 cmdParser.setReturnValue(sSource);
146
147 // Get the source file list an validate
148 vFileList = getFileList(sSource, NumeReKernel::getInstance()->getSettings(), 1);
149
150 if (!vFileList.size())
151 return false;
152
153 // Operate on each file in the list
154 for (unsigned int nFile = 0; nFile < vFileList.size(); nFile++)
155 {
156 _sTarget = sTarget;
157 sFile = vFileList[nFile];
158
159 if (sFile.find('.') != std::string::npos)
160 {
161 std::string sExt = sFile.substr(sFile.rfind('.'));
162
163 if (sExt != ".exe" && sExt != ".sys" && sExt != ".dll")
164 _fSys.declareFileType(sExt);
165 }
166
167 // Resolve the file name
168 sFile = _fSys.ValidFileName(sFile);
169
170 if (_sTarget[_sTarget.length()-1] == '*' && _sTarget[_sTarget.length()-2] == '/')
171 _sTarget = _sTarget.substr(0, _sTarget.length()-2) + sFile.substr(sFile.rfind('/'));
172 else if (_sTarget[_sTarget.length()-1] == '/')
173 _sTarget = _sTarget.substr(0, _sTarget.length()-1) + sFile.substr(sFile.rfind('/'));
174
175 // Prepare the file tags
176 if (_sTarget.find('<') != std::string::npos && _sTarget.find('>', _sTarget.find('<')) != std::string::npos)
177 {
178 std::string sToken = "";
179
180 for (unsigned int i = 0; i < _sTarget.length(); i++)
181 {
182 if (_sTarget[i] == '<')
183 {
184 if (_sTarget.find('>', i) == std::string::npos)
185 break;
186
187 sToken = _sTarget.substr(i, _sTarget.find('>', i)+1-i);
188
189 if (sToken.find('#') != std::string::npos)
190 {
191 unsigned int nLength = 1;
192
193 if (sToken.find('~') != std::string::npos)
194 nLength = sToken.rfind('~')-sToken.find('#')+1;
195
196 sToken.clear();
197
198 if (nLength > toString((int)nthFile).length())
199 sToken.append(nLength-toString((int)(nthFile)).length(),'0');
200
201 sToken += toString((int)(nthFile));
202 _sTarget.replace(i,_sTarget.find('>',i)+1-i,sToken);
203 i += sToken.length();
204 }
205 else if (sToken == "<fname>")
206 {
207 sToken = sDummy.substr(sDummy.rfind('/')+1, sDummy.rfind('.')-1-sDummy.rfind('/'));
208 _sTarget.replace(i,_sTarget.find('>',i)+1-i,sToken);
209 i += sToken.length();
210 }
211 }
212
213 if (_sTarget.find('<',i) == std::string::npos)
214 break;
215 }
216 }
217
218 if (NumeReKernel::getInstance()->getStringParser().isStringExpression(_sTarget))
219 NumeReKernel::getInstance()->getStringParser().evalAndFormat(_sTarget, sDummy, true);
220
221 _sTarget = removeQuotationMarks(_sTarget);
222 StripSpaces(_sTarget);
223
224 if (_sTarget.substr(_sTarget.length()-2) == "/*")
225 _sTarget.erase(_sTarget.length()-1);
226
227 // Validate target file name
228 _sTarget = _fSys.ValidFileName(_sTarget);
229
230 if (_sTarget.substr(_sTarget.rfind('.')-1) == "*.dat")
231 _sTarget = _sTarget.substr(0,_sTarget.rfind('/')) + sFile.substr(sFile.rfind('/'));
232 else if (_sTarget.substr(_sTarget.rfind('.')-1) == "/.dat")
233 _sTarget = _sTarget.substr(0, _sTarget.rfind('/')) + sFile.substr(sFile.rfind('/'));
234
235 if (_sTarget.substr(_sTarget.rfind('.')) != sFile.substr(sFile.rfind('.')))
236 _sTarget = _sTarget.substr(0, _sTarget.rfind('.')) + sFile.substr(sFile.rfind('.'));
237
238 if (!fileExists(sFile))
239 continue;
240
241 // Perform the actual file operation
242 if (cmdParser.getCommand() == "move")
243 moveFile(sFile, _sTarget);
244 else
245 copyFile(sFile, _sTarget);
246
247 nthFile++;
248 bSuccess = true;
249
250 if (!bAll
251 || (cmdParser.getCommandLine().find_first_of("?*") == std::string::npos)
252 || (sTarget.find('*') == std::string::npos && (sTarget[sTarget.length()-1] != '/' && sTarget.substr(sTarget.length()-2) != "/\"") && sTarget.find("<#") == std::string::npos && sTarget.find("<fname>") == std::string::npos))
253 {
254 cmdParser.setReturnValue(sFile);
255 break;
256 }
257 }
258
259 return bSuccess;
260}
261
262
263bool generateTemplate(const std::string& sFile, const std::string& sTempl, const std::vector<std::string>& vTokens, Settings& _option)
264{
265 std::ifstream iTempl_in;
266 std::ofstream oFile_out;
267 std::string sLine;
268 std::string sToken;
269
270 iTempl_in.open(_option.ValidFileName(sTempl, ".nlng").c_str());
271 oFile_out.open(_option.ValidFileName(sFile, sFile.substr(sFile.rfind('.'))).c_str());
272
273 if (iTempl_in.fail() || oFile_out.fail())
274 {
275 iTempl_in.close();
276 oFile_out.close();
277 return false;
278 }
279
280 while (!iTempl_in.eof())
281 {
282 std::getline(iTempl_in, sLine);
283 for (unsigned int i = 0; i < vTokens.size(); i++)
284 {
285 sToken = "%%"+toString(i+1)+"%%";
286 while (sLine.find(sToken) != std::string::npos)
287 {
288 sLine.replace(sLine.find(sToken), sToken.length(), vTokens[i]);
289 }
290 }
291 oFile_out << sLine << std::endl;
292 }
293 iTempl_in.close();
294 oFile_out.close();
295 return true;
296}
297
This class provides the functionality to extract the different components of a command line into the ...
const std::string & getCommandLine() const
Returns the command line used for constructing this instance (e.g. for errors).
std::string getParameterValueAsString(const std::string &sParameter, const std::string &sDefaultValue, bool stripAlways=false, bool onlyStringEvaluation=false) const
Parses the selected parameter value as a string and returns it. If the parameter is not found,...
const std::string & getExpr() const
Returns the expression as plain value.
void setReturnValue(const std::string &sRetVal)
Sets the return value of the current command by simply appending it to the return value statement.
void clearReturnValue()
Removes the return value statement.
const std::string & getCommand() const
Returns the command.
std::string parseExprAsString() const
Prepares the expression by handling all string operations and removing the surrounding quotation mark...
bool hasParam(const std::string &sParameter) const
Simple wrapper around findParameter(), if used as a boolean flag.
This class implements the basic input/ output file system and provides functionalities to work with f...
Definition: filesystem.hpp:92
void initializeFromKernel()
Member function to remote-initialize the class from the kernel. Cannot be used during kernel start-up...
Definition: filesystem.cpp:750
std::string ValidFileName(std::string _sFileName, const std::string sExtension=".dat", bool checkExtension=true, bool doCleanPath=true) const
This member function evaluates, whether the passed filename is a valid filename. One may supply a pre...
Definition: filesystem.cpp:280
void declareFileType(const std::string &sFileType)
Definition: filesystem.hpp:132
This class handles the internal language system and returns the language strings of the selected lang...
Definition: language.hpp:38
std::string YES() const
Definition: language.hpp:197
std::string get(const std::string &sMessage, const std::vector< std::string > &vTokens) const
This member function returns the language string for the passed language identifier and replaces all ...
Definition: language.cpp:292
StringParserRetVal evalAndFormat(std::string &sLine, std::string &sCache, bool bSilent=false, bool bCheckAssertions=false)
This public member function evaluates the passed string expression and formats the results for the co...
static NumeReKernel * getInstance()
This static member function returns a a pointer to the singleton instance of the kernel.
Definition: kernel.hpp:221
NumeRe::StringParser & getStringParser()
Definition: kernel.hpp:286
static void getline(std::string &sLine)
This function is an implementation replacing the std::getline() function.
Definition: kernel.cpp:3621
static void printPreFmt(const std::string &__sLine, bool printingEnabled=true)
This member function appends the pre- formatted string to the buffer and informs the terminal that we...
Definition: kernel.cpp:2683
static void print(const std::string &__sLine, bool printingEnabled=true)
This member function appends the passed string as a new output line to the buffer and informs the ter...
Definition: kernel.cpp:2636
Settings & getSettings()
Definition: kernel.hpp:296
This class manages the setting values of the internal (kernel) settings of this application.
Definition: settings.hpp:663
Common exception class for all exceptions thrown in NumeRe.
Definition: error.hpp:32
static size_t invalid_position
Definition: error.hpp:235
bool generateTemplate(const std::string &sFile, const std::string &sTempl, const std::vector< std::string > &vTokens, Settings &_option)
Definition: fileops.cpp:263
bool removeFile(CommandLineParser &cmdParser)
Removes one or more files from the disk.
Definition: fileops.cpp:37
std::string removeQuotationMarks(const std::string &)
This function simply removes the surrounding quotation marks.
Language _lang
Definition: kernel.cpp:39
bool moveOrCopyFiles(CommandLineParser &cmdParser)
Moves or copies files from one location to another. Supports also wildcards and file lists.
Definition: fileops.cpp:98
std::string replacePathSeparator(const std::string &)
This function replaces the Windows style path sparators to UNIX style.
bool fileExists(const string &)
This function checks, whether the file with the passed file name exists.
Definition: tools.cpp:2500
void StripSpaces(std::string &)
Removes leading and trailing white spaces and tabulator characters.
std::string toString(int)
Converts an integer to a string without the Settings bloat.
vector< string > getFileList(const string &sDirectory, const Settings &_option, int nFlags)
This function returns a list of files (including their paths, if nFlags & 1).
Definition: tools.cpp:2853
void moveFile(const string &sFile, const string &sNewFileName)
Move a file from one to another location. Can be used for renaming as well.
Definition: tools.cpp:1412
void copyFile(const string &sFile, const string &sTarget)
Copy the file's contents to another file.
Definition: tools.cpp:1431
std::string LineBreak(std::string sOutput, const Settings &_option, bool bAllowDashBreaks, int nFirstIndent, int nIndent)
This function takes a string, splits it into multiple lines if it is too long and returns the result.
Definition: tools.cpp:2205