1 /*=========================================================================
4 Module: $RCSfile: bbtkUtilities.h,v $
6 Date: $Date: 2008/01/29 10:12:45 $
7 Version: $Revision: 1.6 $
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 "bbtkMessageManager.h"
54 /// Holds various usefull methods
55 struct BBTK_EXPORT Utilities
58 // ===================================================================================
60 // See : http://www.techbytes.ca/techbyte103.html for more O.S.
61 static inline bool FileExists(std::string strFilename)
63 struct stat stFileInfo;
67 // Attempt to get the file attributes
68 intStat = stat(strFilename.c_str(),&stFileInfo);
70 // We were able to get the file attributes
71 // so the file obviously exists.
74 // We were not able to get the file attributes.
75 // This may mean that we don't have permission to
76 // access the folder which contains this file. If you
77 // need to do that level of checking, lookup the
78 // return values of stat which will give you
79 // more details on why stat failed.
87 // ===================================================================================
89 static std::string ExtractPackageName(const std::string &name,
95 std::string::size_type slash_position = name.find_last_of("/\\");
96 if (slash_position != std::string::npos)
98 pkgname = name.substr(slash_position+1,std::string::npos);
99 path = name.substr(0,slash_position);
100 // std::cout << "F:P='"<<path<<"'"<<std::endl;//+1,std::string::npos);
107 // remove {.so | dll} if any
108 std::string::size_type dot_position = pkgname.find_last_of('.');
109 if (dot_position != std::string::npos){
110 pkgname = pkgname.substr(0,dot_position);
112 #if defined(__GNUC__)
115 // shared lib name = libbb<name>.so
117 // remove {libbb} if any
118 if (memcmp ( pkgname.c_str(), "libbb", 5) == 0) {
119 pkgname = pkgname.substr(5, pkgname.length());
122 /// \ \todo what would happen if (stupid) user names his package 'libbb' ?!?
123 /// \ --> Should be forbidden!
125 #elif defined(_WIN32)
128 // shared lib name = <name>.dll
130 // remove {bb} if any
131 if (memcmp (pkgname.c_str(), "bb", 2) == 0) {
132 pkgname = pkgname.substr(2, pkgname.length());
136 /// \ \todo what would happen if (stupid) user names his package 'bb' ?!?
137 /// \ --> Should be forbidden!
140 bbtkError("neither __GNUC__ nor _WIN32 ?!? How did you compile ?");
145 // ===================================================================================
147 static std::string ExtractScriptName(const std::string &name,
152 std::string::size_type slash_position = name.find_last_of("/\\");
153 if (slash_position != std::string::npos) {
154 pkgname =name.substr(slash_position+1,std::string::npos);
155 path = name.substr(0,slash_position);
159 // remove {.bbs } if any
160 std::string::size_type dot_position = pkgname.find_last_of('.');
161 if (dot_position != std::string::npos){
162 pkgname = pkgname.substr(0,dot_position);
167 // ===================================================================================
169 static std::string ExpandLibName(const std::string &name, bool verbose)
171 // ----- Think of expanding path name ( ./ ../ ../../ )
173 char buf[2048]; // for getcwd
174 char * currentDir = getcwd(buf, 2048);
175 std::string cwd(currentDir);
176 std::string libname(name);
177 std::string fileSeparator;
178 fileSeparator = ConfigurationFile::GetInstance().Get_file_separator();
179 // tooHigh : true is user supplies a library pathname with too many "../"
180 bool tooHigh = false;
182 //std::cout << "------------------cwd [" << cwd << "]" << std::endl;
184 if ( name[0] == '/' || name[0] == '\\' )
188 else if ( name =="." )
190 libname = cwd + fileSeparator;
193 else if (name[0] == '.' && (name[1] == '/' || name[1] == '\\') )
195 libname = cwd + fileSeparator + name.substr(2, name.length());
198 else if ( name[0] == '.' && name[1] == '.' /* && (name[2] == '/' || name[2] == '\\') */ )
200 if ( IsAtRoot(cwd) ) // hope it gets / (for Linux), C: D: (for Windows)
202 // if we are already at / or c: --> hopeless
204 std::cout << " File path [" << name << "] doesn't exist" << std::endl;
209 // iterate on ../ and go up from the current working dir!
211 bool alreadyProcessRoot = false;
213 //if (a[a.size()-1] != fileSeparator[0])
214 // a.append(fileSeparator);
215 //std::cout << "------------------a [" << a << "]" << std::endl;
217 for(;;) // wild loop !
219 std::string::size_type slash_position = cwd.find_last_of(fileSeparator);
220 if (slash_position != std::string::npos) {
221 if (slash_position == 0)
223 cwd = cwd.substr(0,slash_position/*+1*/);
224 //std::cout << "------------------cwd [" << cwd << "]" << std::endl;
230 a = a.substr(3, /*name.length()*/ a.length()); // remove ../
231 //std::cout << "------------------a [" << a << "]" << std::endl;
232 if (a == "" || alreadyProcessRoot)
235 std::cout << " File path : [" << name << "] doesn't exist" << std::endl;
239 // std::string b = cwd + a;
241 char c = cwd[cwd.size()-1];
242 if (c != '/' && c != '\\' )
243 libname += fileSeparator;
246 if ( a[0] != '.' ) // if . (probabely ../), loop again
250 alreadyProcessRoot = true;
252 } // end iterating on ../
254 //std::cout << "------------------out of loop]" << std::endl;
259 } // ----- End of expanding path name ( ./ ../ ../../ )
261 std::cout <<"* ERROR in ExpandLibName : should never get here!" << std::endl;
263 return(""); // Will never get here!
266 // ===================================================================================
268 static std::string MakeLibnameFromPath(std::string path, std::string pkgname)
270 std::string libname = path;
271 char c = path[path.size()-1];
272 #if defined(__GNUC__)
280 #elif defined(_WIN32)
282 libname = path+"\\bb";
289 // ===================================================================================
291 static inline std::string MakePkgnameFromPath(std::string path, std::string pkgname, bool addExt)
293 std::string libname = path;
294 char c = path[path.size()-1];
295 if (c != '/' && c != '\\')
297 libname += ConfigurationFile::GetInstance().Get_file_separator ();
302 int l = libname.size();
305 if (libname.substr(l-4, 4) != ".bbs")
307 libname = libname + ".bbs";
314 // ===================================================================================
316 static inline bool IsAtRoot(std::string cwd)
318 if ( cwd == "/" // hope it gets / (for Linux)
319 || (cwd.size() <= 3 && cwd[1] == ':') ) // hope it gets C: D: (for Windows)
325 // ===================================================================================
327 static bool IsDirectory(std::string const &dirName)
331 if ( stat(dirName.c_str(), &fs) == 0 )
334 return ((fs.st_mode & _S_IFDIR) != 0);
336 return S_ISDIR(fs.st_mode);
345 // ===================================================================================
347 static inline void SplitAroundFirstDot( const std::string& in,
351 std::string delimiter = ".";
352 std::string::size_type pos = in.find_first_of(delimiter);
353 if (std::string::npos != pos)
355 left = in.substr(0,pos);
356 right = in.substr(pos+1,in.size());
361 // bbtkError(in<<" : expected 'a.b' format but no dot found");
367 // ===================================================================================
369 static inline std::string get_file_name(const std::string& s)
371 std::string::size_type slash_position = s.find_last_of("/\\");
372 if (slash_position != std::string::npos)
374 return s.substr(slash_position+1,std::string::npos);
382 // ===================================================================================
384 * \brief Explore a directory with possibility of recursion
385 * return number of files read
386 * @param dirpath directory to explore
387 * @param recursive whether we want recursion or not
389 static int Explore(std::string const &dirpath, bool recursive, std::vector<std::string> &Filenames)
391 int numberOfFiles = 0;
392 std::string fileName;
394 std::string dirName = dirpath;
397 WIN32_FIND_DATA fileData;
398 HANDLE hFile = FindFirstFile((dirName+"*").c_str(), &fileData);
400 for(BOOL b = (hFile != INVALID_HANDLE_VALUE); b;
401 b = FindNextFile(hFile, &fileData))
403 fileName = fileData.cFileName;
404 if ( fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
406 // Need to check for . and .. to avoid infinite loop
407 if ( fileName != "." && fileName != ".." && recursive )
409 numberOfFiles += Explore(dirName+ "\\"+fileName,recursive,Filenames);
414 Filenames.push_back(dirName+fileName);
418 DWORD dwError = GetLastError();
419 if (hFile != INVALID_HANDLE_VALUE)
421 if (dwError != ERROR_NO_MORE_FILES)
424 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
425 FORMAT_MESSAGE_FROM_SYSTEM|
426 FORMAT_MESSAGE_IGNORE_INSERTS,
428 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
429 (LPTSTR) &lpMsgBuf,0,NULL);
431 // ErrorMacro("FindNextFile error. Error is " << (char *)lpMsgBuf
432 // <<" for the directory : "<<dirName);
438 // Real POSIX implementation: scandir is a BSD extension only, and doesn't
439 // work on debian for example
440 //std::cout <<"in Explor dirname[" << dirName << "]" << std::endl;
441 DIR* dir = opendir(dirName.c_str());
446 //std::cout <<"Open OK" << std::endl;
447 // According to POSIX, the dirent structure contains a field char d_name[]
448 // of unspecified size, with at most NAME_MAX characters preceeding the
449 // terminating null character. Use of other fields will harm the porta-
450 // bility of your programs.
454 for (d = readdir(dir); d; d = readdir(dir))
456 fileName = dirName + "/" + d->d_name;
457 //std::cout <<"in Explor filename[" << fileName << "]" << std::endl;
458 if( stat(fileName.c_str(), &buf) != 0 )
460 //ErrorMacro( strerror(errno) );
462 if ( S_ISREG(buf.st_mode) ) //is it a regular file?
464 Filenames.push_back( fileName );
467 else if ( S_ISDIR(buf.st_mode) ) //directory?
469 if ( d->d_name[0] != '.' && recursive ) //we also skip hidden files
471 numberOfFiles += Explore( fileName, recursive, Filenames);
476 //ErrorMacro( "Unexpected error" );
480 if( closedir(dir) != 0 )
482 // ErrorMacro( strerror(errno) );
486 return numberOfFiles;
490 //========================================================================
491 // Usefull functions for html generation
492 //========================================================================
494 static inline void replace( std::string& str,
495 const std::string& from,
496 const std::string& to )
499 string::size_type pos = str.find( from );
500 while ( pos != string::npos )
502 str.replace( pos, from.size(), to );
503 pos = str.find( from, pos+from.size()-1 );
506 //========================================================================
508 static inline void html_format(std::string& str)
510 replace( str, "&", "&" );
511 replace( str, "<", "<" );
512 replace( str, ">", ">" );
514 //========================================================================
520 #endif //#ifndef __bbtkUtilities_h_INCLUDED__