1 /*=========================================================================
3 Module: $RCSfile: bbtkUtilities.cxx,v $
5 Date: $Date: 2008/12/12 10:20:48 $
6 Version: $Revision: 1.10 $
7 =========================================================================*/
9 /* ---------------------------------------------------------------------
11 * Copyright (c) CREATIS-LRMN (Centre de Recherche en Imagerie Medicale)
12 * Authors : Eduardo Davila, Laurent Guigues, Jean-Pierre Roux
14 * This software is governed by the CeCILL-B license under French law and
15 * abiding by the rules of distribution of free software. You can use,
16 * modify and/ or redistribute the software under the terms of the CeCILL-B
17 * license as circulated by CEA, CNRS and INRIA at the following URL
18 * http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
19 * or in the file LICENSE.txt.
21 * As a counterpart to the access to the source code and rights to copy,
22 * modify and redistribute granted by the license, users are provided only
23 * with a limited warranty and the software's author, the holder of the
24 * economic rights, and the successive licensors have only limited
27 * The fact that you are presently reading this means that you have had
28 * knowledge of the CeCILL-B license and that you accept its terms.
29 * ------------------------------------------------------------------------ */
32 #include "bbtkUtilities.h"
33 #include "bbtkMessageManager.h"
42 // ======================================================================
43 // See : http://www.techbytes.ca/techbyte103.html for more O.S.
44 bool Utilities::FileExists(std::string strFilename)
46 struct stat stFileInfo;
50 // Attempt to get the file attributes
51 intStat = stat(strFilename.c_str(),&stFileInfo);
54 // We were able to get the file attributes
55 // so the file obviously exists.
60 // We were not able to get the file attributes.
61 // This may mean that we don't have permission to
62 // access the folder which contains this file. If you
63 // need to do that level of checking, lookup the
64 // return values of stat which will give you
65 // more details on why stat failed.
73 // =====================================================================
75 std::string Utilities::ExtractPackageName(const std::string &name,
81 std::string::size_type slash_position = name.find_last_of("/\\");
82 if (slash_position != std::string::npos)
84 pkgname = name.substr(slash_position+1,std::string::npos);
85 path = name.substr(0,slash_position);
86 // std::cout << "F:P='"<<path<<"'"<<std::endl;//+1,std::string::npos);
93 // remove {.so | dll} if any
94 std::string::size_type dot_position = pkgname.find_last_of('.');
95 if (dot_position != std::string::npos){
96 pkgname = pkgname.substr(0,dot_position);
101 // shared lib name = libbb<name>.so
103 // remove {libbb} if any
104 if (memcmp ( pkgname.c_str(), "libbb", 5) == 0) {
105 pkgname = pkgname.substr(5, pkgname.length());
108 /// \ \todo what would happen if (stupid) user names his package 'libbb' ?!?
109 /// \ --> Should be forbidden!
111 #elif defined(_WIN32)
114 // shared lib name = <name>.dll
116 // EED Problem loading package call bbtkTools
117 // // remove {bb} if any
118 if (memcmp (pkgname.c_str(), "bb", 2) == 0) {
119 pkgname = pkgname.substr(2, pkgname.length());
123 /// \ \todo what would happen if (stupid) user names his package 'bb' ?!?
124 /// \ --> Should be forbidden!
127 bbtkError("neither __GNUC__ nor _WIN32 ?!? How did you compile ?");
132 //=====================================================================
133 std::string Utilities::ExtractScriptName(const std::string &name,
138 std::string::size_type slash_position = name.find_last_of("/\\");
139 if (slash_position != std::string::npos) {
140 pkgname =name.substr(slash_position+1,std::string::npos);
141 path = name.substr(0,slash_position);
145 // remove {.bbs } if any
146 std::string::size_type dot_position = pkgname.find_last_of('.');
147 if (dot_position != std::string::npos){
148 pkgname = pkgname.substr(0,dot_position);
153 // ========================================================================
155 std::string Utilities::ExpandLibName(const std::string &name, bool verbose)
157 // ----- Think of expanding path name ( ./ ../ ../../ )
159 char buf[2048]; // for getcwd
160 char * currentDir = getcwd(buf, 2048);
161 std::string cwd(currentDir);
162 std::string libname(name);
163 std::string fileSeparator;
164 fileSeparator = ConfigurationFile::GetInstance().Get_file_separator();
165 // tooHigh : true is user supplies a library pathname with too many "../"
166 bool tooHigh = false;
168 //std::cout << "------------------cwd [" << cwd << "] name [" << name << "]" << std::endl;
170 if ( name[0] == '/' || name[1] == ':' ) // Linux or Windows absolute name
174 else if ( name =="." )
176 libname = cwd + fileSeparator;
179 else if (name[0] == '.' && (name[1] == '/' || name[1] == '\\') )
181 libname = cwd + fileSeparator + name.substr(2, name.length());
184 else if ( name[0] == '.' && name[1] == '.' /* && (name[2] == '/' || name[2] == '\\') */ )
186 if ( IsAtRoot(cwd) ) // hope it gets / (for Linux), C: D: (for Windows)
188 // if we are already at / or c: --> hopeless
190 std::cout << " File path [" << name << "] doesn't exist" << std::endl;
195 // iterate on ../ and go up from the current working dir!
197 bool alreadyProcessRoot = false;
199 //if (a[a.size()-1] != fileSeparator[0])
200 // a.append(fileSeparator);
201 //std::cout << "------------------a [" << a << "]" << std::endl;
203 for(;;) // wild loop !
205 std::string::size_type slash_position = cwd.find_last_of(fileSeparator);
206 if (slash_position != std::string::npos) {
207 if (slash_position == 0)
209 cwd = cwd.substr(0,slash_position/*+1*/);
210 //std::cout << "------------------cwd [" << cwd << "]" << std::endl;
216 a = a.substr(3, /*name.length()*/ a.length()); // remove ../
217 //std::cout << "------------------a [" << a << "]" << std::endl;
218 if (a == "" || alreadyProcessRoot)
221 std::cout << " File path : [" << name << "] doesn't exist" << std::endl;
225 // std::string b = cwd + a;
227 char c = cwd[cwd.size()-1];
228 if (c != '/' && c != '\\' )
229 libname += fileSeparator;
232 if ( a[0] != '.' ) // if . (probabely ../), loop again
236 alreadyProcessRoot = true;
238 } // end iterating on ../
240 //std::cout << "------------------out of loop]" << std::endl;
245 } // ----- End of expanding path name ( ./ ../ ../../ )
247 std::cout <<"* ERROR in ExpandLibName : should never get here!" << std::endl;
249 return(""); // Will never get here!
252 // ===================================================================================
254 std::string Utilities::MakeLibnameFromPath(std::string path, std::string pkgname)
256 std::string libname = path;
257 char c = path[path.size()-1];
258 #if defined(__GNUC__)
270 #elif defined(_WIN32)
272 libname = path+"\\bb";
279 // ===================================================================================
281 std::string Utilities::MakePkgnameFromPath(std::string path, std::string pkgname, bool addExt)
283 std::string libname = path;
284 char c = path[path.size()-1];
285 if (c != '/' && c != '\\')
287 libname += ConfigurationFile::GetInstance().Get_file_separator ();
292 int l = libname.size();
295 if (libname.substr(l-4, 4) != ".bbs")
297 libname = libname + ".bbs";
304 // =======================================================================
305 /// Builds the complete path to the file 'name' located
306 /// in user settings dir, e.g. /home/username/.bbtk/
307 std::string Utilities::MakeUserSettingsFullFileName(const std::string& name)
309 #if defined(__GNUC__)
310 std::string str_home(getenv("HOME"));
311 #elif defined(_WIN32)
312 std::string str_home(getenv("USERPROFILE"));
314 std::string fullname = str_home + "/.bbtk/" + name;
315 Utilities::replace( fullname,
316 INVALID_FILE_SEPARATOR ,
317 VALID_FILE_SEPARATOR);
323 //========================================================================
325 bool Utilities::IsAtRoot(std::string cwd)
327 if ( cwd == "/" // hope it gets / (for Linux)
328 || (cwd.size() <= 3 && cwd[1] == ':') ) // hope it gets C: D: (for Windows)
334 // ======================================================================
336 bool Utilities::IsDirectory(std::string const &dirName)
340 if ( stat(dirName.c_str(), &fs) == 0 )
343 return ((fs.st_mode & _S_IFDIR) != 0);
345 return S_ISDIR(fs.st_mode);
354 // ===================================================================================
356 void Utilities::SplitAroundFirstDot( const std::string& in,
360 std::string delimiter = ".";
361 std::string::size_type pos = in.find_first_of(delimiter);
362 if (std::string::npos != pos)
364 left = in.substr(0,pos);
365 right = in.substr(pos+1,in.size());
372 bbtkGlobalError("Token '"<<in<<"' : expected 'a.b' format but no dot found");
375 //=======================================================================
376 void Utilities::SplitString ( const std::string& str,
377 const std::string& delimiters,
378 std::vector<std::string>& tokens)
380 // Skip delimiters at beginning.
381 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
382 // Find first delimiter.
383 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
385 while (std::string::npos != pos || std::string::npos != lastPos)
387 // Found a token, add it to the vector.
388 tokens.push_back(str.substr(lastPos, pos - lastPos));
389 // Skip delimiters. Note the "not_of"
390 lastPos = str.find_first_not_of(delimiters, pos);
391 // Find next delimiter
392 pos = str.find_first_of(delimiters, lastPos);
396 //=======================================================================
399 // ===================================================================================
401 std::string Utilities::get_file_name(const std::string& s)
403 std::string::size_type slash_position = s.find_last_of("/\\");
404 if (slash_position != std::string::npos)
406 return s.substr(slash_position+1,std::string::npos);
414 // ===================================================================================
416 * \brief Explore a directory with possibility of recursion
417 * return number of files read
418 * @param dirpath directory to explore
419 * @param recursive whether we want recursion or not
421 int Utilities::Explore(std::string const &dirpath, bool recursive, std::vector<std::string> &Filenames)
423 int numberOfFiles = 0;
424 std::string fileName;
426 std::string dirName = dirpath;
429 WIN32_FIND_DATA fileData;
430 HANDLE hFile = FindFirstFile((dirName+"\\*").c_str(), &fileData);
432 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
433 b = FindNextFile(hFile, &fileData))
435 fileName = fileData.cFileName;
436 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
438 // Need to check for . and .. to avoid infinite loop
439 if ( fileName != "." && fileName != ".." && recursive )
441 numberOfFiles += Explore(dirName+ "\\"+fileName,recursive,Filenames);
446 Filenames.push_back(dirName+"\\"+fileName);
450 DWORD dwError = GetLastError();
451 if (hFile != INVALID_HANDLE_VALUE)
453 if (dwError != ERROR_NO_MORE_FILES)
456 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
457 FORMAT_MESSAGE_FROM_SYSTEM|
458 FORMAT_MESSAGE_IGNORE_INSERTS,
460 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
461 (LPTSTR) &lpMsgBuf,0,NULL);
463 // ErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
464 // <<" for the directory : "<<dirName);
470 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
471 // work on debian for example
472 //std::cout <<"in Explor dirname[" << dirName << "]" << std::endl;
473 DIR* dir = opendir(dirName.c_str());
478 //std::cout <<"Open OK" << std::endl;
479 // According to POSIX, the dirent structure contains a field char d_name[]
480 // of unspecified size, with at most NAME_MAX characters preceeding the
481 // terminating null character. Use of other fields will harm the porta-
482 // bility of your programs.
486 for (d = readdir(dir); d; d = readdir(dir))
488 fileName = dirName + "/" + d->d_name;
489 //std::cout <<"in Explor filename[" << fileName << "]" << std::endl;
490 if( stat(fileName.c_str(), &buf) != 0 )
492 //ErrorMacro( strerror(errno) );
494 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
496 Filenames.push_back( fileName );
499 else if ( S_ISDIR(buf.st_mode) ) //directory?
501 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
503 numberOfFiles += Explore( fileName, recursive, Filenames);
508 //ErrorMacro( "Unexpected error" );
512 if( closedir(dir) != 0 )
514 // ErrorMacro( strerror(errno) );
518 return numberOfFiles;
523 //=======================================================================
524 // Replaces substrings "\\n" by a real carriage return "\n"
525 void Utilities::SubsBackslashN ( std::string& s )
527 std::string ss("\\n");
528 std::string::size_type pos = 0;
530 const char* cr = "\n";
531 while ( pos != std::string::npos )
533 s.replace(pos,2,cr,1);
534 pos = s.find(ss, pos-1);
537 //=======================================================================
541 bool Utilities::loosematch(std::string stdLine,std::string stdOptions)
544 std::vector<std::string> tokens;
545 SplitString ( stdOptions,"|", tokens);
546 int i,size=tokens.size();
547 for (i=0; i<size; i++)
550 if ( strcmpi(stdLine.c_str(),tokens[i].c_str())==0)
555 if ( strcasecmp(stdLine.c_str(),tokens[i].c_str())==0)