1 /*=========================================================================
4 Module: $RCSfile: bbtkUtilities.h,v $
6 Date: $Date: 2008/02/08 14:58:31 $
7 Version: $Revision: 1.11 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See doc/license.txt or
11 http://www.creatis.insa-lyon.fr/Public/bbtk/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
22 * \brief struct bbtk::Utilities : various usefull methods
26 * \class bbtk::Utilities
27 * \brief various usefull methods
30 #ifndef __bbtkUtilities_h_INCLUDED__
31 #define __bbtkUtilities_h_INCLUDED__
33 #include "bbtkConfigurationFile.h"
34 #include "bbtkSystem.h"
37 #ifdef CMAKE_HAVE_TERMIOS_H
39 #define BBTK_USE_TERMIOS_BASED_PROMPT
47 #include <sys/types.h>
50 #include <cctype> // std::toupper
51 //#include "bbtkMessageManager.h"
55 /// Holds various usefull methods
56 struct BBTK_EXPORT Utilities
59 // ===================================================================================
61 // See : http://www.techbytes.ca/techbyte103.html for more O.S.
62 static inline bool FileExists(std::string strFilename)
64 struct stat stFileInfo;
68 // Attempt to get the file attributes
69 intStat = stat(strFilename.c_str(),&stFileInfo);
71 // We were able to get the file attributes
72 // so the file obviously exists.
75 // We were not able to get the file attributes.
76 // This may mean that we don't have permission to
77 // access the folder which contains this file. If you
78 // need to do that level of checking, lookup the
79 // return values of stat which will give you
80 // more details on why stat failed.
88 // ===================================================================================
90 static std::string ExtractPackageName(const std::string &name,
96 std::string::size_type slash_position = name.find_last_of("/\\");
97 if (slash_position != std::string::npos)
99 pkgname = name.substr(slash_position+1,std::string::npos);
100 path = name.substr(0,slash_position);
101 // std::cout << "F:P='"<<path<<"'"<<std::endl;//+1,std::string::npos);
108 // remove {.so | dll} if any
109 std::string::size_type dot_position = pkgname.find_last_of('.');
110 if (dot_position != std::string::npos){
111 pkgname = pkgname.substr(0,dot_position);
113 #if defined(__GNUC__)
116 // shared lib name = libbb<name>.so
118 // remove {libbb} if any
119 if (memcmp ( pkgname.c_str(), "libbb", 5) == 0) {
120 pkgname = pkgname.substr(5, pkgname.length());
123 /// \ \todo what would happen if (stupid) user names his package 'libbb' ?!?
124 /// \ --> Should be forbidden!
126 #elif defined(_WIN32)
129 // shared lib name = <name>.dll
131 // remove {bb} if any
132 if (memcmp (pkgname.c_str(), "bb", 2) == 0) {
133 pkgname = pkgname.substr(2, pkgname.length());
137 /// \ \todo what would happen if (stupid) user names his package 'bb' ?!?
138 /// \ --> Should be forbidden!
141 bbtkError("neither __GNUC__ nor _WIN32 ?!? How did you compile ?");
146 // ===================================================================================
148 static std::string ExtractScriptName(const std::string &name,
153 std::string::size_type slash_position = name.find_last_of("/\\");
154 if (slash_position != std::string::npos) {
155 pkgname =name.substr(slash_position+1,std::string::npos);
156 path = name.substr(0,slash_position);
160 // remove {.bbs } if any
161 std::string::size_type dot_position = pkgname.find_last_of('.');
162 if (dot_position != std::string::npos){
163 pkgname = pkgname.substr(0,dot_position);
168 // ===================================================================================
170 static std::string ExpandLibName(const std::string &name, bool verbose)
172 // ----- Think of expanding path name ( ./ ../ ../../ )
174 char buf[2048]; // for getcwd
175 char * currentDir = getcwd(buf, 2048);
176 std::string cwd(currentDir);
177 std::string libname(name);
178 std::string fileSeparator;
179 fileSeparator = ConfigurationFile::GetInstance().Get_file_separator();
180 // tooHigh : true is user supplies a library pathname with too many "../"
181 bool tooHigh = false;
183 //std::cout << "------------------cwd [" << cwd << "] name [" << name << "]" << std::endl;
185 if ( name[0] == '/' || name[1] == ':' ) // Linux or Windows absolute name
189 else if ( name =="." )
191 libname = cwd + fileSeparator;
194 else if (name[0] == '.' && (name[1] == '/' || name[1] == '\\') )
196 libname = cwd + fileSeparator + name.substr(2, name.length());
199 else if ( name[0] == '.' && name[1] == '.' /* && (name[2] == '/' || name[2] == '\\') */ )
201 if ( IsAtRoot(cwd) ) // hope it gets / (for Linux), C: D: (for Windows)
203 // if we are already at / or c: --> hopeless
205 std::cout << " File path [" << name << "] doesn't exist" << std::endl;
210 // iterate on ../ and go up from the current working dir!
212 bool alreadyProcessRoot = false;
214 //if (a[a.size()-1] != fileSeparator[0])
215 // a.append(fileSeparator);
216 //std::cout << "------------------a [" << a << "]" << std::endl;
218 for(;;) // wild loop !
220 std::string::size_type slash_position = cwd.find_last_of(fileSeparator);
221 if (slash_position != std::string::npos) {
222 if (slash_position == 0)
224 cwd = cwd.substr(0,slash_position/*+1*/);
225 //std::cout << "------------------cwd [" << cwd << "]" << std::endl;
231 a = a.substr(3, /*name.length()*/ a.length()); // remove ../
232 //std::cout << "------------------a [" << a << "]" << std::endl;
233 if (a == "" || alreadyProcessRoot)
236 std::cout << " File path : [" << name << "] doesn't exist" << std::endl;
240 // std::string b = cwd + a;
242 char c = cwd[cwd.size()-1];
243 if (c != '/' && c != '\\' )
244 libname += fileSeparator;
247 if ( a[0] != '.' ) // if . (probabely ../), loop again
251 alreadyProcessRoot = true;
253 } // end iterating on ../
255 //std::cout << "------------------out of loop]" << std::endl;
260 } // ----- End of expanding path name ( ./ ../ ../../ )
262 std::cout <<"* ERROR in ExpandLibName : should never get here!" << std::endl;
264 return(""); // Will never get here!
267 // ===================================================================================
269 static std::string MakeLibnameFromPath(std::string path, std::string pkgname)
271 std::string libname = path;
272 char c = path[path.size()-1];
273 #if defined(__GNUC__)
281 #elif defined(_WIN32)
283 libname = path+"\\bb";
290 // ===================================================================================
292 static inline std::string MakePkgnameFromPath(std::string path, std::string pkgname, bool addExt)
294 std::string libname = path;
295 char c = path[path.size()-1];
296 if (c != '/' && c != '\\')
298 libname += ConfigurationFile::GetInstance().Get_file_separator ();
303 int l = libname.size();
306 if (libname.substr(l-4, 4) != ".bbs")
308 libname = libname + ".bbs";
315 // ===================================================================================
317 static inline bool IsAtRoot(std::string cwd)
319 if ( cwd == "/" // hope it gets / (for Linux)
320 || (cwd.size() <= 3 && cwd[1] == ':') ) // hope it gets C: D: (for Windows)
326 // ===================================================================================
328 static bool IsDirectory(std::string const &dirName)
332 if ( stat(dirName.c_str(), &fs) == 0 )
335 return ((fs.st_mode & _S_IFDIR) != 0);
337 return S_ISDIR(fs.st_mode);
346 // ===================================================================================
348 static inline void SplitAroundFirstDot( const std::string& in,
352 std::string delimiter = ".";
353 std::string::size_type pos = in.find_first_of(delimiter);
354 if (std::string::npos != pos)
356 left = in.substr(0,pos);
357 right = in.substr(pos+1,in.size());
362 // bbtkError(in<<" : expected 'a.b' format but no dot found");
367 //=======================================================================
368 static inline void SplitString ( const std::string& str,
369 const std::string& delimiters,
370 std::vector<std::string>& tokens)
372 // Skip delimiters at beginning.
373 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
374 // Find first delimiter.
375 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
377 while (std::string::npos != pos || std::string::npos != lastPos)
379 // Found a token, add it to the vector.
380 tokens.push_back(str.substr(lastPos, pos - lastPos));
381 // Skip delimiters. Note the "not_of"
382 lastPos = str.find_first_not_of(delimiters, pos);
383 // Find next delimiter
384 pos = str.find_first_of(delimiters, lastPos);
388 //=======================================================================
391 // ===================================================================================
393 static inline std::string get_file_name(const std::string& s)
395 std::string::size_type slash_position = s.find_last_of("/\\");
396 if (slash_position != std::string::npos)
398 return s.substr(slash_position+1,std::string::npos);
406 // ===================================================================================
408 * \brief Explore a directory with possibility of recursion
409 * return number of files read
410 * @param dirpath directory to explore
411 * @param recursive whether we want recursion or not
413 static int Explore(std::string const &dirpath, bool recursive, std::vector<std::string> &Filenames)
415 int numberOfFiles = 0;
416 std::string fileName;
418 std::string dirName = dirpath;
421 WIN32_FIND_DATA fileData;
422 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
424 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
425 b = FindNextFile(hFile, &fileData))
427 fileName = fileData.cFileName;
428 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
430 // Need to check for . and .. to avoid infinite loop
431 if ( fileName != "." && fileName != ".." && recursive )
433 numberOfFiles += Explore(dirName+ "\\"+fileName,recursive,Filenames);
438 Filenames.push_back(dirName+fileName);
442 DWORD dwError = GetLastError();
443 if (hFile != INVALID_HANDLE_VALUE)
445 if (dwError != ERROR_NO_MORE_FILES)
448 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
449 FORMAT_MESSAGE_FROM_SYSTEM|
450 FORMAT_MESSAGE_IGNORE_INSERTS,
452 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
453 (LPTSTR) &lpMsgBuf,0,NULL);
455 // ErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
456 // <<" for the directory : "<<dirName);
462 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
463 // work on debian for example
464 //std::cout <<"in Explor dirname[" << dirName << "]" << std::endl;
465 DIR* dir = opendir(dirName.c_str());
470 //std::cout <<"Open OK" << std::endl;
471 // According to POSIX, the dirent structure contains a field char d_name[]
472 // of unspecified size, with at most NAME_MAX characters preceeding the
473 // terminating null character. Use of other fields will harm the porta-
474 // bility of your programs.
478 for (d = readdir(dir); d; d = readdir(dir))
480 fileName = dirName + "/" + d->d_name;
481 //std::cout <<"in Explor filename[" << fileName << "]" << std::endl;
482 if( stat(fileName.c_str(), &buf) != 0 )
484 //ErrorMacro( strerror(errno) );
486 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
488 Filenames.push_back( fileName );
491 else if ( S_ISDIR(buf.st_mode) ) //directory?
493 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
495 numberOfFiles += Explore( fileName, recursive, Filenames);
500 //ErrorMacro( "Unexpected error" );
504 if( closedir(dir) != 0 )
506 // ErrorMacro( strerror(errno) );
510 return numberOfFiles;
514 //========================================================================
515 // Usefull functions for html generation
516 //========================================================================
518 static inline void replace( std::string& str,
519 const std::string& from,
520 const std::string& to )
523 string::size_type pos = str.find( from );
524 while ( pos != string::npos )
526 str.replace( pos, from.size(), to );
527 pos = str.find( from, pos+from.size()-1 );
530 //========================================================================
532 static inline void html_format(std::string& str)
534 replace( str, "&", "&" );
535 replace( str, "<", "<" );
536 replace( str, ">", ">" );
540 //========================================================================
541 // Usefull functions OPTIONS string
542 //========================================================================
545 static bool loosematch(std::string stdLine,std::string stdOptions);
555 #endif //#ifndef __bbtkUtilities_h_INCLUDED__