PhoenixMock  1.8.7
Tools to split/merge/print mock used in Phoenix
string_system.cpp
Go to the documentation of this file.
1 
2 /***************************************
3  Auteur : Pierre Aubert
4  Mail : pierre.aubert@lapp.in2p3.fr
5  Licence : CeCILL-C
6 ****************************************/
7 
8 #include <errno.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <dirent.h>
12 #include <regex.h>
13 #include <fcntl.h> //Definition of AT_* constants
14 #ifndef __APPLE__
15 #define GCC_VERSION (__GNUC__ * 10000 \
16  + __GNUC_MINOR__ * 100 \
17  + __GNUC_PATCHLEVEL__)
18 # if GCC_VERSION <= 60200
19 # include <asm-generic/errno-base.h>
20 # endif
21 #endif
22 
23 #include <time.h>
24 #include <ctime>
25 
26 #include <sys/types.h>
27 #include <unistd.h>
28 
29 // #include <cerrno>
30 #include <iostream>
31 
32 
33 #include "string_filename.h"
34 
35 #include "string_system.h"
36 
37 /* From https://nicolasj.developpez.com/articles/regex/
38 
39 [:digit:] 0-9
40 [:alpha:] A-Za-z
41 [:alnum:] 0-9A-Za-z
42 [:cntrl:] Les caractères de contrôles (code ASCII 0177 et inférieur à 040)
43 [:print:] Les caractères imprimables
44 [:graph:] Idem [:print:] sans l'espace
45 [:lower:] a-z
46 [:upper:] A-Z
47 [:punct:] Ni [:cntrl:] ni [:alnum:]
48 [:space:] \n\t\r\f
49 [:xdigit:] 0-9a-fA-F nombres hexadécimaux
50 
51 Ces définitions concordent avec celles que l'on trouve dans le fichier d'en-tête ctype.h. Le point '.' permet de reconnaître n'importe quel caractère. Il est aussi possible de préciser le nombre de répétitions que l'on souhaite pour un élément :
52 
53 Opérateurs Signification
54 ? L'élément est répété, au plus une fois
55 * L'élément est présent 0 ou plus de fois
56 + L'élément est présent au moins une fois
57 {n} L'élément est présent exactement n fois
58 {n,} L'élément est présent au moins n fois
59 {n,m} L'élément est présent entre n et m fois
60 
61 Un élément est un groupe délimité par des crochets qui sont optionnels si le groupe ne comporte qu'un élément. Voici un exemple pour reconnaître si une chaîne contient trois 'a' consécutifs :
62 
63 Sélectionnez
64 
65 [a]{3}
66 
67 L'opposé d'une expression est obtenu en la faisant précéder par le caractère '^'. Si l'on souhaite donner le choix entre deux expressions, il suffit de les séparer par le caractère '|'.
68 Ce même caractère peut être placé au début de l'expression régulière pour préciser que la chaîne à analyser doit commencer par l'élément suivant :
69 
70 Sélectionnez
71 
72 ^[A-Z]
73 
74 Précise que la chaîne doit commencer par une lettre majuscule. Le caractère '$' a le même rôle, mais cette fois en fin de chaîne.
75 Pour finir, voici la liste des méta caractères ainsi que la manière de les échapper :
76 
77 Méta caractères Echappés en
78  ? \?
79  + \+
80  . \.
81  * \*
82  { \{
83  | \|
84  ( \(
85  ) \)
86 */
87 
88 
90 
94 bool isStringMatchRegex(const std::string & str, const std::string & expression){
95  if(str.size() == 0lu || expression.size() == 0lu){return false;}
96  int err;
97  regex_t preg;
98  const char *str_request = str.c_str();
99  const char *str_regex = expression.c_str();
100  err = regcomp(&preg, str_regex, 0); //REG_NOSUB | REG_EXTENDED
101  if(err != 0) return false;
102  int match = regexec(&preg, str_request, 0, NULL, 0);
103  regfree (&preg);
104  if(match == 0){return true;}
105  else{return false;}//if (match == REG_NOMATCH){return false;}
106 // else{
107 // char *text;
108 // long unsigned int size;
109 // size = regerror (err, &preg, NULL, 0);
110 // text = new char[size];
111 // if (text){
112 // regerror (err, &preg, text, size);
113 // fprintf (stderr, "isStringMatchRegex : %s\n", text);
114 // delete [] text;
115 // }else{
116 // fprintf (stderr, "isStringMatchRegex : Memoire insuffisante\n");
117 // }
118 // return false;
119 // }
120 }
121 
123 
126 void getListFileInCurrentDir(std::list<std::string> & listFile, const std::string & expr){
127  char * curr_dir = getenv("PWD");
128  if(NULL == curr_dir){
129  printf("getListFileInCurrentDir : Could not get the working directory\n");
130  return;
131  }
132  // Open the current directory
133  DIR * dp = opendir((const char*)curr_dir);
134  if(NULL == dp){
135  printf("getListFileInCurrentDir : Could not open the working directory\n");
136  return;
137  }
138  dirent * dptr = readdir(dp);
139  while(NULL != dptr){
140  if(isStringMatchRegex(std::string(dptr->d_name), expr)) listFile.push_back(std::string(dptr->d_name));
141  dptr = readdir(dp);
142  }
143 }
144 
146 
150 bool getListFileInDir(std::list<std::string> & listFile, const std::string & dirName, const std::string & expr){
151  // Open the current directory
152  DIR * dp = opendir(dirName.c_str());
153  if(NULL == dp){
154 // printf("getListFileInDir : Could not open the working directory\n");
155  return false;
156  }
157  dirent * dptr = readdir(dp);
158  while(NULL != dptr){
159  if(isStringMatchRegex(std::string(dptr->d_name), expr)) listFile.push_back(std::string(dptr->d_name));
160  std::cout << "getListFileInDir : '" << std::string(dptr->d_name) << "'"<< std::endl;
161  dptr = readdir(dp);
162  }
163  closedir(dp);
164  return true;
165 }
166 
168 
171 bool getListAllFileInDir(std::list<std::string> & listFile, const std::string & dirName){
172  // Open the current directory
173  DIR * dp = opendir(dirName.c_str());
174  if(NULL == dp){
175  return false;
176  }
177  dirent * dptr = readdir(dp);
178  while(NULL != dptr){
179  std::string fileName(dptr->d_name);
180  if(fileName != ".." && fileName != "."){
181  listFile.push_back(fileName);
182  }
183  dptr = readdir(dp);
184  }
185  closedir(dp);
186  return true;
187 }
189 
193 void makeListArgument(std::list<std::string> & listArgument, int argc, char** argv){
194  if(argc <= 0) return;
195  for(int i(0); i < argc; ++i){
196  listArgument.push_back(argv[i]);
197  }
198 }
199 
201 
204 std::string phoenix_getenv(const std::string & varName){
205  char * curr_var = getenv(varName.c_str());
206  if(NULL == curr_var){
207  return "";
208  }else{
209  return std::string(curr_var);
210  }
211 }
212 
214 
219 bool phoenix_setenv(const std::string & name, const std::string & value, int overwrite){
220  return setenv(name.c_str(), value.c_str(), overwrite) == 0;
221 }
222 
224 
227 bool phoenix_unsetenv(const std::string & name){
228  return unsetenv(name.c_str()) == 0;
229 }
230 
232 
234 std::string getHomeDir(){
235  return phoenix_getenv("HOME");
236 }
237 
239 
242 bool createDirIfNotExist(const std::string & directoryName){
243  if(directoryName == "") return false;
244  if(isDirectoryExist(directoryName)){
245  return true;
246  }
247  int res = mkdir(directoryName.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
248  return res == 0 || res == EEXIST;
249 }
250 
252 
255 time_t getFileModificationTime(const std::string & fileName){
256  struct stat attr;
257  if(stat(fileName.c_str(), &attr) == 0){
258 #ifdef __APPLE__
259  return attr.st_mtimespec.tv_sec;
260 #else
261  return attr.st_mtim.tv_sec;
262 #endif
263  }else{
264  return -1l;
265  }
266 }
267 
269 
274 time_t getFileInDirPerTime(std::vector<std::string> & vecFile, const std::string & dirName, time_t mostRecentTime){
275  DIR * dp = opendir(dirName.c_str());
276  if(dp == NULL){return mostRecentTime;}
277  dirent * dptr = readdir(dp);
278  while(NULL != dptr){
279  if(dptr->d_type == DT_REG){ //We search for directory only
280  std::string pathName(dptr->d_name);
281  time_t fileTime = getFileModificationTime(dirName + "/" + pathName);
282  if(fileTime > mostRecentTime){
283  mostRecentTime = fileTime;
284  vecFile.push_back(pathName);
285  }
286  }
287  dptr = readdir(dp);
288  }
289  return mostRecentTime;
290 }
291 
292 
294 
296 std::string getProgramLocation(){
297  char buffer[4096];
298  ssize_t nbChar = readlink("/proc/self/exe", buffer, 2048);
299 // readlink("/proc/self/exe", buf, bufsize) (Linux)
300 // readlink("/proc/curproc/file", buf, bufsize) (FreeBSD)
301 // readlink("/proc/self/path/a.out", buf, bufsize) (Solaris)
302 
303  if(nbChar > 0l){
304  std::string outputBuf("");
305  for(ssize_t i(0l); i < nbChar; ++i){
306  outputBuf += buffer[i];
307  }
308  return outputBuf;
309  }else{
310  return "";
311  }
312 }
313 
315 
317 std::string getProgramDirectory(){
318  std::string progLoc(getProgramLocation());
319  if(progLoc != ""){
320  return getDirectory(progLoc);
321  }else{
322 #ifdef CMAKE_INSTALL_PREFIX
323  return CMAKE_INSTALL_PREFIX "/bin/";
324 #else
325  return "/usr/bin/";
326 #endif
327  }
328 }
329 
331 
333 std::string getProgramPrefix(){
335 }
336 
338 
341 std::string phoenix_popen(const std::string & command){
342  if(command == ""){return "";}
343  FILE * fp = popen(command.c_str(), "r");
344  if(fp == NULL){
345  std::cerr << "phoenix_popen : cannot get result of command '"<<command<<"'" << std::endl;
346  return "";
347  }
348  std::string resultCommand(getFileContent(fp));
349  pclose(fp);
350  return resultCommand;
351 }
352 
354 
358 int phoenix_popen(std::string & executionLog, const std::string & command){
359  executionLog = "";
360  if(command == ""){return -1;}
361  FILE * fp = popen(command.c_str(), "r");
362  if(fp == NULL){
363  std::cerr << "phoenix_popen : cannot get result of command '"<<command<<"'" << std::endl;
364  return -1;
365  }
366  executionLog = getFileContent(fp);
367  return pclose(fp);
368 }
369 
371 
376 bool phoenix_popen(const std::string & executionLogFile, const std::string & command, bool onlyLogOnFail){
377  std::string executionLog("");
378  bool b(phoenix_popen(executionLog, command) == 0);
379  if(!b){
380  std::cerr << "phoenix_popen : command '"<<command<<"' failed. To get more information see log '"<<executionLogFile<<"'" << std::endl;
381  }
382  if((onlyLogOnFail && !b) || !onlyLogOnFail){
383  if(!saveFileContent(executionLogFile, executionLog)){
384  std::cerr << "phoenix_popen : cannot create log file '"<<executionLogFile<<"'" << std::endl;
385  }
386  }
387  return b;
388 }
389 
391 
395 bool phoenix_chmod(const std::string & fileName, mode_t __mode){
396  bool b(chmod(fileName.c_str(), __mode) >= 0);
397  if(!b){
398  std::cerr << "phoenix_chmod : Cannot set mode of file '"<<fileName<<"'" << std::endl;
399  }
400  return b;
401 }
402 
404 
406 std::string getCurrentNodeName(){
407  return eraseCharsInStr(phoenix_popen("uname -n"), " \n\t");
408 }
409 
411 
414 void phoenix_find(std::vector<std::string> & vecFile, const std::string & path){
415  vecFile = cutStringVector(phoenix_popen("ls " + path), '\n');
416 }
417 
419 
422 std::vector<std::string> phoenix_find(const std::string & path){
423  std::vector<std::string> vecFile;
424  phoenix_find(vecFile, path);
425  return vecFile;
426 }
427 
429 
432  return clock();
433 }
434 
436 
439  return ((double)phoenix_getClock())/((double)CLOCKS_PER_SEC);
440 }
441 
443 
446  return std::time(0);
447 }
448 
450 
452 std::string phoenix_getDate(){
453  std::time_t currentTime = phoenix_getTime();
454  std::tm* now_tm = std::gmtime(&currentTime);
455  char buf[42];
456  std::strftime(buf, 42, "%Y/%m/%d : %X", now_tm);
457  return buf;
458 }
459 
461 
464  std::time_t currentTime = phoenix_getTime();
465  std::tm* now_tm = std::gmtime(&currentTime);
466  char buf[42];
467  std::strftime(buf, 42, "%Y/%m/%d-%X", now_tm);
468  return buf;
469 }
getListFileInDir
bool getListFileInDir(std::list< std::string > &listFile, const std::string &dirName, const std::string &expr)
Get the list of files in a directory.
Definition: string_system.cpp:150
getFileModificationTime
time_t getFileModificationTime(const std::string &fileName)
Get the last modification time of the given file.
Definition: string_system.cpp:255
getFileInDirPerTime
time_t getFileInDirPerTime(std::vector< std::string > &vecFile, const std::string &dirName, time_t mostRecentTime)
Get the list of most recent files in a directory.
Definition: string_system.cpp:274
phoenix_getenv
std::string phoenix_getenv(const std::string &varName)
Get the value of the given environment variable.
Definition: string_system.cpp:204
phoenix_unsetenv
bool phoenix_unsetenv(const std::string &name)
Unset a environment variable.
Definition: string_system.cpp:227
saveFileContent
bool saveFileContent(const std::string &filename, const std::string &content)
Save a string in a file.
Definition: string_filename.cpp:300
isDirectoryExist
bool isDirectoryExist(const std::string &dirName)
Says if the given direcotry exists.
Definition: string_filename.cpp:57
phoenix_getClockSec
double phoenix_getClockSec()
Get current time.
Definition: string_system.cpp:438
phoenix_setenv
bool phoenix_setenv(const std::string &name, const std::string &value, int overwrite)
Set a environment variable.
Definition: string_system.cpp:219
getFileContent
std::string getFileContent(const std::string &filename)
Get the file content in a string.
Definition: string_filename.cpp:268
isStringMatchRegex
bool isStringMatchRegex(const std::string &str, const std::string &expression)
Fonction qui dit si une chaine de caractère correspond à une expression régulière de regex.
Definition: string_system.cpp:94
phoenix_chmod
bool phoenix_chmod(const std::string &fileName, mode_t __mode)
Change the mode of a file or directory.
Definition: string_system.cpp:395
string_filename.h
createDirIfNotExist
bool createDirIfNotExist(const std::string &directoryName)
Creates a directory if it does not exist.
Definition: string_system.cpp:242
phoenix_popen
std::string phoenix_popen(const std::string &command)
Execute the given command and returns the output of this command.
Definition: string_system.cpp:341
makeListArgument
void makeListArgument(std::list< std::string > &listArgument, int argc, char **argv)
Makes the argument list of a program.
Definition: string_system.cpp:193
phoenix_getClock
time_t phoenix_getClock()
Get current time.
Definition: string_system.cpp:431
getProgramDirectory
std::string getProgramDirectory()
Get the program directory.
Definition: string_system.cpp:317
getCurrentNodeName
std::string getCurrentNodeName()
Get the name of the current node on which the program is running.
Definition: string_system.cpp:406
eraseCharsInStr
std::string eraseCharsInStr(const std::string &str, const std::string &rmchs)
copie la string str en effaçant les caractères rmchs
Definition: string_function.cpp:173
phoenix_getTime
time_t phoenix_getTime()
Get the current time of the program.
Definition: string_system.cpp:445
createReleaseCurl.str
str
Definition: createReleaseCurl.py:128
getListAllFileInDir
bool getListAllFileInDir(std::list< std::string > &listFile, const std::string &dirName)
Get the list of files in a directory.
Definition: string_system.cpp:171
getListFileInCurrentDir
void getListFileInCurrentDir(std::list< std::string > &listFile, const std::string &expr)
Function like a ls in shell.
Definition: string_system.cpp:126
phoenix_getDateCompact
std::string phoenix_getDateCompact()
Get the current date.
Definition: string_system.cpp:463
phoenix_getDate
std::string phoenix_getDate()
Get the current date.
Definition: string_system.cpp:452
getProgramLocation
std::string getProgramLocation()
Get the program location.
Definition: string_system.cpp:296
getHomeDir
std::string getHomeDir()
Gets the $HOME directory.
Definition: string_system.cpp:234
string_system.h
phoenix_find
void phoenix_find(std::vector< std::string > &vecFile, const std::string &path)
Find all files which matches the path expression (example : /path/*.cpp)
Definition: string_system.cpp:414
cutStringVector
std::vector< std::string > cutStringVector(const std::string &str, char separator)
Cut a string the the given separator char.
Definition: string_function.cpp:448
getDirectory
std::string getDirectory(const std::string &fileName)
fonction qui renvoie le dossier parent du fichier
Definition: string_filename.cpp:156
getProgramPrefix
std::string getProgramPrefix()
Get the program prefix (installation directory without /bin)
Definition: string_system.cpp:333