Put a flag in that will stop system tools from deleting system environment memory...
[cmake.git] / Source / kwsys / SystemTools.cxx
blob46cc83c68246cdd7913cd199dcfdcc08d0ed8115
1 /*=========================================================================
3 Program: KWSys - Kitware System Library
4 Module: $RCSfile: SystemTools.cxx,v $
6 Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.
7 See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
9 This software is distributed WITHOUT ANY WARRANTY; without even
10 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11 PURPOSE. See the above copyright notices for more information.
13 =========================================================================*/
14 #include "kwsysPrivate.h"
15 #include KWSYS_HEADER(RegularExpression.hxx)
16 #include KWSYS_HEADER(SystemTools.hxx)
17 #include KWSYS_HEADER(Directory.hxx)
19 #include KWSYS_HEADER(ios/iostream)
20 #include KWSYS_HEADER(ios/fstream)
21 #include KWSYS_HEADER(ios/sstream)
23 // Work-around CMake dependency scanning limitation. This must
24 // duplicate the above list of headers.
25 #if 0
26 # include "SystemTools.hxx.in"
27 # include "Directory.hxx.in"
28 # include "kwsys_ios_iostream.h.in"
29 # include "kwsys_ios_fstream.h.in"
30 # include "kwsys_ios_sstream.h.in"
31 #endif
33 #ifdef _MSC_VER
34 # pragma warning (disable: 4786)
35 #endif
37 #if defined(__sgi) && !defined(__GNUC__)
38 # pragma set woff 1375 /* base class destructor not virtual */
39 #endif
41 #include <ctype.h>
42 #include <errno.h>
43 #ifdef __QNX__
44 # include <malloc.h> /* for malloc/free on QNX */
45 #endif
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sys/stat.h>
50 #include <time.h>
52 // support for realpath call
53 #ifndef _WIN32
54 #include <utime.h>
55 #include <limits.h>
56 #include <sys/wait.h>
57 #include <sys/ioctl.h>
58 #include <unistd.h>
59 #include <pwd.h>
60 #ifndef __VMS
61 #include <sys/param.h>
62 #include <termios.h>
63 #endif
64 #include <signal.h> /* sigprocmask */
65 #endif
67 // Windows API. Some parts used even on cygwin.
68 #if defined(_WIN32) || defined (__CYGWIN__)
69 # include <windows.h>
70 #endif
72 #ifdef __CYGWIN__
73 # undef _WIN32
74 extern "C" void cygwin_conv_to_win32_path(const char *path, char *win32_path);
75 #endif
77 // getpwnam doesn't exist on Windows and Cray Xt3/Catamount
78 // same for TIOCGWINSZ
79 #if defined(_WIN32) || defined (__LIBCATAMOUNT__)
80 # undef HAVE_GETPWNAM
81 # undef HAVE_TTY_INFO
82 #else
83 # define HAVE_GETPWNAM 1
84 # define HAVE_TTY_INFO 1
85 #endif
87 #define VTK_URL_PROTOCOL_REGEX "([a-zA-Z0-9]*)://(.*)"
88 #define VTK_URL_REGEX "([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]+)(:([0-9]+))?/(.+)?"
90 #ifdef _MSC_VER
91 #include <sys/utime.h>
92 #else
93 #include <utime.h>
94 #endif
97 // This is a hack to prevent warnings about these functions being
98 // declared but not referenced.
99 #if defined(__sgi) && !defined(__GNUC__)
100 # include <sys/termios.h>
101 namespace KWSYS_NAMESPACE
103 class SystemToolsHack
105 public:
106 enum
108 Ref1 = sizeof(cfgetospeed(0)),
109 Ref2 = sizeof(cfgetispeed(0)),
110 Ref3 = sizeof(tcgetattr(0, 0)),
111 Ref4 = sizeof(tcsetattr(0, 0, 0)),
112 Ref5 = sizeof(cfsetospeed(0,0)),
113 Ref6 = sizeof(cfsetispeed(0,0))
117 #endif
119 #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
120 #include <io.h>
121 #include <direct.h>
122 #define _unlink unlink
123 #endif
125 /* The maximum length of a file name. */
126 #if defined(PATH_MAX)
127 # define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
128 #elif defined(MAXPATHLEN)
129 # define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
130 #else
131 # define KWSYS_SYSTEMTOOLS_MAXPATH 16384
132 #endif
133 #if defined(__WATCOMC__)
134 #include <direct.h>
135 #define _mkdir mkdir
136 #define _rmdir rmdir
137 #define _getcwd getcwd
138 #define _chdir chdir
139 #endif
141 #if defined(__HAIKU__)
142 #include <os/kernel/OS.h>
143 #include <os/storage/Path.h>
144 #endif
146 #if defined(__BEOS__) && !defined(__ZETA__) && !defined(__HAIKU__)
147 #include <be/kernel/OS.h>
148 #include <be/storage/Path.h>
150 // BeOS 5 doesn't have usleep(), but it has snooze(), which is identical.
151 static inline void usleep(unsigned int msec)
153 ::snooze(msec);
156 // BeOS 5 also doesn't have realpath(), but its C++ API offers something close.
157 static inline char *realpath(const char *path, char *resolved_path)
159 const size_t maxlen = KWSYS_SYSTEMTOOLS_MAXPATH;
160 snprintf(resolved_path, maxlen, "%s", path);
161 BPath normalized(resolved_path, NULL, true);
162 const char *resolved = normalized.Path();
163 if (resolved != NULL) // NULL == No such file.
165 if (snprintf(resolved_path, maxlen, "%s", resolved) < maxlen)
167 return resolved_path;
170 return NULL; // something went wrong.
172 #endif
174 #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
175 inline int Mkdir(const char* dir)
177 return _mkdir(dir);
179 inline int Rmdir(const char* dir)
181 return _rmdir(dir);
183 inline const char* Getcwd(char* buf, unsigned int len)
185 const char* ret = _getcwd(buf, len);
186 if(!ret)
188 fprintf(stderr, "No current working directory.\n");
189 abort();
191 // make sure the drive letter is capital
192 if(strlen(buf) > 1 && buf[1] == ':')
194 buf[0] = toupper(buf[0]);
196 return ret;
198 inline int Chdir(const char* dir)
200 #if defined(__BORLANDC__)
201 return chdir(dir);
202 #else
203 return _chdir(dir);
204 #endif
206 inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
208 char *ptemp;
209 char fullpath[MAX_PATH];
210 if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
212 resolved_path = fullpath;
213 KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
215 else
217 resolved_path = path;
220 #else
221 #include <sys/types.h>
222 #include <fcntl.h>
223 #include <unistd.h>
224 inline int Mkdir(const char* dir)
226 return mkdir(dir, 00777);
228 inline int Rmdir(const char* dir)
230 return rmdir(dir);
232 inline const char* Getcwd(char* buf, unsigned int len)
234 const char* ret = getcwd(buf, len);
235 if(!ret)
237 fprintf(stderr, "No current working directory\n");
238 abort();
240 return ret;
243 inline int Chdir(const char* dir)
245 return chdir(dir);
247 inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
249 char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
251 char *ret = realpath(path, resolved_name);
252 if(ret)
254 resolved_path = ret;
256 else
258 // if path resolution fails, return what was passed in
259 resolved_path = path;
262 #endif
264 #if !defined(_WIN32) && defined(__COMO__)
265 // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
266 extern "C"
268 extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
269 extern int pclose (FILE *__stream) __THROW;
270 extern char *realpath (__const char *__restrict __name,
271 char *__restrict __resolved) __THROW;
272 extern char *strdup (__const char *__s) __THROW;
273 extern int putenv (char *__string) __THROW;
275 #endif
277 /* Implement floattime() for various platforms */
278 // Taken from Python 2.1.3
280 #if defined( _WIN32 ) && !defined( __CYGWIN__ )
281 # include <sys/timeb.h>
282 # define HAVE_FTIME
283 # if defined( __BORLANDC__)
284 # define FTIME ftime
285 # define TIMEB timeb
286 # else // Visual studio?
287 # define FTIME _ftime
288 # define TIMEB _timeb
289 # endif
290 #elif defined( __CYGWIN__ ) || defined( __linux__ )
291 # include <sys/time.h>
292 # include <time.h>
293 # define HAVE_GETTIMEOFDAY
294 #endif
296 namespace KWSYS_NAMESPACE
299 class SystemToolsTranslationMap :
300 public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
305 double
306 SystemTools::GetTime(void)
308 /* There are three ways to get the time:
309 (1) gettimeofday() -- resolution in microseconds
310 (2) ftime() -- resolution in milliseconds
311 (3) time() -- resolution in seconds
312 In all cases the return value is a float in seconds.
313 Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
314 fail, so we fall back on ftime() or time().
315 Note: clock resolution does not imply clock accuracy! */
316 #ifdef HAVE_GETTIMEOFDAY
318 struct timeval t;
319 #ifdef GETTIMEOFDAY_NO_TZ
320 if (gettimeofday(&t) == 0)
321 #else /* !GETTIMEOFDAY_NO_TZ */
322 if (gettimeofday(&t, static_cast<struct timezone *>(NULL)) == 0)
323 #endif /* !GETTIMEOFDAY_NO_TZ */
324 return static_cast<double>(t.tv_sec) +
325 static_cast<double>(t.tv_usec)*0.000001;
327 #endif /* !HAVE_GETTIMEOFDAY */
329 #if defined(HAVE_FTIME)
330 struct TIMEB t;
331 ::FTIME(&t);
332 return static_cast<double>(t.time) +
333 static_cast<double>(t.millitm) * static_cast<double>(0.001);
334 #else /* !HAVE_FTIME */
335 time_t secs;
336 time(&secs);
337 return static_cast<double>(secs);
338 #endif /* !HAVE_FTIME */
342 // adds the elements of the env variable path to the arg passed in
343 void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
345 #if defined(_WIN32) && !defined(__CYGWIN__)
346 const char* pathSep = ";";
347 #else
348 const char* pathSep = ":";
349 #endif
350 if(!env)
352 env = "PATH";
354 const char* cpathEnv = SystemTools::GetEnv(env);
355 if ( !cpathEnv )
357 return;
360 kwsys_stl::string pathEnv = cpathEnv;
362 // A hack to make the below algorithm work.
363 if(pathEnv[pathEnv.length()-1] != ':')
365 pathEnv += pathSep;
367 kwsys_stl::string::size_type start =0;
368 bool done = false;
369 while(!done)
371 kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
372 if(endpos != kwsys_stl::string::npos)
374 kwsys_stl::string convertedPath;
375 Realpath(pathEnv.substr(start, endpos-start).c_str(), convertedPath);
376 path.push_back(convertedPath);
377 start = endpos+1;
379 else
381 done = true;
384 for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
385 i != path.end(); ++i)
387 SystemTools::ConvertToUnixSlashes(*i);
391 const char* SystemTools::GetEnv(const char* key)
393 return getenv(key);
396 bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
398 const char* v = getenv(key);
399 if(v)
401 result = v;
402 return true;
404 else
406 return false;
410 class kwsysDeletingCharVector : public kwsys_stl::vector<char*>
412 public:
413 ~kwsysDeletingCharVector();
416 kwsysDeletingCharVector::~kwsysDeletingCharVector()
418 #ifndef KWSYS_DO_NOT_CLEAN_PUTENV
419 for(kwsys_stl::vector<char*>::iterator i = this->begin();
420 i != this->end(); ++i)
422 delete []*i;
424 #endif
426 bool SystemTools::PutEnv(const char* value)
428 static kwsysDeletingCharVector localEnvironment;
429 char* envVar = new char[strlen(value)+1];
430 strcpy(envVar, value);
431 int ret = putenv(envVar);
432 // save the pointer in the static vector so that it can
433 // be deleted on exit
434 localEnvironment.push_back(envVar);
435 return ret == 0;
439 const char* SystemTools::GetExecutableExtension()
441 #if defined(_WIN32) || defined(__CYGWIN__) || defined(__VMS)
442 return ".exe";
443 #else
444 return "";
445 #endif
449 bool SystemTools::MakeDirectory(const char* path)
451 if(!path)
453 return false;
455 if(SystemTools::FileExists(path))
457 return true;
459 kwsys_stl::string dir = path;
460 if(dir.size() == 0)
462 return false;
464 SystemTools::ConvertToUnixSlashes(dir);
466 kwsys_stl::string::size_type pos = dir.find(':');
467 if(pos == kwsys_stl::string::npos)
469 pos = 0;
471 kwsys_stl::string topdir;
472 while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
474 topdir = dir.substr(0, pos);
475 Mkdir(topdir.c_str());
476 pos++;
478 if(dir[dir.size()-1] == '/')
480 topdir = dir.substr(0, dir.size());
482 else
484 topdir = dir;
486 if(Mkdir(topdir.c_str()) != 0)
488 // There is a bug in the Borland Run time library which makes MKDIR
489 // return EACCES when it should return EEXISTS
490 // if it is some other error besides directory exists
491 // then return false
492 if( (errno != EEXIST)
493 #ifdef __BORLANDC__
494 && (errno != EACCES)
495 #endif
498 return false;
501 return true;
505 // replace replace with with as many times as it shows up in source.
506 // write the result into source.
507 void SystemTools::ReplaceString(kwsys_stl::string& source,
508 const char* replace,
509 const char* with)
511 const char *src = source.c_str();
512 char *searchPos = const_cast<char *>(strstr(src,replace));
514 // get out quick if string is not found
515 if (!searchPos)
517 return;
520 // perform replacements until done
521 size_t replaceSize = strlen(replace);
522 // do while hangs if replaceSize is 0
523 if(replaceSize == 0)
525 return;
527 char *orig = strdup(src);
528 char *currentPos = orig;
529 searchPos = searchPos - src + orig;
531 // initialize the result
532 source.erase(source.begin(),source.end());
535 *searchPos = '\0';
536 source += currentPos;
537 currentPos = searchPos + replaceSize;
538 // replace
539 source += with;
540 searchPos = strstr(currentPos,replace);
542 while (searchPos);
544 // copy any trailing text
545 source += currentPos;
546 free(orig);
549 #if defined(KEY_WOW64_32KEY) && defined(KEY_WOW64_64KEY)
550 # define KWSYS_ST_KEY_WOW64_32KEY KEY_WOW64_32KEY
551 # define KWSYS_ST_KEY_WOW64_64KEY KEY_WOW64_64KEY
552 #else
553 # define KWSYS_ST_KEY_WOW64_32KEY 0x0200
554 # define KWSYS_ST_KEY_WOW64_64KEY 0x0100
555 #endif
557 #if defined(_WIN32) && !defined(__CYGWIN__)
558 static DWORD SystemToolsMakeRegistryMode(DWORD mode,
559 SystemTools::KeyWOW64 view)
561 if(view == SystemTools::KeyWOW64_32)
563 return mode | KWSYS_ST_KEY_WOW64_32KEY;
565 else if(view == SystemTools::KeyWOW64_64)
567 return mode | KWSYS_ST_KEY_WOW64_64KEY;
569 return mode;
571 #endif
573 // Read a registry value.
574 // Example :
575 // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
576 // => will return the data of the "default" value of the key
577 // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
578 // => will return the data of the "Root" value of the key
580 #if defined(_WIN32) && !defined(__CYGWIN__)
581 bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value,
582 KeyWOW64 view)
584 bool valueset = false;
585 kwsys_stl::string primary = key;
586 kwsys_stl::string second;
587 kwsys_stl::string valuename;
589 size_t start = primary.find("\\");
590 if (start == kwsys_stl::string::npos)
592 return false;
595 size_t valuenamepos = primary.find(";");
596 if (valuenamepos != kwsys_stl::string::npos)
598 valuename = primary.substr(valuenamepos+1);
601 second = primary.substr(start+1, valuenamepos-start-1);
602 primary = primary.substr(0, start);
604 HKEY primaryKey = HKEY_CURRENT_USER;
605 if (primary == "HKEY_CURRENT_USER")
607 primaryKey = HKEY_CURRENT_USER;
609 if (primary == "HKEY_CURRENT_CONFIG")
611 primaryKey = HKEY_CURRENT_CONFIG;
613 if (primary == "HKEY_CLASSES_ROOT")
615 primaryKey = HKEY_CLASSES_ROOT;
617 if (primary == "HKEY_LOCAL_MACHINE")
619 primaryKey = HKEY_LOCAL_MACHINE;
621 if (primary == "HKEY_USERS")
623 primaryKey = HKEY_USERS;
626 HKEY hKey;
627 if(RegOpenKeyEx(primaryKey,
628 second.c_str(),
630 SystemToolsMakeRegistryMode(KEY_READ, view),
631 &hKey) != ERROR_SUCCESS)
633 return false;
635 else
637 DWORD dwType, dwSize;
638 dwSize = 1023;
639 char data[1024];
640 if(RegQueryValueEx(hKey,
641 (LPTSTR)valuename.c_str(),
642 NULL,
643 &dwType,
644 (BYTE *)data,
645 &dwSize) == ERROR_SUCCESS)
647 if (dwType == REG_SZ)
649 value = data;
650 valueset = true;
652 else if (dwType == REG_EXPAND_SZ)
654 char expanded[1024];
655 DWORD dwExpandedSize = sizeof(expanded)/sizeof(expanded[0]);
656 if(ExpandEnvironmentStrings(data, expanded, dwExpandedSize))
658 value = expanded;
659 valueset = true;
664 RegCloseKey(hKey);
667 return valueset;
669 #else
670 bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &,
671 KeyWOW64)
673 return false;
675 #endif
678 // Write a registry value.
679 // Example :
680 // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
681 // => will set the data of the "default" value of the key
682 // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
683 // => will set the data of the "Root" value of the key
685 #if defined(_WIN32) && !defined(__CYGWIN__)
686 bool SystemTools::WriteRegistryValue(const char *key, const char *value,
687 KeyWOW64 view)
689 kwsys_stl::string primary = key;
690 kwsys_stl::string second;
691 kwsys_stl::string valuename;
693 size_t start = primary.find("\\");
694 if (start == kwsys_stl::string::npos)
696 return false;
699 size_t valuenamepos = primary.find(";");
700 if (valuenamepos != kwsys_stl::string::npos)
702 valuename = primary.substr(valuenamepos+1);
705 second = primary.substr(start+1, valuenamepos-start-1);
706 primary = primary.substr(0, start);
708 HKEY primaryKey = HKEY_CURRENT_USER;
709 if (primary == "HKEY_CURRENT_USER")
711 primaryKey = HKEY_CURRENT_USER;
713 if (primary == "HKEY_CURRENT_CONFIG")
715 primaryKey = HKEY_CURRENT_CONFIG;
717 if (primary == "HKEY_CLASSES_ROOT")
719 primaryKey = HKEY_CLASSES_ROOT;
721 if (primary == "HKEY_LOCAL_MACHINE")
723 primaryKey = HKEY_LOCAL_MACHINE;
725 if (primary == "HKEY_USERS")
727 primaryKey = HKEY_USERS;
730 HKEY hKey;
731 DWORD dwDummy;
732 if(RegCreateKeyEx(primaryKey,
733 second.c_str(),
736 REG_OPTION_NON_VOLATILE,
737 SystemToolsMakeRegistryMode(KEY_WRITE, view),
738 NULL,
739 &hKey,
740 &dwDummy) != ERROR_SUCCESS)
742 return false;
745 if(RegSetValueEx(hKey,
746 (LPTSTR)valuename.c_str(),
748 REG_SZ,
749 (CONST BYTE *)value,
750 (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
752 return true;
754 return false;
756 #else
757 bool SystemTools::WriteRegistryValue(const char *, const char *, KeyWOW64)
759 return false;
761 #endif
763 // Delete a registry value.
764 // Example :
765 // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
766 // => will delete the data of the "default" value of the key
767 // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
768 // => will delete the data of the "Root" value of the key
770 #if defined(_WIN32) && !defined(__CYGWIN__)
771 bool SystemTools::DeleteRegistryValue(const char *key, KeyWOW64 view)
773 kwsys_stl::string primary = key;
774 kwsys_stl::string second;
775 kwsys_stl::string valuename;
777 size_t start = primary.find("\\");
778 if (start == kwsys_stl::string::npos)
780 return false;
783 size_t valuenamepos = primary.find(";");
784 if (valuenamepos != kwsys_stl::string::npos)
786 valuename = primary.substr(valuenamepos+1);
789 second = primary.substr(start+1, valuenamepos-start-1);
790 primary = primary.substr(0, start);
792 HKEY primaryKey = HKEY_CURRENT_USER;
793 if (primary == "HKEY_CURRENT_USER")
795 primaryKey = HKEY_CURRENT_USER;
797 if (primary == "HKEY_CURRENT_CONFIG")
799 primaryKey = HKEY_CURRENT_CONFIG;
801 if (primary == "HKEY_CLASSES_ROOT")
803 primaryKey = HKEY_CLASSES_ROOT;
805 if (primary == "HKEY_LOCAL_MACHINE")
807 primaryKey = HKEY_LOCAL_MACHINE;
809 if (primary == "HKEY_USERS")
811 primaryKey = HKEY_USERS;
814 HKEY hKey;
815 if(RegOpenKeyEx(primaryKey,
816 second.c_str(),
818 SystemToolsMakeRegistryMode(KEY_WRITE, view),
819 &hKey) != ERROR_SUCCESS)
821 return false;
823 else
825 if(RegDeleteValue(hKey,
826 (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
828 RegCloseKey(hKey);
829 return true;
832 return false;
834 #else
835 bool SystemTools::DeleteRegistryValue(const char *, KeyWOW64)
837 return false;
839 #endif
841 bool SystemTools::SameFile(const char* file1, const char* file2)
843 #ifdef _WIN32
844 HANDLE hFile1, hFile2;
846 hFile1 = CreateFile( file1,
847 GENERIC_READ,
848 FILE_SHARE_READ ,
849 NULL,
850 OPEN_EXISTING,
851 FILE_FLAG_BACKUP_SEMANTICS,
852 NULL
854 hFile2 = CreateFile( file2,
855 GENERIC_READ,
856 FILE_SHARE_READ,
857 NULL,
858 OPEN_EXISTING,
859 FILE_FLAG_BACKUP_SEMANTICS,
860 NULL
862 if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
864 if(hFile1 != INVALID_HANDLE_VALUE)
866 CloseHandle(hFile1);
868 if(hFile2 != INVALID_HANDLE_VALUE)
870 CloseHandle(hFile2);
872 return false;
875 BY_HANDLE_FILE_INFORMATION fiBuf1;
876 BY_HANDLE_FILE_INFORMATION fiBuf2;
877 GetFileInformationByHandle( hFile1, &fiBuf1 );
878 GetFileInformationByHandle( hFile2, &fiBuf2 );
879 CloseHandle(hFile1);
880 CloseHandle(hFile2);
881 return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
882 fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
883 fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
884 #else
885 struct stat fileStat1, fileStat2;
886 if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
888 // see if the files are the same file
889 // check the device inode and size
890 if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
891 memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
892 fileStat2.st_size == fileStat1.st_size
895 return true;
898 return false;
899 #endif
902 //----------------------------------------------------------------------------
903 #if defined(_WIN32) || defined(__CYGWIN__)
904 static bool WindowsFileExists(const char* filename)
906 WIN32_FILE_ATTRIBUTE_DATA fd;
907 return GetFileAttributesExA(filename, GetFileExInfoStandard, &fd) != 0;
909 #endif
911 //----------------------------------------------------------------------------
912 bool SystemTools::FileExists(const char* filename)
914 if(!(filename && *filename))
916 return false;
918 #if defined(__CYGWIN__)
919 // Convert filename to native windows path if possible.
920 char winpath[MAX_PATH];
921 if(SystemTools::PathCygwinToWin32(filename, winpath))
923 return WindowsFileExists(winpath);
925 return access(filename, R_OK) == 0;
926 #elif defined(_WIN32)
927 return WindowsFileExists(filename);
928 #else
929 return access(filename, R_OK) == 0;
930 #endif
933 //----------------------------------------------------------------------------
934 bool SystemTools::FileExists(const char* filename, bool isFile)
936 if(SystemTools::FileExists(filename))
938 // If isFile is set return not FileIsDirectory,
939 // so this will only be true if it is a file
940 return !isFile || !SystemTools::FileIsDirectory(filename);
942 return false;
945 //----------------------------------------------------------------------------
946 #ifdef __CYGWIN__
947 bool SystemTools::PathCygwinToWin32(const char *path, char *win32_path)
949 SystemToolsTranslationMap::iterator i =
950 SystemTools::Cyg2Win32Map->find(path);
952 if (i != SystemTools::Cyg2Win32Map->end())
954 strncpy(win32_path, i->second.c_str(), MAX_PATH);
956 else
958 cygwin_conv_to_win32_path(path, win32_path);
959 SystemToolsTranslationMap::value_type entry(path, win32_path);
960 SystemTools::Cyg2Win32Map->insert(entry);
962 return win32_path[0] != 0;
964 #endif
966 bool SystemTools::Touch(const char* filename, bool create)
968 if(create && !SystemTools::FileExists(filename))
970 FILE* file = fopen(filename, "a+b");
971 if(file)
973 fclose(file);
974 return true;
976 return false;
978 #ifdef _MSC_VER
979 #define utime _utime
980 #define utimbuf _utimbuf
981 #endif
982 struct stat fromStat;
983 if(stat(filename, &fromStat) < 0)
985 return false;
987 struct utimbuf buf;
988 buf.actime = fromStat.st_atime;
989 buf.modtime = static_cast<time_t>(SystemTools::GetTime());
990 if(utime(filename, &buf) < 0)
992 return false;
994 return true;
997 bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
998 int* result)
1000 // Default to same time.
1001 *result = 0;
1002 #if !defined(_WIN32) || defined(__CYGWIN__)
1003 // POSIX version. Use stat function to get file modification time.
1004 struct stat s1;
1005 if(stat(f1, &s1) != 0)
1007 return false;
1009 struct stat s2;
1010 if(stat(f2, &s2) != 0)
1012 return false;
1014 # if KWSYS_STAT_HAS_ST_MTIM
1015 // Compare using nanosecond resolution.
1016 if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
1018 *result = -1;
1020 else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
1022 *result = 1;
1024 else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
1026 *result = -1;
1028 else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
1030 *result = 1;
1032 # else
1033 // Compare using 1 second resolution.
1034 if(s1.st_mtime < s2.st_mtime)
1036 *result = -1;
1038 else if(s1.st_mtime > s2.st_mtime)
1040 *result = 1;
1042 # endif
1043 #else
1044 // Windows version. Get the modification time from extended file attributes.
1045 WIN32_FILE_ATTRIBUTE_DATA f1d;
1046 WIN32_FILE_ATTRIBUTE_DATA f2d;
1047 if(!GetFileAttributesEx(f1, GetFileExInfoStandard, &f1d))
1049 return false;
1051 if(!GetFileAttributesEx(f2, GetFileExInfoStandard, &f2d))
1053 return false;
1056 // Compare the file times using resolution provided by system call.
1057 *result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime);
1058 #endif
1059 return true;
1063 // Return a capitalized string (i.e the first letter is uppercased, all other
1064 // are lowercased)
1065 kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
1067 kwsys_stl::string n;
1068 if(s.size() == 0)
1070 return n;
1072 n.resize(s.size());
1073 n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
1074 for (size_t i = 1; i < s.size(); i++)
1076 n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
1078 return n;
1081 // Return capitalized words
1082 kwsys_stl::string SystemTools::CapitalizedWords(const kwsys_stl::string& s)
1084 kwsys_stl::string n(s);
1085 for (size_t i = 0; i < s.size(); i++)
1087 #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
1088 // MS has an assert that will fail if s[i] < 0; setting
1089 // LC_CTYPE using setlocale() does *not* help. Painful.
1090 if ((int)s[i] >= 0 && isalpha(s[i]) &&
1091 (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
1092 #else
1093 if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
1094 #endif
1096 n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
1099 return n;
1102 // Return uncapitalized words
1103 kwsys_stl::string SystemTools::UnCapitalizedWords(const kwsys_stl::string& s)
1105 kwsys_stl::string n(s);
1106 for (size_t i = 0; i < s.size(); i++)
1108 #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
1109 // MS has an assert that will fail if s[i] < 0; setting
1110 // LC_CTYPE using setlocale() does *not* help. Painful.
1111 if ((int)s[i] >= 0 && isalpha(s[i]) &&
1112 (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
1113 #else
1114 if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
1115 #endif
1117 n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
1120 return n;
1123 // only works for words with at least two letters
1124 kwsys_stl::string SystemTools::AddSpaceBetweenCapitalizedWords(
1125 const kwsys_stl::string& s)
1127 kwsys_stl::string n;
1128 if (s.size())
1130 n.reserve(s.size());
1131 n += s[0];
1132 for (size_t i = 1; i < s.size(); i++)
1134 if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1]))
1136 n += ' ';
1138 n += s[i];
1141 return n;
1144 char* SystemTools::AppendStrings(const char* str1, const char* str2)
1146 if (!str1)
1148 return SystemTools::DuplicateString(str2);
1150 if (!str2)
1152 return SystemTools::DuplicateString(str1);
1154 size_t len1 = strlen(str1);
1155 char *newstr = new char[len1 + strlen(str2) + 1];
1156 if (!newstr)
1158 return 0;
1160 strcpy(newstr, str1);
1161 strcat(newstr + len1, str2);
1162 return newstr;
1165 char* SystemTools::AppendStrings(
1166 const char* str1, const char* str2, const char* str3)
1168 if (!str1)
1170 return SystemTools::AppendStrings(str2, str3);
1172 if (!str2)
1174 return SystemTools::AppendStrings(str1, str3);
1176 if (!str3)
1178 return SystemTools::AppendStrings(str1, str2);
1181 size_t len1 = strlen(str1), len2 = strlen(str2);
1182 char *newstr = new char[len1 + len2 + strlen(str3) + 1];
1183 if (!newstr)
1185 return 0;
1187 strcpy(newstr, str1);
1188 strcat(newstr + len1, str2);
1189 strcat(newstr + len1 + len2, str3);
1190 return newstr;
1193 // Return a lower case string
1194 kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
1196 kwsys_stl::string n;
1197 n.resize(s.size());
1198 for (size_t i = 0; i < s.size(); i++)
1200 n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
1202 return n;
1205 // Return a lower case string
1206 kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
1208 kwsys_stl::string n;
1209 n.resize(s.size());
1210 for (size_t i = 0; i < s.size(); i++)
1212 n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
1214 return n;
1217 // Count char in string
1218 size_t SystemTools::CountChar(const char* str, char c)
1220 size_t count = 0;
1222 if (str)
1224 while (*str)
1226 if (*str == c)
1228 ++count;
1230 ++str;
1233 return count;
1236 // Remove chars in string
1237 char* SystemTools::RemoveChars(const char* str, const char *toremove)
1239 if (!str)
1241 return NULL;
1243 char *clean_str = new char [strlen(str) + 1];
1244 char *ptr = clean_str;
1245 while (*str)
1247 const char *str2 = toremove;
1248 while (*str2 && *str != *str2)
1250 ++str2;
1252 if (!*str2)
1254 *ptr++ = *str;
1256 ++str;
1258 *ptr = '\0';
1259 return clean_str;
1262 // Remove chars in string
1263 char* SystemTools::RemoveCharsButUpperHex(const char* str)
1265 if (!str)
1267 return 0;
1269 char *clean_str = new char [strlen(str) + 1];
1270 char *ptr = clean_str;
1271 while (*str)
1273 if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'F'))
1275 *ptr++ = *str;
1277 ++str;
1279 *ptr = '\0';
1280 return clean_str;
1283 // Replace chars in string
1284 char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
1286 if (str)
1288 char *ptr = str;
1289 while (*ptr)
1291 const char *ptr2 = toreplace;
1292 while (*ptr2)
1294 if (*ptr == *ptr2)
1296 *ptr = replacement;
1298 ++ptr2;
1300 ++ptr;
1303 return str;
1306 // Returns if string starts with another string
1307 bool SystemTools::StringStartsWith(const char* str1, const char* str2)
1309 if (!str1 || !str2)
1311 return false;
1313 size_t len1 = strlen(str1), len2 = strlen(str2);
1314 return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
1317 // Returns if string ends with another string
1318 bool SystemTools::StringEndsWith(const char* str1, const char* str2)
1320 if (!str1 || !str2)
1322 return false;
1324 size_t len1 = strlen(str1), len2 = strlen(str2);
1325 return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
1328 // Returns a pointer to the last occurence of str2 in str1
1329 const char* SystemTools::FindLastString(const char* str1, const char* str2)
1331 if (!str1 || !str2)
1333 return NULL;
1336 size_t len1 = strlen(str1), len2 = strlen(str2);
1337 if (len1 >= len2)
1339 const char *ptr = str1 + len1 - len2;
1342 if (!strncmp(ptr, str2, len2))
1344 return ptr;
1346 } while (ptr-- != str1);
1349 return NULL;
1352 // Duplicate string
1353 char* SystemTools::DuplicateString(const char* str)
1355 if (str)
1357 char *newstr = new char [strlen(str) + 1];
1358 return strcpy(newstr, str);
1360 return NULL;
1363 // Return a cropped string
1364 kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s,
1365 size_t max_len)
1367 if (!s.size() || max_len == 0 || max_len >= s.size())
1369 return s;
1372 kwsys_stl::string n;
1373 n.reserve(max_len);
1375 size_t middle = max_len / 2;
1377 n += s.substr(0, middle);
1378 n += s.substr(s.size() - (max_len - middle), kwsys_stl::string::npos);
1380 if (max_len > 2)
1382 n[middle] = '.';
1383 if (max_len > 3)
1385 n[middle - 1] = '.';
1386 if (max_len > 4)
1388 n[middle + 1] = '.';
1393 return n;
1396 //----------------------------------------------------------------------------
1397 kwsys_stl::vector<kwsys::String> SystemTools::SplitString(const char* p, char sep, bool isPath)
1399 kwsys_stl::string path = p;
1400 kwsys_stl::vector<kwsys::String> paths;
1401 if(isPath && path[0] == '/')
1403 path.erase(path.begin());
1404 paths.push_back("/");
1406 kwsys_stl::string::size_type pos1 = 0;
1407 kwsys_stl::string::size_type pos2 = path.find(sep, pos1+1);
1408 while(pos2 != kwsys_stl::string::npos)
1410 paths.push_back(path.substr(pos1, pos2-pos1));
1411 pos1 = pos2+1;
1412 pos2 = path.find(sep, pos1+1);
1414 paths.push_back(path.substr(pos1, pos2-pos1));
1416 return paths;
1419 //----------------------------------------------------------------------------
1420 int SystemTools::EstimateFormatLength(const char *format, va_list ap)
1422 if (!format)
1424 return 0;
1427 // Quick-hack attempt at estimating the length of the string.
1428 // Should never under-estimate.
1430 // Start with the length of the format string itself.
1432 size_t length = strlen(format);
1434 // Increase the length for every argument in the format.
1436 const char* cur = format;
1437 while(*cur)
1439 if(*cur++ == '%')
1441 // Skip "%%" since it doesn't correspond to a va_arg.
1442 if(*cur != '%')
1444 while(!int(isalpha(*cur)))
1446 ++cur;
1448 switch (*cur)
1450 case 's':
1452 // Check the length of the string.
1453 char* s = va_arg(ap, char*);
1454 if(s)
1456 length += strlen(s);
1458 } break;
1459 case 'e':
1460 case 'f':
1461 case 'g':
1463 // Assume the argument contributes no more than 64 characters.
1464 length += 64;
1466 // Eat the argument.
1467 static_cast<void>(va_arg(ap, double));
1468 } break;
1469 default:
1471 // Assume the argument contributes no more than 64 characters.
1472 length += 64;
1474 // Eat the argument.
1475 static_cast<void>(va_arg(ap, int));
1476 } break;
1480 // Move past the characters just tested.
1481 ++cur;
1485 return static_cast<int>(length);
1488 kwsys_stl::string SystemTools::EscapeChars(
1489 const char *str,
1490 const char *chars_to_escape,
1491 char escape_char)
1493 kwsys_stl::string n;
1494 if (str)
1496 if (!chars_to_escape | !*chars_to_escape)
1498 n.append(str);
1500 else
1502 n.reserve(strlen(str));
1503 while (*str)
1505 const char *ptr = chars_to_escape;
1506 while (*ptr)
1508 if (*str == *ptr)
1510 n += escape_char;
1511 break;
1513 ++ptr;
1515 n += *str;
1516 ++str;
1520 return n;
1523 #ifdef __VMS
1524 static void ConvertVMSToUnix(kwsys_stl::string& path)
1526 kwsys_stl::string::size_type rootEnd = path.find(":[");
1527 kwsys_stl::string::size_type pathEnd = path.find("]");
1528 if(rootEnd != path.npos)
1530 kwsys_stl::string root = path.substr(0, rootEnd);
1531 kwsys_stl::string pathPart = path.substr(rootEnd+2, pathEnd - rootEnd-2);
1532 const char* pathCString = pathPart.c_str();
1533 const char* pos0 = pathCString;
1534 for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
1536 if ( *pos0 == '.' )
1538 pathPart[pos] = '/';
1540 pos0 ++;
1542 path = "/"+ root + "/" + pathPart;
1545 #endif
1547 // convert windows slashes to unix slashes
1548 void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
1550 const char* pathCString = path.c_str();
1551 bool hasDoubleSlash = false;
1552 #ifdef __VMS
1553 ConvertVMSToUnix(path);
1554 #else
1555 const char* pos0 = pathCString;
1556 const char* pos1 = pathCString+1;
1557 for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
1559 // make sure we don't convert an escaped space to a unix slash
1560 if ( *pos0 == '\\' && *pos1 != ' ' )
1562 path[pos] = '/';
1565 // Also, reuse the loop to check for slash followed by another slash
1566 if (*pos1 == '/' && *(pos1+1) == '/' && !hasDoubleSlash)
1568 #ifdef _WIN32
1569 // However, on windows if the first characters are both slashes,
1570 // then keep them that way, so that network paths can be handled.
1571 if ( pos > 0)
1573 hasDoubleSlash = true;
1575 #else
1576 hasDoubleSlash = true;
1577 #endif
1580 pos0 ++;
1581 pos1 ++;
1584 if ( hasDoubleSlash )
1586 SystemTools::ReplaceString(path, "//", "/");
1588 #endif
1589 // remove any trailing slash
1590 if(!path.empty())
1592 // if there is a tilda ~ then replace it with HOME
1593 pathCString = path.c_str();
1594 if(pathCString[0] == '~' && (pathCString[1] == '/' || pathCString[1] == '\0'))
1596 const char* homeEnv = SystemTools::GetEnv("HOME");
1597 if (homeEnv)
1599 path.replace(0,1,homeEnv);
1602 #ifdef HAVE_GETPWNAM
1603 else if(pathCString[0] == '~')
1605 kwsys_stl::string::size_type idx = path.find_first_of("/\0");
1606 kwsys_stl::string user = path.substr(1, idx-1);
1607 passwd* pw = getpwnam(user.c_str());
1608 if(pw)
1610 path.replace(0, idx, pw->pw_dir);
1613 #endif
1614 // remove trailing slash if the path is more than
1615 // a single /
1616 pathCString = path.c_str();
1617 if(path.size() > 1 && *(pathCString+(path.size()-1)) == '/')
1619 // if it is c:/ then do not remove the trailing slash
1620 if(!((path.size() == 3 && pathCString[1] == ':')))
1622 path = path.substr(0, path.size()-1);
1628 // change // to /, and escape any spaces in the path
1629 kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
1631 kwsys_stl::string ret = path;
1633 // remove // except at the beginning might be a cygwin drive
1634 kwsys_stl::string::size_type pos=0;
1635 while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
1637 ret.erase(pos, 1);
1639 // escape spaces and () in the path
1640 if(ret.find_first_of(" ") != kwsys_stl::string::npos)
1642 kwsys_stl::string result = "";
1643 char lastch = 1;
1644 for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
1646 // if it is already escaped then don't try to escape it again
1647 if((*ch == ' ') && lastch != '\\')
1649 result += '\\';
1651 result += *ch;
1652 lastch = *ch;
1654 ret = result;
1656 return ret;
1659 kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
1661 #if defined(_WIN32) && !defined(__CYGWIN__)
1662 return SystemTools::ConvertToWindowsOutputPath(path);
1663 #else
1664 return SystemTools::ConvertToUnixOutputPath(path);
1665 #endif
1668 // remove double slashes not at the start
1669 kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
1671 kwsys_stl::string ret;
1672 // make it big enough for all of path and double quotes
1673 ret.reserve(strlen(path)+3);
1674 // put path into the string
1675 ret.assign(path);
1676 ret = path;
1677 kwsys_stl::string::size_type pos = 0;
1678 // first convert all of the slashes
1679 while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
1681 ret[pos] = '\\';
1682 pos++;
1684 // check for really small paths
1685 if(ret.size() < 2)
1687 return ret;
1689 // now clean up a bit and remove double slashes
1690 // Only if it is not the first position in the path which is a network
1691 // path on windows
1692 pos = 1; // start at position 1
1693 if(ret[0] == '\"')
1695 pos = 2; // if the string is already quoted then start at 2
1696 if(ret.size() < 3)
1698 return ret;
1701 while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
1703 ret.erase(pos, 1);
1705 // now double quote the path if it has spaces in it
1706 // and is not already double quoted
1707 if(ret.find(' ') != kwsys_stl::string::npos
1708 && ret[0] != '\"')
1710 ret.insert(static_cast<kwsys_stl::string::size_type>(0),
1711 static_cast<kwsys_stl::string::size_type>(1), '\"');
1712 ret.append(1, '\"');
1714 return ret;
1717 bool SystemTools::CopyFileIfDifferent(const char* source,
1718 const char* destination,
1719 bool copyPermissions)
1721 // special check for a destination that is a directory
1722 // FilesDiffer does not handle file to directory compare
1723 if(SystemTools::FileIsDirectory(destination))
1725 kwsys_stl::string new_destination = destination;
1726 SystemTools::ConvertToUnixSlashes(new_destination);
1727 new_destination += '/';
1728 kwsys_stl::string source_name = source;
1729 new_destination += SystemTools::GetFilenameName(source_name);
1730 if(SystemTools::FilesDiffer(source, new_destination.c_str()))
1732 return SystemTools::CopyFileAlways(source, destination,
1733 copyPermissions);
1735 else
1737 // the files are the same so the copy is done return
1738 // true
1739 return true;
1742 // source and destination are files so do a copy if they
1743 // are different
1744 if(SystemTools::FilesDiffer(source, destination))
1746 return SystemTools::CopyFileAlways(source, destination, copyPermissions);
1748 // at this point the files must be the same so return true
1749 return true;
1752 #define KWSYS_ST_BUFFER 4096
1754 bool SystemTools::FilesDiffer(const char* source,
1755 const char* destination)
1757 struct stat statSource;
1758 if (stat(source, &statSource) != 0)
1760 return true;
1763 struct stat statDestination;
1764 if (stat(destination, &statDestination) != 0)
1766 return true;
1769 if(statSource.st_size != statDestination.st_size)
1771 return true;
1774 if(statSource.st_size == 0)
1776 return false;
1779 #if defined(_WIN32) || defined(__CYGWIN__)
1780 kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
1781 kwsys_ios::ios::in));
1782 kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
1783 kwsys_ios::ios::in));
1784 #else
1785 kwsys_ios::ifstream finSource(source);
1786 kwsys_ios::ifstream finDestination(destination);
1787 #endif
1788 if(!finSource || !finDestination)
1790 return true;
1793 // Compare the files a block at a time.
1794 char source_buf[KWSYS_ST_BUFFER];
1795 char dest_buf[KWSYS_ST_BUFFER];
1796 off_t nleft = statSource.st_size;
1797 while(nleft > 0)
1799 // Read a block from each file.
1800 kwsys_ios::streamsize nnext = (nleft > KWSYS_ST_BUFFER)? KWSYS_ST_BUFFER : static_cast<kwsys_ios::streamsize>(nleft);
1801 finSource.read(source_buf, nnext);
1802 finDestination.read(dest_buf, nnext);
1804 // If either failed to read assume they are different.
1805 if(static_cast<kwsys_ios::streamsize>(finSource.gcount()) != nnext ||
1806 static_cast<kwsys_ios::streamsize>(finDestination.gcount()) != nnext)
1808 return true;
1811 // If this block differs the file differs.
1812 if(memcmp(static_cast<const void*>(source_buf),
1813 static_cast<const void*>(dest_buf),
1814 static_cast<size_t>(nnext)) != 0)
1816 return true;
1819 // Update the byte count remaining.
1820 nleft -= nnext;
1823 // No differences found.
1824 return false;
1828 //----------------------------------------------------------------------------
1830 * Copy a file named by "source" to the file named by "destination".
1832 bool SystemTools::CopyFileAlways(const char* source, const char* destination,
1833 bool copyPermissions)
1835 // If files are the same do not copy
1836 if ( SystemTools::SameFile(source, destination) )
1838 return true;
1840 mode_t perm = 0;
1841 bool perms = SystemTools::GetPermissions(source, perm);
1843 const int bufferSize = 4096;
1844 char buffer[bufferSize];
1846 // If destination is a directory, try to create a file with the same
1847 // name as the source in that directory.
1849 kwsys_stl::string new_destination;
1850 if(SystemTools::FileExists(destination) &&
1851 SystemTools::FileIsDirectory(destination))
1853 new_destination = destination;
1854 SystemTools::ConvertToUnixSlashes(new_destination);
1855 new_destination += '/';
1856 kwsys_stl::string source_name = source;
1857 new_destination += SystemTools::GetFilenameName(source_name);
1858 destination = new_destination.c_str();
1861 // Create destination directory
1863 kwsys_stl::string destination_dir = destination;
1864 destination_dir = SystemTools::GetFilenamePath(destination_dir);
1865 SystemTools::MakeDirectory(destination_dir.c_str());
1867 // Open files
1869 #if defined(_WIN32) || defined(__CYGWIN__)
1870 kwsys_ios::ifstream fin(source,
1871 kwsys_ios::ios::binary | kwsys_ios::ios::in);
1872 #else
1873 kwsys_ios::ifstream fin(source);
1874 #endif
1875 if(!fin)
1877 return false;
1880 // try and remove the destination file so that read only destination files
1881 // can be written to.
1882 // If the remove fails continue so that files in read only directories
1883 // that do not allow file removal can be modified.
1884 SystemTools::RemoveFile(destination);
1886 #if defined(_WIN32) || defined(__CYGWIN__)
1887 kwsys_ios::ofstream fout(destination,
1888 kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
1889 #else
1890 kwsys_ios::ofstream fout(destination,
1891 kwsys_ios::ios::out | kwsys_ios::ios::trunc);
1892 #endif
1893 if(!fout)
1895 return false;
1898 // This copy loop is very sensitive on certain platforms with
1899 // slightly broken stream libraries (like HPUX). Normally, it is
1900 // incorrect to not check the error condition on the fin.read()
1901 // before using the data, but the fin.gcount() will be zero if an
1902 // error occurred. Therefore, the loop should be safe everywhere.
1903 while(fin)
1905 fin.read(buffer, bufferSize);
1906 if(fin.gcount())
1908 fout.write(buffer, fin.gcount());
1912 // Make sure the operating system has finished writing the file
1913 // before closing it. This will ensure the file is finished before
1914 // the check below.
1915 fout.flush();
1917 fin.close();
1918 fout.close();
1920 // More checks.
1921 struct stat statSource, statDestination;
1922 statSource.st_size = 12345;
1923 statDestination.st_size = 12345;
1924 if(stat(source, &statSource) != 0)
1926 return false;
1928 else if(stat(destination, &statDestination) != 0)
1930 return false;
1932 else if(statSource.st_size != statDestination.st_size)
1934 return false;
1936 if ( copyPermissions && perms )
1938 if ( !SystemTools::SetPermissions(destination, perm) )
1940 return false;
1943 return true;
1946 //----------------------------------------------------------------------------
1947 bool SystemTools::CopyAFile(const char* source, const char* destination,
1948 bool always, bool copyPermissions)
1950 if(always)
1952 return SystemTools::CopyFileAlways(source, destination, copyPermissions);
1954 else
1956 return SystemTools::CopyFileIfDifferent(source, destination, copyPermissions);
1961 * Copy a directory content from "source" directory to the directory named by
1962 * "destination".
1964 bool SystemTools::CopyADirectory(const char* source, const char* destination,
1965 bool always, bool copyPermissions)
1967 Directory dir;
1968 dir.Load(source);
1969 size_t fileNum;
1970 if ( !SystemTools::MakeDirectory(destination) )
1972 return false;
1974 for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
1976 if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
1977 strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
1979 kwsys_stl::string fullPath = source;
1980 fullPath += "/";
1981 fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
1982 if(SystemTools::FileIsDirectory(fullPath.c_str()))
1984 kwsys_stl::string fullDestPath = destination;
1985 fullDestPath += "/";
1986 fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
1987 if (!SystemTools::CopyADirectory(fullPath.c_str(),
1988 fullDestPath.c_str(),
1989 always,
1990 copyPermissions))
1992 return false;
1995 else
1997 if(!SystemTools::CopyAFile(fullPath.c_str(), destination, always,
1998 copyPermissions))
2000 return false;
2006 return true;
2010 // return size of file; also returns zero if no file exists
2011 unsigned long SystemTools::FileLength(const char* filename)
2013 struct stat fs;
2014 if (stat(filename, &fs) != 0)
2016 return 0;
2018 else
2020 return static_cast<unsigned long>(fs.st_size);
2024 int SystemTools::Strucmp(const char *s1, const char *s2)
2026 // lifted from Graphvis http://www.graphviz.org
2027 while ((*s1 != '\0')
2028 && (tolower(*s1) == tolower(*s2)))
2030 s1++;
2031 s2++;
2034 return tolower(*s1) - tolower(*s2);
2037 // return file's modified time
2038 long int SystemTools::ModifiedTime(const char* filename)
2040 struct stat fs;
2041 if (stat(filename, &fs) != 0)
2043 return 0;
2045 else
2047 return static_cast<long int>(fs.st_mtime);
2051 // return file's creation time
2052 long int SystemTools::CreationTime(const char* filename)
2054 struct stat fs;
2055 if (stat(filename, &fs) != 0)
2057 return 0;
2059 else
2061 return fs.st_ctime >= 0 ? static_cast<long int>(fs.st_ctime) : 0;
2065 bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
2067 if (!str || !tmt || strlen(str) > 11)
2069 return false;
2072 struct tm tmt2;
2074 // __DATE__
2075 // The compilation date of the current source file. The date is a string
2076 // literal of the form Mmm dd yyyy. The month name Mmm is the same as for
2077 // dates generated by the library function asctime declared in TIME.H.
2079 // index: 012345678901
2080 // format: Mmm dd yyyy
2081 // example: Dec 19 2003
2083 static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2085 char buffer[12];
2086 strcpy(buffer, str);
2088 buffer[3] = 0;
2089 char *ptr = strstr(month_names, buffer);
2090 if (!ptr)
2092 return false;
2095 int month = static_cast<int>((ptr - month_names) / 3);
2096 int day = atoi(buffer + 4);
2097 int year = atoi(buffer + 7);
2099 tmt2.tm_isdst = -1;
2100 tmt2.tm_hour = 0;
2101 tmt2.tm_min = 0;
2102 tmt2.tm_sec = 0;
2103 tmt2.tm_wday = 0;
2104 tmt2.tm_yday = 0;
2105 tmt2.tm_mday = day;
2106 tmt2.tm_mon = month;
2107 tmt2.tm_year = year - 1900;
2109 *tmt = mktime(&tmt2);
2110 return true;
2113 bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
2115 if (!str || !tmt || strlen(str) > 26)
2117 return false;
2120 struct tm tmt2;
2122 // __TIMESTAMP__
2123 // The date and time of the last modification of the current source file,
2124 // expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy,
2125 /// where Ddd is the abbreviated day of the week and Date is an integer
2126 // from 1 to 31.
2128 // index: 0123456789
2129 // 0123456789
2130 // 0123456789
2131 // format: Ddd Mmm Date hh:mm:ss yyyy
2132 // example: Fri Dec 19 14:34:58 2003
2134 static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2136 char buffer[27];
2137 strcpy(buffer, str);
2139 buffer[7] = 0;
2140 char *ptr = strstr(month_names, buffer + 4);
2141 if (!ptr)
2143 return false;
2146 int month = static_cast<int>((ptr - month_names) / 3);
2147 int day = atoi(buffer + 8);
2148 int hour = atoi(buffer + 11);
2149 int min = atoi(buffer + 14);
2150 int sec = atoi(buffer + 17);
2151 int year = atoi(buffer + 20);
2153 tmt2.tm_isdst = -1;
2154 tmt2.tm_hour = hour;
2155 tmt2.tm_min = min;
2156 tmt2.tm_sec = sec;
2157 tmt2.tm_wday = 0;
2158 tmt2.tm_yday = 0;
2159 tmt2.tm_mday = day;
2160 tmt2.tm_mon = month;
2161 tmt2.tm_year = year - 1900;
2163 *tmt = mktime(&tmt2);
2164 return true;
2167 kwsys_stl::string SystemTools::GetLastSystemError()
2169 int e = errno;
2170 return strerror(e);
2173 bool SystemTools::RemoveFile(const char* source)
2175 #ifdef _WIN32
2176 mode_t mode;
2177 if ( !SystemTools::GetPermissions(source, mode) )
2179 return false;
2181 /* Win32 unlink is stupid --- it fails if the file is read-only */
2182 SystemTools::SetPermissions(source, S_IWRITE);
2183 #endif
2184 bool res = unlink(source) != 0 ? false : true;
2185 #ifdef _WIN32
2186 if ( !res )
2188 SystemTools::SetPermissions(source, mode);
2190 #endif
2191 return res;
2194 bool SystemTools::RemoveADirectory(const char* source)
2196 // Add write permission to the directory so we can modify its
2197 // content to remove files and directories from it.
2198 mode_t mode;
2199 if(SystemTools::GetPermissions(source, mode))
2201 #if defined(_WIN32) && !defined(__CYGWIN__)
2202 mode |= S_IWRITE;
2203 #else
2204 mode |= S_IWUSR;
2205 #endif
2206 SystemTools::SetPermissions(source, mode);
2209 Directory dir;
2210 dir.Load(source);
2211 size_t fileNum;
2212 for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
2214 if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
2215 strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
2217 kwsys_stl::string fullPath = source;
2218 fullPath += "/";
2219 fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
2220 if(SystemTools::FileIsDirectory(fullPath.c_str()) &&
2221 !SystemTools::FileIsSymlink(fullPath.c_str()))
2223 if (!SystemTools::RemoveADirectory(fullPath.c_str()))
2225 return false;
2228 else
2230 if(!SystemTools::RemoveFile(fullPath.c_str()))
2232 return false;
2238 return (Rmdir(source) == 0);
2243 size_t SystemTools::GetMaximumFilePathLength()
2245 return KWSYS_SYSTEMTOOLS_MAXPATH;
2249 * Find the file the given name. Searches the given path and then
2250 * the system search path. Returns the full path to the file if it is
2251 * found. Otherwise, the empty string is returned.
2253 kwsys_stl::string SystemTools
2254 ::FindName(const char* name,
2255 const kwsys_stl::vector<kwsys_stl::string>& userPaths,
2256 bool no_system_path)
2258 // Add the system search path to our path first
2259 kwsys_stl::vector<kwsys_stl::string> path;
2260 if (!no_system_path)
2262 SystemTools::GetPath(path, "CMAKE_FILE_PATH");
2263 SystemTools::GetPath(path);
2265 // now add the additional paths
2267 for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
2268 i != userPaths.end(); ++i)
2270 path.push_back(*i);
2273 // Add a trailing slash to all paths to aid the search process.
2275 for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
2276 i != path.end(); ++i)
2278 kwsys_stl::string& p = *i;
2279 if(p.empty() || p[p.size()-1] != '/')
2281 p += "/";
2285 // now look for the file
2286 kwsys_stl::string tryPath;
2287 for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
2288 p != path.end(); ++p)
2290 tryPath = *p;
2291 tryPath += name;
2292 if(SystemTools::FileExists(tryPath.c_str()))
2294 return tryPath;
2297 // Couldn't find the file.
2298 return "";
2302 * Find the file the given name. Searches the given path and then
2303 * the system search path. Returns the full path to the file if it is
2304 * found. Otherwise, the empty string is returned.
2306 kwsys_stl::string SystemTools
2307 ::FindFile(const char* name,
2308 const kwsys_stl::vector<kwsys_stl::string>& userPaths,
2309 bool no_system_path)
2311 kwsys_stl::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
2312 if(tryPath != "" && !SystemTools::FileIsDirectory(tryPath.c_str()))
2314 return SystemTools::CollapseFullPath(tryPath.c_str());
2316 // Couldn't find the file.
2317 return "";
2321 * Find the directory the given name. Searches the given path and then
2322 * the system search path. Returns the full path to the directory if it is
2323 * found. Otherwise, the empty string is returned.
2325 kwsys_stl::string SystemTools
2326 ::FindDirectory(const char* name,
2327 const kwsys_stl::vector<kwsys_stl::string>& userPaths,
2328 bool no_system_path)
2330 kwsys_stl::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
2331 if(tryPath != "" && SystemTools::FileIsDirectory(tryPath.c_str()))
2333 return SystemTools::CollapseFullPath(tryPath.c_str());
2335 // Couldn't find the file.
2336 return "";
2340 * Find the executable with the given name. Searches the given path and then
2341 * the system search path. Returns the full path to the executable if it is
2342 * found. Otherwise, the empty string is returned.
2344 kwsys_stl::string SystemTools::FindProgram(
2345 const char* nameIn,
2346 const kwsys_stl::vector<kwsys_stl::string>& userPaths,
2347 bool no_system_path)
2349 if(!nameIn || !*nameIn)
2351 return "";
2353 kwsys_stl::string name = nameIn;
2354 kwsys_stl::vector<kwsys_stl::string> extensions;
2355 #if defined (_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
2356 bool hasExtension = false;
2357 // check to see if the name already has a .xxx at
2358 // the end of it
2359 if(name.size() > 3 && name[name.size()-4] == '.')
2361 hasExtension = true;
2363 // on windows try .com then .exe
2364 if(!hasExtension)
2366 extensions.push_back(".com");
2367 extensions.push_back(".exe");
2369 #endif
2370 kwsys_stl::string tryPath;
2372 // first try with extensions if the os supports them
2373 if(extensions.size())
2375 for(kwsys_stl::vector<kwsys_stl::string>::iterator i =
2376 extensions.begin(); i != extensions.end(); ++i)
2378 tryPath = name;
2379 tryPath += *i;
2380 if(SystemTools::FileExists(tryPath.c_str()) &&
2381 !SystemTools::FileIsDirectory(tryPath.c_str()))
2383 return SystemTools::CollapseFullPath(tryPath.c_str());
2387 // now try just the name
2388 tryPath = name;
2389 if(SystemTools::FileExists(tryPath.c_str()) &&
2390 !SystemTools::FileIsDirectory(tryPath.c_str()))
2392 return SystemTools::CollapseFullPath(tryPath.c_str());
2394 // now construct the path
2395 kwsys_stl::vector<kwsys_stl::string> path;
2396 // Add the system search path to our path.
2397 if (!no_system_path)
2399 SystemTools::GetPath(path);
2401 // now add the additional paths
2403 for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i =
2404 userPaths.begin(); i != userPaths.end(); ++i)
2406 path.push_back(*i);
2409 // Add a trailing slash to all paths to aid the search process.
2411 for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
2412 i != path.end(); ++i)
2414 kwsys_stl::string& p = *i;
2415 if(p.empty() || p[p.size()-1] != '/')
2417 p += "/";
2421 // Try each path
2422 for(kwsys_stl::vector<kwsys_stl::string>::iterator p = path.begin();
2423 p != path.end(); ++p)
2425 #ifdef _WIN32
2426 // Remove double quotes from the path on windows
2427 SystemTools::ReplaceString(*p, "\"", "");
2428 #endif
2429 // first try with extensions
2430 if(extensions.size())
2432 for(kwsys_stl::vector<kwsys_stl::string>::iterator ext
2433 = extensions.begin(); ext != extensions.end(); ++ext)
2435 tryPath = *p;
2436 tryPath += name;
2437 tryPath += *ext;
2438 if(SystemTools::FileExists(tryPath.c_str()) &&
2439 !SystemTools::FileIsDirectory(tryPath.c_str()))
2441 return SystemTools::CollapseFullPath(tryPath.c_str());
2445 // now try it without them
2446 tryPath = *p;
2447 tryPath += name;
2448 if(SystemTools::FileExists(tryPath.c_str()) &&
2449 !SystemTools::FileIsDirectory(tryPath.c_str()))
2451 return SystemTools::CollapseFullPath(tryPath.c_str());
2454 // Couldn't find the program.
2455 return "";
2458 kwsys_stl::string SystemTools::FindProgram(
2459 const kwsys_stl::vector<kwsys_stl::string>& names,
2460 const kwsys_stl::vector<kwsys_stl::string>& path,
2461 bool noSystemPath)
2463 for(kwsys_stl::vector<kwsys_stl::string>::const_iterator it = names.begin();
2464 it != names.end() ; ++it)
2466 // Try to find the program.
2467 kwsys_stl::string result = SystemTools::FindProgram(it->c_str(),
2468 path,
2469 noSystemPath);
2470 if ( !result.empty() )
2472 return result;
2475 return "";
2479 * Find the library with the given name. Searches the given path and then
2480 * the system search path. Returns the full path to the library if it is
2481 * found. Otherwise, the empty string is returned.
2483 kwsys_stl::string SystemTools
2484 ::FindLibrary(const char* name,
2485 const kwsys_stl::vector<kwsys_stl::string>& userPaths)
2487 // See if the executable exists as written.
2488 if(SystemTools::FileExists(name) &&
2489 !SystemTools::FileIsDirectory(name))
2491 return SystemTools::CollapseFullPath(name);
2494 // Add the system search path to our path.
2495 kwsys_stl::vector<kwsys_stl::string> path;
2496 SystemTools::GetPath(path);
2497 // now add the additional paths
2499 for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
2500 i != userPaths.end(); ++i)
2502 path.push_back(*i);
2505 // Add a trailing slash to all paths to aid the search process.
2507 for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
2508 i != path.end(); ++i)
2510 kwsys_stl::string& p = *i;
2511 if(p.empty() || p[p.size()-1] != '/')
2513 p += "/";
2517 kwsys_stl::string tryPath;
2518 for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
2519 p != path.end(); ++p)
2521 #if defined(__APPLE__)
2522 tryPath = *p;
2523 tryPath += name;
2524 tryPath += ".framework";
2525 if(SystemTools::FileExists(tryPath.c_str())
2526 && SystemTools::FileIsDirectory(tryPath.c_str()))
2528 return SystemTools::CollapseFullPath(tryPath.c_str());
2530 #endif
2531 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
2532 tryPath = *p;
2533 tryPath += name;
2534 tryPath += ".lib";
2535 if(SystemTools::FileExists(tryPath.c_str())
2536 && !SystemTools::FileIsDirectory(tryPath.c_str()))
2538 return SystemTools::CollapseFullPath(tryPath.c_str());
2540 #else
2541 tryPath = *p;
2542 tryPath += "lib";
2543 tryPath += name;
2544 tryPath += ".so";
2545 if(SystemTools::FileExists(tryPath.c_str())
2546 && !SystemTools::FileIsDirectory(tryPath.c_str()))
2548 return SystemTools::CollapseFullPath(tryPath.c_str());
2550 tryPath = *p;
2551 tryPath += "lib";
2552 tryPath += name;
2553 tryPath += ".a";
2554 if(SystemTools::FileExists(tryPath.c_str())
2555 && !SystemTools::FileIsDirectory(tryPath.c_str()))
2557 return SystemTools::CollapseFullPath(tryPath.c_str());
2559 tryPath = *p;
2560 tryPath += "lib";
2561 tryPath += name;
2562 tryPath += ".sl";
2563 if(SystemTools::FileExists(tryPath.c_str())
2564 && !SystemTools::FileIsDirectory(tryPath.c_str()))
2566 return SystemTools::CollapseFullPath(tryPath.c_str());
2568 tryPath = *p;
2569 tryPath += "lib";
2570 tryPath += name;
2571 tryPath += ".dylib";
2572 if(SystemTools::FileExists(tryPath.c_str())
2573 && !SystemTools::FileIsDirectory(tryPath.c_str()))
2575 return SystemTools::CollapseFullPath(tryPath.c_str());
2577 tryPath = *p;
2578 tryPath += "lib";
2579 tryPath += name;
2580 tryPath += ".dll";
2581 if(SystemTools::FileExists(tryPath.c_str())
2582 && !SystemTools::FileIsDirectory(tryPath.c_str()))
2584 return SystemTools::CollapseFullPath(tryPath.c_str());
2586 #endif
2589 // Couldn't find the library.
2590 return "";
2593 kwsys_stl::string SystemTools::GetRealPath(const char* path)
2595 kwsys_stl::string ret;
2596 Realpath(path, ret);
2597 return ret;
2600 bool SystemTools::FileIsDirectory(const char* name)
2602 // Remove any trailing slash from the name.
2603 char buffer[KWSYS_SYSTEMTOOLS_MAXPATH];
2604 size_t last = strlen(name)-1;
2605 if(last > 0 && (name[last] == '/' || name[last] == '\\')
2606 && strcmp(name, "/") !=0)
2608 memcpy(buffer, name, last);
2609 buffer[last] = 0;
2610 name = buffer;
2613 // Now check the file node type.
2614 struct stat fs;
2615 if(stat(name, &fs) == 0)
2617 #if defined( _WIN32 )
2618 return ((fs.st_mode & _S_IFDIR) != 0);
2619 #else
2620 return S_ISDIR(fs.st_mode);
2621 #endif
2623 else
2625 return false;
2629 bool SystemTools::FileIsSymlink(const char* name)
2631 #if defined( _WIN32 )
2632 (void)name;
2633 return false;
2634 #else
2635 struct stat fs;
2636 if(lstat(name, &fs) == 0)
2638 return S_ISLNK(fs.st_mode);
2640 else
2642 return false;
2644 #endif
2647 #if defined(_WIN32) && !defined(__CYGWIN__)
2648 bool SystemTools::CreateSymlink(const char*, const char*)
2650 return false;
2652 #else
2653 bool SystemTools::CreateSymlink(const char* origName, const char* newName)
2655 return symlink(origName, newName) >= 0;
2657 #endif
2659 #if defined(_WIN32) && !defined(__CYGWIN__)
2660 bool SystemTools::ReadSymlink(const char*, kwsys_stl::string&)
2662 return false;
2664 #else
2665 bool SystemTools::ReadSymlink(const char* newName,
2666 kwsys_stl::string& origName)
2668 char buf[KWSYS_SYSTEMTOOLS_MAXPATH+1];
2669 int count =
2670 static_cast<int>(readlink(newName, buf, KWSYS_SYSTEMTOOLS_MAXPATH));
2671 if(count >= 0)
2673 // Add null-terminator.
2674 buf[count] = 0;
2675 origName = buf;
2676 return true;
2678 else
2680 return false;
2683 #endif
2685 int SystemTools::ChangeDirectory(const char *dir)
2687 return Chdir(dir);
2690 kwsys_stl::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
2692 char buf[2048];
2693 const char* cwd = Getcwd(buf, 2048);
2694 kwsys_stl::string path;
2695 if ( cwd )
2697 path = cwd;
2699 if(collapse)
2701 return SystemTools::CollapseFullPath(path.c_str());
2703 return path;
2706 kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
2708 kwsys_stl::string dir, file;
2709 SystemTools::SplitProgramPath(in_name, dir, file);
2710 return dir;
2713 bool SystemTools::SplitProgramPath(const char* in_name,
2714 kwsys_stl::string& dir,
2715 kwsys_stl::string& file,
2716 bool)
2718 dir = in_name;
2719 file = "";
2720 SystemTools::ConvertToUnixSlashes(dir);
2722 if(!SystemTools::FileIsDirectory(dir.c_str()))
2724 kwsys_stl::string::size_type slashPos = dir.rfind("/");
2725 if(slashPos != kwsys_stl::string::npos)
2727 file = dir.substr(slashPos+1);
2728 dir = dir.substr(0, slashPos);
2730 else
2732 file = dir;
2733 dir = "";
2736 if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
2738 kwsys_stl::string oldDir = in_name;
2739 SystemTools::ConvertToUnixSlashes(oldDir);
2740 dir = in_name;
2741 return false;
2743 return true;
2746 bool SystemTools::FindProgramPath(const char* argv0,
2747 kwsys_stl::string& pathOut,
2748 kwsys_stl::string& errorMsg,
2749 const char* exeName,
2750 const char* buildDir,
2751 const char* installPrefix )
2753 kwsys_stl::vector<kwsys_stl::string> failures;
2754 kwsys_stl::string self = argv0 ? argv0 : "";
2755 failures.push_back(self);
2756 SystemTools::ConvertToUnixSlashes(self);
2757 self = SystemTools::FindProgram(self.c_str());
2758 if(!SystemTools::FileExists(self.c_str()))
2760 if(buildDir)
2762 kwsys_stl::string intdir = ".";
2763 #ifdef CMAKE_INTDIR
2764 intdir = CMAKE_INTDIR;
2765 #endif
2766 self = buildDir;
2767 self += "/bin/";
2768 self += intdir;
2769 self += "/";
2770 self += exeName;
2771 self += SystemTools::GetExecutableExtension();
2774 if(installPrefix)
2776 if(!SystemTools::FileExists(self.c_str()))
2778 failures.push_back(self);
2779 self = installPrefix;
2780 self += "/bin/";
2781 self += exeName;
2784 if(!SystemTools::FileExists(self.c_str()))
2786 failures.push_back(self);
2787 kwsys_ios::ostringstream msg;
2788 msg << "Can not find the command line program ";
2789 if (exeName)
2791 msg << exeName;
2793 msg << "\n";
2794 if (argv0)
2796 msg << " argv[0] = \"" << argv0 << "\"\n";
2798 msg << " Attempted paths:\n";
2799 kwsys_stl::vector<kwsys_stl::string>::iterator i;
2800 for(i=failures.begin(); i != failures.end(); ++i)
2802 msg << " \"" << i->c_str() << "\"\n";
2804 errorMsg = msg.str();
2805 return false;
2807 pathOut = self;
2808 return true;
2812 kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
2814 return SystemTools::CollapseFullPath(in_relative, 0);
2817 void SystemTools::AddTranslationPath(const char * a, const char * b)
2819 kwsys_stl::string path_a = a;
2820 kwsys_stl::string path_b = b;
2821 SystemTools::ConvertToUnixSlashes(path_a);
2822 SystemTools::ConvertToUnixSlashes(path_b);
2823 // First check this is a directory path, since we don't want the table to
2824 // grow too fat
2825 if( SystemTools::FileIsDirectory( path_a.c_str() ) )
2827 // Make sure the path is a full path and does not contain no '..'
2828 // Ken--the following code is incorrect. .. can be in a valid path
2829 // for example /home/martink/MyHubba...Hubba/Src
2830 if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
2831 == kwsys_stl::string::npos )
2833 // Before inserting make sure path ends with '/'
2834 if(path_a.size() && path_a[path_a.size() -1] != '/')
2836 path_a += '/';
2838 if(path_b.size() && path_b[path_b.size() -1] != '/')
2840 path_b += '/';
2842 if( !(path_a == path_b) )
2844 SystemTools::TranslationMap->insert(
2845 SystemToolsTranslationMap::value_type(path_a, path_b));
2851 void SystemTools::AddKeepPath(const char* dir)
2853 kwsys_stl::string cdir;
2854 Realpath(SystemTools::CollapseFullPath(dir).c_str(), cdir);
2855 SystemTools::AddTranslationPath(cdir.c_str(), dir);
2858 void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
2860 // Do not translate paths that are too short to have meaningful
2861 // translations.
2862 if(path.size() < 2)
2864 return;
2867 // Always add a trailing slash before translation. It does not
2868 // matter if this adds an extra slash, but we do not want to
2869 // translate part of a directory (like the foo part of foo-dir).
2870 path += "/";
2872 // In case a file was specified we still have to go through this:
2873 // Now convert any path found in the table back to the one desired:
2874 kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
2875 for(it = SystemTools::TranslationMap->begin();
2876 it != SystemTools::TranslationMap->end();
2877 ++it )
2879 // We need to check of the path is a substring of the other path
2880 if(path.find( it->first ) == 0)
2882 path = path.replace( 0, it->first.size(), it->second);
2886 // Remove the trailing slash we added before.
2887 path.erase(path.end()-1, path.end());
2890 void
2891 SystemToolsAppendComponents(
2892 kwsys_stl::vector<kwsys_stl::string>& out_components,
2893 kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
2894 kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
2896 for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = first;
2897 i != last; ++i)
2899 if(*i == "..")
2901 if(out_components.begin() != out_components.end())
2903 out_components.erase(out_components.end()-1, out_components.end());
2906 else if(!(*i == ".") && !(*i == ""))
2908 out_components.push_back(*i);
2913 kwsys_stl::string SystemTools::CollapseFullPath(const char* in_path,
2914 const char* in_base)
2916 // Collect the output path components.
2917 kwsys_stl::vector<kwsys_stl::string> out_components;
2919 // Split the input path components.
2920 kwsys_stl::vector<kwsys_stl::string> path_components;
2921 SystemTools::SplitPath(in_path, path_components);
2923 // If the input path is relative, start with a base path.
2924 if(path_components[0].length() == 0)
2926 kwsys_stl::vector<kwsys_stl::string> base_components;
2927 if(in_base)
2929 // Use the given base path.
2930 SystemTools::SplitPath(in_base, base_components);
2932 else
2934 // Use the current working directory as a base path.
2935 char buf[2048];
2936 if(const char* cwd = Getcwd(buf, 2048))
2938 SystemTools::SplitPath(cwd, base_components);
2940 else
2942 // ??
2946 // Append base path components to the output path.
2947 out_components.push_back(base_components[0]);
2948 SystemToolsAppendComponents(out_components,
2949 base_components.begin()+1,
2950 base_components.end());
2953 // Append input path components to the output path.
2954 SystemToolsAppendComponents(out_components,
2955 path_components.begin(),
2956 path_components.end());
2958 // Transform the path back to a string.
2959 kwsys_stl::string newPath = SystemTools::JoinPath(out_components);
2961 // Update the translation table with this potentially new path. I am not
2962 // sure why this line is here, it seems really questionable, but yet I
2963 // would put good money that if I remove it something will break, basically
2964 // from what I can see it created a mapping from the collapsed path, to be
2965 // replaced by the input path, which almost completely does the opposite of
2966 // this function, the only thing preventing this from happening a lot is
2967 // that if the in_path has a .. in it, then it is not added to the
2968 // translation table. So for most calls this either does nothing due to the
2969 // .. or it adds a translation between identical paths as nothing was
2970 // collapsed, so I am going to try to comment it out, and see what hits the
2971 // fan, hopefully quickly.
2972 // Commented out line below:
2973 //SystemTools::AddTranslationPath(newPath.c_str(), in_path);
2975 SystemTools::CheckTranslationPath(newPath);
2976 #ifdef _WIN32
2977 newPath = SystemTools::GetActualCaseForPath(newPath.c_str());
2978 SystemTools::ConvertToUnixSlashes(newPath);
2979 #endif
2980 // Return the reconstructed path.
2981 return newPath;
2984 // compute the relative path from here to there
2985 kwsys_stl::string SystemTools::RelativePath(const char* local, const char* remote)
2987 if(!SystemTools::FileIsFullPath(local))
2989 return "";
2991 if(!SystemTools::FileIsFullPath(remote))
2993 return "";
2996 // split up both paths into arrays of strings using / as a separator
2997 kwsys_stl::vector<kwsys::String> localSplit = SystemTools::SplitString(local, '/', true);
2998 kwsys_stl::vector<kwsys::String> remoteSplit = SystemTools::SplitString(remote, '/', true);
2999 kwsys_stl::vector<kwsys::String> commonPath; // store shared parts of path in this array
3000 kwsys_stl::vector<kwsys::String> finalPath; // store the final relative path here
3001 // count up how many matching directory names there are from the start
3002 unsigned int sameCount = 0;
3003 while(
3004 ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1)))
3006 // for windows and apple do a case insensitive string compare
3007 #if defined(_WIN32) || defined(__APPLE__)
3008 SystemTools::Strucmp(localSplit[sameCount].c_str(),
3009 remoteSplit[sameCount].c_str()) == 0
3010 #else
3011 localSplit[sameCount] == remoteSplit[sameCount]
3012 #endif
3015 // put the common parts of the path into the commonPath array
3016 commonPath.push_back(localSplit[sameCount]);
3017 // erase the common parts of the path from the original path arrays
3018 localSplit[sameCount] = "";
3019 remoteSplit[sameCount] = "";
3020 sameCount++;
3023 // If there is nothing in common at all then just return the full
3024 // path. This is the case only on windows when the paths have
3025 // different drive letters. On unix two full paths always at least
3026 // have the root "/" in common so we will return a relative path
3027 // that passes through the root directory.
3028 if(sameCount == 0)
3030 return remote;
3033 // for each entry that is not common in the local path
3034 // add a ../ to the finalpath array, this gets us out of the local
3035 // path into the remote dir
3036 for(unsigned int i = 0; i < localSplit.size(); ++i)
3038 if(localSplit[i].size())
3040 finalPath.push_back("../");
3043 // for each entry that is not common in the remote path add it
3044 // to the final path.
3045 for(kwsys_stl::vector<String>::iterator vit = remoteSplit.begin();
3046 vit != remoteSplit.end(); ++vit)
3048 if(vit->size())
3050 finalPath.push_back(*vit);
3053 kwsys_stl::string relativePath; // result string
3054 // now turn the array of directories into a unix path by puttint /
3055 // between each entry that does not already have one
3056 for(kwsys_stl::vector<String>::iterator vit1 = finalPath.begin();
3057 vit1 != finalPath.end(); ++vit1)
3059 if(relativePath.size() && relativePath[relativePath.size()-1] != '/')
3061 relativePath += "/";
3063 relativePath += *vit1;
3065 return relativePath;
3068 // OK, some fun stuff to get the actual case of a given path.
3069 // Basically, you just need to call ShortPath, then GetLongPathName,
3070 // However, GetLongPathName is not implemented on windows NT and 95,
3071 // so we have to simulate it on those versions
3072 #ifdef _WIN32
3073 int OldWindowsGetLongPath(kwsys_stl::string const& shortPath,
3074 kwsys_stl::string& longPath )
3076 kwsys_stl::string::size_type iFound = shortPath.rfind('/');
3077 if (iFound > 1 && iFound != shortPath.npos)
3079 // recurse to peel off components
3081 if (OldWindowsGetLongPath(shortPath.substr(0, iFound), longPath) > 0)
3083 longPath += '/';
3084 if (shortPath[1] != '/')
3086 WIN32_FIND_DATA findData;
3088 // append the long component name to the path
3090 if (INVALID_HANDLE_VALUE != ::FindFirstFile
3091 (shortPath.c_str(), &findData))
3093 longPath += findData.cFileName;
3095 else
3097 // if FindFirstFile fails, return the error code
3099 longPath = "";
3100 return 0;
3105 else
3107 longPath = shortPath;
3109 return (int)longPath.size();
3113 int PortableGetLongPathName(const char* pathIn,
3114 kwsys_stl::string & longPath)
3116 HMODULE lh = LoadLibrary("Kernel32.dll");
3117 if(lh)
3119 FARPROC proc = GetProcAddress(lh, "GetLongPathNameA");
3120 if(proc)
3122 typedef DWORD (WINAPI * GetLongFunctionPtr) (LPCSTR,LPSTR,DWORD);
3123 GetLongFunctionPtr func = (GetLongFunctionPtr)proc;
3124 char buffer[MAX_PATH+1];
3125 int len = (*func)(pathIn, buffer, MAX_PATH+1);
3126 if(len == 0 || len > MAX_PATH+1)
3128 FreeLibrary(lh);
3129 return 0;
3131 longPath = buffer;
3132 FreeLibrary(lh);
3133 return len;
3135 FreeLibrary(lh);
3137 return OldWindowsGetLongPath(pathIn, longPath);
3139 #endif
3142 //----------------------------------------------------------------------------
3143 kwsys_stl::string SystemTools::GetActualCaseForPath(const char* p)
3145 #ifndef _WIN32
3146 return p;
3147 #else
3148 // Check to see if actual case has already been called
3149 // for this path, and the result is stored in the LongPathMap
3150 SystemToolsTranslationMap::iterator i =
3151 SystemTools::LongPathMap->find(p);
3152 if(i != SystemTools::LongPathMap->end())
3154 return i->second;
3156 kwsys_stl::string shortPath;
3157 if(!SystemTools::GetShortPath(p, shortPath))
3159 return p;
3161 kwsys_stl::string longPath;
3162 int len = PortableGetLongPathName(shortPath.c_str(), longPath);
3163 if(len == 0 || len > MAX_PATH+1)
3165 return p;
3167 // Use original path if conversion back to a long path failed.
3168 if(longPath == shortPath)
3170 longPath = p;
3172 // make sure drive letter is always upper case
3173 if(longPath.size() > 1 && longPath[1] == ':')
3175 longPath[0] = toupper(longPath[0]);
3177 (*SystemTools::LongPathMap)[p] = longPath;
3178 return longPath;
3179 #endif
3182 //----------------------------------------------------------------------------
3183 const char* SystemTools::SplitPathRootComponent(const char* p,
3184 kwsys_stl::string* root)
3186 // Identify the root component.
3187 const char* c = p;
3188 if((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\'))
3190 // Network path.
3191 if(root)
3193 *root = "//";
3195 c += 2;
3197 else if(c[0] == '/')
3199 // Unix path.
3200 if(root)
3202 *root = "/";
3204 c += 1;
3206 else if(c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\'))
3208 // Windows path.
3209 if(root)
3211 (*root) = "_:/";
3212 (*root)[0] = c[0];
3214 c += 3;
3216 else if(c[0] && c[1] == ':')
3218 // Path relative to a windows drive working directory.
3219 if(root)
3221 (*root) = "_:";
3222 (*root)[0] = c[0];
3224 c += 2;
3226 else if(c[0] == '~')
3228 // Home directory. The returned root should always have a
3229 // trailing slash so that appending components as
3230 // c[0]c[1]/c[2]/... works. The remaining path returned should
3231 // skip the first slash if it exists:
3233 // "~" : root = "~/" , return ""
3234 // "~/ : root = "~/" , return ""
3235 // "~/x : root = "~/" , return "x"
3236 // "~u" : root = "~u/", return ""
3237 // "~u/" : root = "~u/", return ""
3238 // "~u/x" : root = "~u/", return "x"
3239 size_t n = 1;
3240 while(c[n] && c[n] != '/')
3242 ++n;
3244 if(root)
3246 root->assign(c, n);
3247 *root += '/';
3249 if(c[n] == '/')
3251 ++n;
3253 c += n;
3255 else
3257 // Relative path.
3258 if(root)
3260 *root = "";
3264 // Return the remaining path.
3265 return c;
3268 //----------------------------------------------------------------------------
3269 void SystemTools::SplitPath(const char* p,
3270 kwsys_stl::vector<kwsys_stl::string>& components,
3271 bool expand_home_dir)
3273 const char* c = p;
3274 components.clear();
3276 // Identify the root component.
3278 kwsys_stl::string root;
3279 c = SystemTools::SplitPathRootComponent(c, &root);
3281 // Expand home directory references if requested.
3282 if(expand_home_dir && !root.empty() && root[0] == '~')
3284 kwsys_stl::string homedir;
3285 root = root.substr(0, root.size()-1);
3286 if(root.size() == 1)
3288 #if defined(_WIN32) && !defined(__CYGWIN__)
3289 if(const char* userp = getenv("USERPROFILE"))
3291 homedir = userp;
3293 else
3294 #endif
3295 if(const char* h = getenv("HOME"))
3297 homedir = h;
3300 #ifdef HAVE_GETPWNAM
3301 else if(passwd* pw = getpwnam(root.c_str()+1))
3303 if(pw->pw_dir)
3305 homedir = pw->pw_dir;
3308 #endif
3309 if(!homedir.empty() && (homedir[homedir.size()-1] == '/' ||
3310 homedir[homedir.size()-1] == '\\'))
3312 homedir = homedir.substr(0, homedir.size()-1);
3314 SystemTools::SplitPath(homedir.c_str(), components);
3316 else
3318 components.push_back(root);
3322 // Parse the remaining components.
3323 const char* first = c;
3324 const char* last = first;
3325 for(;*last; ++last)
3327 if(*last == '/' || *last == '\\')
3329 // End of a component. Save it.
3330 components.push_back(
3331 kwsys_stl::string(first,static_cast<kwsys_stl::string::size_type>(
3332 last-first)));
3333 first = last+1;
3337 // Save the last component unless there were no components.
3338 if(last != c)
3340 components.push_back(
3341 kwsys_stl::string(first,static_cast<kwsys_stl::string::size_type>(
3342 last-first)));
3346 //----------------------------------------------------------------------------
3347 kwsys_stl::string
3348 SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components)
3350 return SystemTools::JoinPath(components.begin(), components.end());
3353 //----------------------------------------------------------------------------
3354 kwsys_stl::string
3355 SystemTools
3356 ::JoinPath(kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
3357 kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
3359 // Construct result in a single string.
3360 kwsys_stl::string result;
3362 // The first two components do not add a slash.
3363 if(first != last)
3365 result.append(*first++);
3367 if(first != last)
3369 result.append(*first++);
3372 // All remaining components are always separated with a slash.
3373 while(first != last)
3375 result.append("/");
3376 result.append((*first++));
3379 // Return the concatenated result.
3380 return result;
3383 //----------------------------------------------------------------------------
3384 bool SystemTools::ComparePath(const char* c1, const char* c2)
3386 #if defined(_WIN32) || defined(__APPLE__)
3387 # ifdef _MSC_VER
3388 return _stricmp(c1, c2) == 0;
3389 # elif defined(__APPLE__) || defined(__GNUC__)
3390 return strcasecmp(c1, c2) == 0;
3391 #else
3392 return SystemTools::Strucmp(c1, c2) == 0;
3393 # endif
3394 #else
3395 return strcmp(c1, c2) == 0;
3396 #endif
3399 //----------------------------------------------------------------------------
3400 bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines, char separator)
3402 kwsys_stl::string data(str);
3403 kwsys_stl::string::size_type lpos = 0;
3404 while(lpos < data.length())
3406 kwsys_stl::string::size_type rpos = data.find_first_of(separator, lpos);
3407 if(rpos == kwsys_stl::string::npos)
3409 // Line ends at end of string without a newline.
3410 lines.push_back(data.substr(lpos));
3411 return false;
3413 else
3415 // Line ends in a "\n", remove the character.
3416 lines.push_back(data.substr(lpos, rpos-lpos));
3418 lpos = rpos+1;
3420 return true;
3423 //----------------------------------------------------------------------------
3424 bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
3426 kwsys_stl::string data(str);
3427 kwsys_stl::string::size_type lpos = 0;
3428 while(lpos < data.length())
3430 kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
3431 if(rpos == kwsys_stl::string::npos)
3433 // Line ends at end of string without a newline.
3434 lines.push_back(data.substr(lpos));
3435 return false;
3437 if((rpos > lpos) && (data[rpos-1] == '\r'))
3439 // Line ends in a "\r\n" pair, remove both characters.
3440 lines.push_back(data.substr(lpos, (rpos-1)-lpos));
3442 else
3444 // Line ends in a "\n", remove the character.
3445 lines.push_back(data.substr(lpos, rpos-lpos));
3447 lpos = rpos+1;
3449 return true;
3453 * Return path of a full filename (no trailing slashes).
3454 * Warning: returned path is converted to Unix slashes format.
3456 kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
3458 kwsys_stl::string fn = filename;
3459 SystemTools::ConvertToUnixSlashes(fn);
3461 kwsys_stl::string::size_type slash_pos = fn.rfind("/");
3462 if(slash_pos != kwsys_stl::string::npos)
3464 kwsys_stl::string ret = fn.substr(0, slash_pos);
3465 if(ret.size() == 2 && ret[1] == ':')
3467 return ret + '/';
3469 if(ret.size() == 0)
3471 return "/";
3473 return ret;
3475 else
3477 return "";
3483 * Return file name of a full filename (i.e. file name without path).
3485 kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
3487 #if defined(_WIN32)
3488 kwsys_stl::string::size_type slash_pos = filename.find_last_of("/\\");
3489 #else
3490 kwsys_stl::string::size_type slash_pos = filename.find_last_of("/");
3491 #endif
3492 if(slash_pos != kwsys_stl::string::npos)
3494 return filename.substr(slash_pos + 1);
3496 else
3498 return filename;
3504 * Return file extension of a full filename (dot included).
3505 * Warning: this is the longest extension (for example: .tar.gz)
3507 kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
3509 kwsys_stl::string name = SystemTools::GetFilenameName(filename);
3510 kwsys_stl::string::size_type dot_pos = name.find(".");
3511 if(dot_pos != kwsys_stl::string::npos)
3513 return name.substr(dot_pos);
3515 else
3517 return "";
3522 * Return file extension of a full filename (dot included).
3523 * Warning: this is the shortest extension (for example: .gz of .tar.gz)
3525 kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
3527 kwsys_stl::string name = SystemTools::GetFilenameName(filename);
3528 kwsys_stl::string::size_type dot_pos = name.rfind(".");
3529 if(dot_pos != kwsys_stl::string::npos)
3531 return name.substr(dot_pos);
3533 else
3535 return "";
3540 * Return file name without extension of a full filename (i.e. without path).
3541 * Warning: it considers the longest extension (for example: .tar.gz)
3543 kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
3545 kwsys_stl::string name = SystemTools::GetFilenameName(filename);
3546 kwsys_stl::string::size_type dot_pos = name.find(".");
3547 if(dot_pos != kwsys_stl::string::npos)
3549 return name.substr(0, dot_pos);
3551 else
3553 return name;
3559 * Return file name without extension of a full filename (i.e. without path).
3560 * Warning: it considers the last extension (for example: removes .gz
3561 * from .tar.gz)
3563 kwsys_stl::string
3564 SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
3566 kwsys_stl::string name = SystemTools::GetFilenameName(filename);
3567 kwsys_stl::string::size_type dot_pos = name.rfind(".");
3568 if(dot_pos != kwsys_stl::string::npos)
3570 return name.substr(0, dot_pos);
3572 else
3574 return name;
3578 bool SystemTools::FileHasSignature(const char *filename,
3579 const char *signature,
3580 long offset)
3582 if (!filename || !signature)
3584 return false;
3587 FILE *fp;
3588 fp = fopen(filename, "rb");
3589 if (!fp)
3591 return false;
3594 fseek(fp, offset, SEEK_SET);
3596 bool res = false;
3597 size_t signature_len = strlen(signature);
3598 char *buffer = new char [signature_len];
3600 if (fread(buffer, 1, signature_len, fp) == signature_len)
3602 res = (!strncmp(buffer, signature, signature_len) ? true : false);
3605 delete [] buffer;
3607 fclose(fp);
3608 return res;
3611 SystemTools::FileTypeEnum
3612 SystemTools::DetectFileType(const char *filename,
3613 unsigned long length,
3614 double percent_bin)
3616 if (!filename || percent_bin < 0)
3618 return SystemTools::FileTypeUnknown;
3621 FILE *fp;
3622 fp = fopen(filename, "rb");
3623 if (!fp)
3625 return SystemTools::FileTypeUnknown;
3628 // Allocate buffer and read bytes
3630 unsigned char *buffer = new unsigned char [length];
3631 size_t read_length = fread(buffer, 1, length, fp);
3632 fclose(fp);
3633 if (read_length == 0)
3635 return SystemTools::FileTypeUnknown;
3638 // Loop over contents and count
3640 size_t text_count = 0;
3642 const unsigned char *ptr = buffer;
3643 const unsigned char *buffer_end = buffer + read_length;
3645 while (ptr != buffer_end)
3647 if ((*ptr >= 0x20 && *ptr <= 0x7F) ||
3648 *ptr == '\n' ||
3649 *ptr == '\r' ||
3650 *ptr == '\t')
3652 text_count++;
3654 ptr++;
3657 delete [] buffer;
3659 double current_percent_bin =
3660 (static_cast<double>(read_length - text_count) /
3661 static_cast<double>(read_length));
3663 if (current_percent_bin >= percent_bin)
3665 return SystemTools::FileTypeBinary;
3668 return SystemTools::FileTypeText;
3671 bool SystemTools::LocateFileInDir(const char *filename,
3672 const char *dir,
3673 kwsys_stl::string& filename_found,
3674 int try_filename_dirs)
3676 if (!filename || !dir)
3678 return false;
3681 // Get the basename of 'filename'
3683 kwsys_stl::string filename_base = SystemTools::GetFilenameName(filename);
3685 // Check if 'dir' is really a directory
3686 // If win32 and matches something like C:, accept it as a dir
3688 kwsys_stl::string real_dir;
3689 if (!SystemTools::FileIsDirectory(dir))
3691 #if defined( _WIN32 )
3692 size_t dir_len = strlen(dir);
3693 if (dir_len < 2 || dir[dir_len - 1] != ':')
3695 #endif
3696 real_dir = SystemTools::GetFilenamePath(dir);
3697 dir = real_dir.c_str();
3698 #if defined( _WIN32 )
3700 #endif
3703 // Try to find the file in 'dir'
3705 bool res = false;
3706 if (filename_base.size() && dir)
3708 size_t dir_len = strlen(dir);
3709 int need_slash =
3710 (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
3712 kwsys_stl::string temp = dir;
3713 if (need_slash)
3715 temp += "/";
3717 temp += filename_base;
3719 if (SystemTools::FileExists(temp.c_str()))
3721 res = true;
3722 filename_found = temp;
3725 // If not found, we can try harder by appending part of the file to
3726 // to the directory to look inside.
3727 // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
3728 // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
3730 else if (try_filename_dirs)
3732 kwsys_stl::string filename_dir(filename);
3733 kwsys_stl::string filename_dir_base;
3734 kwsys_stl::string filename_dir_bases;
3737 filename_dir = SystemTools::GetFilenamePath(filename_dir);
3738 filename_dir_base = SystemTools::GetFilenameName(filename_dir);
3739 #if defined( _WIN32 )
3740 if (!filename_dir_base.size() ||
3741 filename_dir_base[filename_dir_base.size() - 1] == ':')
3742 #else
3743 if (!filename_dir_base.size())
3744 #endif
3746 break;
3749 filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
3751 temp = dir;
3752 if (need_slash)
3754 temp += "/";
3756 temp += filename_dir_bases;
3758 res = SystemTools::LocateFileInDir(
3759 filename_base.c_str(), temp.c_str(), filename_found, 0);
3761 } while (!res && filename_dir_base.size());
3765 return res;
3768 bool SystemTools::FileIsFullPath(const char* in_name)
3770 kwsys_stl::string name = in_name;
3771 #if defined(_WIN32) || defined(__CYGWIN__)
3772 // On Windows, the name must be at least two characters long.
3773 if(name.length() < 2)
3775 return false;
3777 if(name[1] == ':')
3779 return true;
3781 if(name[0] == '\\')
3783 return true;
3785 #else
3786 // On UNIX, the name must be at least one character long.
3787 if(name.length() < 1)
3789 return false;
3791 #endif
3792 #if !defined(_WIN32)
3793 if(name[0] == '~')
3795 return true;
3797 #endif
3798 // On UNIX, the name must begin in a '/'.
3799 // On Windows, if the name begins in a '/', then it is a full
3800 // network path.
3801 if(name[0] == '/')
3803 return true;
3805 return false;
3808 bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
3810 #if defined(WIN32) && !defined(__CYGWIN__)
3811 const int size = int(strlen(path)) +1; // size of return
3812 char *buffer = new char[size]; // create a buffer
3813 char *tempPath = new char[size]; // create a buffer
3814 int ret;
3816 // if the path passed in has quotes around it, first remove the quotes
3817 if (path[0] == '"' && path[strlen(path)-1] == '"')
3819 strcpy(tempPath,path+1);
3820 tempPath[strlen(tempPath)-1] = '\0';
3822 else
3824 strcpy(tempPath,path);
3827 buffer[0] = 0;
3828 ret = GetShortPathName(tempPath, buffer, size);
3830 if(buffer[0] == 0 || ret > size)
3832 delete [] buffer;
3833 delete [] tempPath;
3834 return false;
3836 else
3838 shortPath = buffer;
3839 delete [] buffer;
3840 delete [] tempPath;
3841 return true;
3843 #else
3844 shortPath = path;
3845 return true;
3846 #endif
3849 void SystemTools::SplitProgramFromArgs(const char* path,
3850 kwsys_stl::string& program, kwsys_stl::string& args)
3852 // see if this is a full path to a program
3853 // if so then set program to path and args to nothing
3854 if(SystemTools::FileExists(path))
3856 program = path;
3857 args = "";
3858 return;
3860 // Try to find the program in the path, note the program
3861 // may have spaces in its name so we have to look for it
3862 kwsys_stl::vector<kwsys_stl::string> e;
3863 kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
3864 if(findProg.size())
3866 program = findProg;
3867 args = "";
3868 return;
3871 // Now try and peel off space separated chunks from the end of the string
3872 // so the largest path possible is found allowing for spaces in the path
3873 kwsys_stl::string dir = path;
3874 kwsys_stl::string::size_type spacePos = dir.rfind(' ');
3875 while(spacePos != kwsys_stl::string::npos)
3877 kwsys_stl::string tryProg = dir.substr(0, spacePos);
3878 // See if the file exists
3879 if(SystemTools::FileExists(tryProg.c_str()))
3881 program = tryProg;
3882 // remove trailing spaces from program
3883 kwsys_stl::string::size_type pos = program.size()-1;
3884 while(program[pos] == ' ')
3886 program.erase(pos);
3887 pos--;
3889 args = dir.substr(spacePos, dir.size()-spacePos);
3890 return;
3892 // Now try and find the the program in the path
3893 findProg = SystemTools::FindProgram(tryProg.c_str(), e);
3894 if(findProg.size())
3896 program = findProg;
3897 // remove trailing spaces from program
3898 kwsys_stl::string::size_type pos = program.size()-1;
3899 while(program[pos] == ' ')
3901 program.erase(pos);
3902 pos--;
3904 args = dir.substr(spacePos, dir.size()-spacePos);
3905 return;
3907 // move past the space for the next search
3908 spacePos--;
3909 spacePos = dir.rfind(' ', spacePos);
3912 program = "";
3913 args = "";
3916 kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
3918 char buf[1024];
3919 time_t t;
3920 time(&t);
3921 strftime(buf, sizeof(buf), format, localtime(&t));
3922 return kwsys_stl::string(buf);
3925 kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
3927 kwsys_stl::string str(s);
3928 if (str.find_first_of("0123456789") == 0)
3930 str = "_" + str;
3933 kwsys_stl::string permited_chars("_"
3934 "abcdefghijklmnopqrstuvwxyz"
3935 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3936 "0123456789");
3937 kwsys_stl::string::size_type pos = 0;
3938 while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
3940 str[pos] = '_';
3942 return str;
3945 // Due to a buggy stream library on the HP and another on Mac OS X, we
3946 // need this very carefully written version of getline. Returns true
3947 // if any data were read before the end-of-file was reached.
3948 bool SystemTools::GetLineFromStream(kwsys_ios::istream& is,
3949 kwsys_stl::string& line,
3950 bool* has_newline /* = 0 */,
3951 long sizeLimit /* = -1 */)
3953 const int bufferSize = 1024;
3954 char buffer[bufferSize];
3955 bool haveData = false;
3956 bool haveNewline = false;
3958 // Start with an empty line.
3959 line = "";
3961 long leftToRead = sizeLimit;
3963 // If no characters are read from the stream, the end of file has
3964 // been reached. Clear the fail bit just before reading.
3965 while(!haveNewline &&
3966 leftToRead != 0 &&
3967 (is.clear(is.rdstate() & ~kwsys_ios::ios::failbit),
3968 is.getline(buffer, bufferSize), is.gcount() > 0))
3970 // We have read at least one byte.
3971 haveData = true;
3973 // If newline character was read the gcount includes the character
3974 // but the buffer does not: the end of line has been reached.
3975 size_t length = strlen(buffer);
3976 if(length < static_cast<size_t>(is.gcount()))
3978 haveNewline = true;
3981 // Avoid storing a carriage return character.
3982 if(length > 0 && buffer[length-1] == '\r')
3984 buffer[length-1] = 0;
3987 // if we read too much then truncate the buffer
3988 if (leftToRead > 0)
3990 if (static_cast<long>(length) > leftToRead)
3992 buffer[leftToRead-1] = 0;
3993 leftToRead = 0;
3995 else
3997 leftToRead -= static_cast<long>(length);
4001 // Append the data read to the line.
4002 line.append(buffer);
4005 // Return the results.
4006 if(has_newline)
4008 *has_newline = haveNewline;
4010 return haveData;
4013 int SystemTools::GetTerminalWidth()
4015 int width = -1;
4016 #ifdef HAVE_TTY_INFO
4017 struct winsize ws;
4018 char *columns; /* Unix98 environment variable */
4019 if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
4021 width = ws.ws_col;
4023 if(!isatty(STDOUT_FILENO))
4025 width = -1;
4027 columns = getenv("COLUMNS");
4028 if(columns && *columns)
4030 long t;
4031 char *endptr;
4032 t = strtol(columns, &endptr, 0);
4033 if(endptr && !*endptr && (t>0) && (t<1000))
4035 width = static_cast<int>(t);
4038 if ( width < 9 )
4040 width = -1;
4042 #endif
4043 return width;
4046 bool SystemTools::GetPermissions(const char* file, mode_t& mode)
4048 if ( !file )
4050 return false;
4053 struct stat st;
4054 if ( stat(file, &st) < 0 )
4056 return false;
4058 mode = st.st_mode;
4059 return true;
4062 bool SystemTools::SetPermissions(const char* file, mode_t mode)
4064 if ( !file )
4066 return false;
4068 if ( !SystemTools::FileExists(file) )
4070 return false;
4072 if ( chmod(file, mode) < 0 )
4074 return false;
4077 return true;
4080 kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
4082 return SystemTools::GetFilenamePath(fileOrDir);
4085 bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
4087 if(!*cDir)
4089 return false;
4091 kwsys_stl::string subdir = cSubdir;
4092 kwsys_stl::string dir = cDir;
4093 SystemTools::ConvertToUnixSlashes(dir);
4094 kwsys_stl::string path = subdir;
4097 path = SystemTools::GetParentDirectory(path.c_str());
4098 if(SystemTools::ComparePath(dir.c_str(), path.c_str()))
4100 return true;
4103 while ( path.size() > dir.size() );
4104 return false;
4107 void SystemTools::Delay(unsigned int msec)
4109 #ifdef _WIN32
4110 Sleep(msec);
4111 #else
4112 // The sleep function gives 1 second resolution and the usleep
4113 // function gives 1e-6 second resolution but on some platforms has a
4114 // maximum sleep time of 1 second. This could be re-implemented to
4115 // use select with masked signals or pselect to mask signals
4116 // atomically. If select is given empty sets and zero as the max
4117 // file descriptor but a non-zero timeout it can be used to block
4118 // for a precise amount of time.
4119 if(msec >= 1000)
4121 sleep(msec / 1000);
4122 usleep((msec % 1000) * 1000);
4124 else
4126 usleep(msec * 1000);
4128 #endif
4131 void SystemTools::ConvertWindowsCommandLineToUnixArguments(
4132 const char *cmd_line, int *argc, char ***argv)
4134 if (!cmd_line || !argc || !argv)
4136 return;
4139 // A space delimites an argument except when it is inside a quote
4141 (*argc) = 1;
4143 size_t cmd_line_len = strlen(cmd_line);
4145 size_t i;
4146 for (i = 0; i < cmd_line_len; i++)
4148 while (isspace(cmd_line[i]) && i < cmd_line_len)
4150 i++;
4152 if (i < cmd_line_len)
4154 if (cmd_line[i] == '\"')
4156 i++;
4157 while (cmd_line[i] != '\"' && i < cmd_line_len)
4159 i++;
4161 (*argc)++;
4163 else
4165 while (!isspace(cmd_line[i]) && i < cmd_line_len)
4167 i++;
4169 (*argc)++;
4174 (*argv) = new char* [(*argc) + 1];
4175 (*argv)[(*argc)] = NULL;
4177 // Set the first arg to be the exec name
4179 (*argv)[0] = new char [1024];
4180 #ifdef _WIN32
4181 ::GetModuleFileName(0, (*argv)[0], 1024);
4182 #else
4183 (*argv)[0][0] = '\0';
4184 #endif
4186 // Allocate the others
4188 int j;
4189 for (j = 1; j < (*argc); j++)
4191 (*argv)[j] = new char [cmd_line_len + 10];
4194 // Grab the args
4196 size_t pos;
4197 int argc_idx = 1;
4199 for (i = 0; i < cmd_line_len; i++)
4201 while (isspace(cmd_line[i]) && i < cmd_line_len)
4203 i++;
4205 if (i < cmd_line_len)
4207 if (cmd_line[i] == '\"')
4209 i++;
4210 pos = i;
4211 while (cmd_line[i] != '\"' && i < cmd_line_len)
4213 i++;
4215 memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
4216 (*argv)[argc_idx][i - pos] = '\0';
4217 argc_idx++;
4219 else
4221 pos = i;
4222 while (!isspace(cmd_line[i]) && i < cmd_line_len)
4224 i++;
4226 memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
4227 (*argv)[argc_idx][i - pos] = '\0';
4228 argc_idx++;
4234 kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
4236 kwsys_stl::string res;
4238 #ifdef _WIN32
4239 char buffer[256];
4241 OSVERSIONINFOEX osvi;
4242 BOOL bOsVersionInfoEx;
4244 // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
4245 // If that fails, try using the OSVERSIONINFO structure.
4247 ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
4248 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
4250 bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi);
4251 if (!bOsVersionInfoEx)
4253 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
4254 if (!GetVersionEx((OSVERSIONINFO *)&osvi))
4256 return 0;
4260 switch (osvi.dwPlatformId)
4262 // Test for the Windows NT product family.
4264 case VER_PLATFORM_WIN32_NT:
4266 // Test for the specific product family.
4268 if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
4270 #if (_MSC_VER >= 1300)
4271 if (osvi.wProductType == VER_NT_WORKSTATION)
4273 res += "Microsoft Windows Vista";
4275 else
4277 res += "Microsoft Windows Server 2008 family";
4279 #else
4280 res += "Microsoft Windows Vista or Windows Server 2008";
4281 #endif
4284 if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
4286 res += "Microsoft Windows Server 2003 family";
4289 if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
4291 res += "Microsoft Windows XP";
4294 if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
4296 res += "Microsoft Windows 2000";
4299 if (osvi.dwMajorVersion <= 4)
4301 res += "Microsoft Windows NT";
4304 // Test for specific product on Windows NT 4.0 SP6 and later.
4306 if (bOsVersionInfoEx)
4308 // Test for the workstation type.
4310 #if (_MSC_VER >= 1300)
4311 if (osvi.wProductType == VER_NT_WORKSTATION)
4313 if (osvi.dwMajorVersion == 4)
4315 res += " Workstation 4.0";
4317 else if (osvi.dwMajorVersion == 5)
4319 if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
4321 res += " Home Edition";
4323 else
4325 res += " Professional";
4330 // Test for the server type.
4332 else if (osvi.wProductType == VER_NT_SERVER)
4334 if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
4336 if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
4338 res += " Datacenter Edition";
4340 else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
4342 res += " Enterprise Edition";
4344 else if (osvi.wSuiteMask == VER_SUITE_BLADE)
4346 res += " Web Edition";
4348 else
4350 res += " Standard Edition";
4354 else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
4356 if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
4358 res += " Datacenter Server";
4360 else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
4362 res += " Advanced Server";
4364 else
4366 res += " Server";
4370 else if (osvi.dwMajorVersion <= 4) // Windows NT 4.0
4372 if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
4374 res += " Server 4.0, Enterprise Edition";
4376 else
4378 res += " Server 4.0";
4382 #endif // Visual Studio 7 and up
4385 // Test for specific product on Windows NT 4.0 SP5 and earlier
4387 else
4389 HKEY hKey;
4390 #define BUFSIZE 80
4391 char szProductType[BUFSIZE];
4392 DWORD dwBufLen=BUFSIZE;
4393 LONG lRet;
4395 lRet = RegOpenKeyEx(
4396 HKEY_LOCAL_MACHINE,
4397 "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
4398 0, KEY_QUERY_VALUE, &hKey);
4399 if (lRet != ERROR_SUCCESS)
4401 return 0;
4404 lRet = RegQueryValueEx(hKey, "ProductType", NULL, NULL,
4405 (LPBYTE) szProductType, &dwBufLen);
4407 if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))
4409 return 0;
4412 RegCloseKey(hKey);
4414 if (lstrcmpi("WINNT", szProductType) == 0)
4416 res += " Workstation";
4418 if (lstrcmpi("LANMANNT", szProductType) == 0)
4420 res += " Server";
4422 if (lstrcmpi("SERVERNT", szProductType) == 0)
4424 res += " Advanced Server";
4427 res += " ";
4428 sprintf(buffer, "%ld", osvi.dwMajorVersion);
4429 res += buffer;
4430 res += ".";
4431 sprintf(buffer, "%ld", osvi.dwMinorVersion);
4432 res += buffer;
4435 // Display service pack (if any) and build number.
4437 if (osvi.dwMajorVersion == 4 &&
4438 lstrcmpi(osvi.szCSDVersion, "Service Pack 6") == 0)
4440 HKEY hKey;
4441 LONG lRet;
4443 // Test for SP6 versus SP6a.
4445 lRet = RegOpenKeyEx(
4446 HKEY_LOCAL_MACHINE,
4447 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
4448 0, KEY_QUERY_VALUE, &hKey);
4450 if (lRet == ERROR_SUCCESS)
4452 res += " Service Pack 6a (Build ";
4453 sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
4454 res += buffer;
4455 res += ")";
4457 else // Windows NT 4.0 prior to SP6a
4459 res += " ";
4460 res += osvi.szCSDVersion;
4461 res += " (Build ";
4462 sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
4463 res += buffer;
4464 res += ")";
4467 RegCloseKey(hKey);
4469 else // Windows NT 3.51 and earlier or Windows 2000 and later
4471 res += " ";
4472 res += osvi.szCSDVersion;
4473 res += " (Build ";
4474 sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
4475 res += buffer;
4476 res += ")";
4479 break;
4481 // Test for the Windows 95 product family.
4483 case VER_PLATFORM_WIN32_WINDOWS:
4485 if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
4487 res += "Microsoft Windows 95";
4488 if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
4490 res += " OSR2";
4494 if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
4496 res += "Microsoft Windows 98";
4497 if (osvi.szCSDVersion[1] == 'A')
4499 res += " SE";
4503 if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
4505 res += "Microsoft Windows Millennium Edition";
4507 break;
4509 case VER_PLATFORM_WIN32s:
4511 res += "Microsoft Win32s";
4512 break;
4514 #endif
4516 return res;
4519 // ----------------------------------------------------------------------
4520 bool SystemTools::ParseURLProtocol( const kwsys_stl::string& URL,
4521 kwsys_stl::string& protocol,
4522 kwsys_stl::string& dataglom )
4524 // match 0 entire url
4525 // match 1 protocol
4526 // match 2 dataglom following protocol://
4527 kwsys::RegularExpression urlRe( VTK_URL_PROTOCOL_REGEX );
4529 if ( ! urlRe.find( URL ) ) return false;
4531 protocol = urlRe.match( 1 );
4532 dataglom = urlRe.match( 2 );
4534 return true;
4537 // ----------------------------------------------------------------------
4538 bool SystemTools::ParseURL( const kwsys_stl::string& URL,
4539 kwsys_stl::string& protocol,
4540 kwsys_stl::string& username,
4541 kwsys_stl::string& password,
4542 kwsys_stl::string& hostname,
4543 kwsys_stl::string& dataport,
4544 kwsys_stl::string& database )
4546 kwsys::RegularExpression urlRe( VTK_URL_REGEX );
4547 if ( ! urlRe.find( URL ) ) return false;
4549 // match 0 URL
4550 // match 1 protocol
4551 // match 2 mangled user
4552 // match 3 username
4553 // match 4 mangled password
4554 // match 5 password
4555 // match 6 hostname
4556 // match 7 mangled port
4557 // match 8 dataport
4558 // match 9 database name
4560 protocol = urlRe.match( 1 );
4561 username = urlRe.match( 3 );
4562 password = urlRe.match( 5 );
4563 hostname = urlRe.match( 6 );
4564 dataport = urlRe.match( 8 );
4565 database = urlRe.match( 9 );
4567 return true;
4570 // ----------------------------------------------------------------------
4571 // These must NOT be initialized. Default initialization to zero is
4572 // necessary.
4573 unsigned int SystemToolsManagerCount;
4574 SystemToolsTranslationMap *SystemTools::TranslationMap;
4575 SystemToolsTranslationMap *SystemTools::LongPathMap;
4576 #ifdef __CYGWIN__
4577 SystemToolsTranslationMap *SystemTools::Cyg2Win32Map;
4578 #endif
4580 // SystemToolsManager manages the SystemTools singleton.
4581 // SystemToolsManager should be included in any translation unit
4582 // that will use SystemTools or that implements the singleton
4583 // pattern. It makes sure that the SystemTools singleton is created
4584 // before and destroyed after all other singletons in CMake.
4586 SystemToolsManager::SystemToolsManager()
4588 if(++SystemToolsManagerCount == 1)
4590 SystemTools::ClassInitialize();
4594 SystemToolsManager::~SystemToolsManager()
4596 if(--SystemToolsManagerCount == 0)
4598 SystemTools::ClassFinalize();
4602 #if defined(__VMS)
4603 // On VMS we configure the run time C library to be more UNIX like.
4604 // http://h71000.www7.hp.com/doc/732final/5763/5763pro_004.html
4605 extern "C" int decc$feature_get_index(char *name);
4606 extern "C" int decc$feature_set_value(int index, int mode, int value);
4607 static int SetVMSFeature(char* name, int value)
4609 int i;
4610 errno = 0;
4611 i = decc$feature_get_index(name);
4612 return i >= 0 && (decc$feature_set_value(i, 1, value) >= 0 || errno == 0);
4614 #endif
4616 void SystemTools::ClassInitialize()
4618 #ifdef __VMS
4619 SetVMSFeature("DECC$FILENAME_UNIX_ONLY", 1);
4620 #endif
4621 // Allocate the translation map first.
4622 SystemTools::TranslationMap = new SystemToolsTranslationMap;
4623 SystemTools::LongPathMap = new SystemToolsTranslationMap;
4624 #ifdef __CYGWIN__
4625 SystemTools::Cyg2Win32Map = new SystemToolsTranslationMap;
4626 #endif
4628 // Add some special translation paths for unix. These are not added
4629 // for windows because drive letters need to be maintained. Also,
4630 // there are not sym-links and mount points on windows anyway.
4631 #if !defined(_WIN32) || defined(__CYGWIN__)
4632 // Work-around an SGI problem by always adding this mapping:
4633 SystemTools::AddTranslationPath("/tmp_mnt/", "/");
4634 // The tmp path is frequently a logical path so always keep it:
4635 SystemTools::AddKeepPath("/tmp/");
4637 // If the current working directory is a logical path then keep the
4638 // logical name.
4639 if(const char* pwd = getenv("PWD"))
4641 char buf[2048];
4642 if(const char* cwd = Getcwd(buf, 2048))
4644 // The current working directory may be a logical path. Find
4645 // the shortest logical path that still produces the correct
4646 // physical path.
4647 kwsys_stl::string cwd_changed;
4648 kwsys_stl::string pwd_changed;
4650 // Test progressively shorter logical-to-physical mappings.
4651 kwsys_stl::string pwd_str = pwd;
4652 kwsys_stl::string cwd_str = cwd;
4653 kwsys_stl::string pwd_path;
4654 Realpath(pwd, pwd_path);
4655 while(cwd_str == pwd_path && cwd_str != pwd_str)
4657 // The current pair of paths is a working logical mapping.
4658 cwd_changed = cwd_str;
4659 pwd_changed = pwd_str;
4661 // Strip off one directory level and see if the logical
4662 // mapping still works.
4663 pwd_str = SystemTools::GetFilenamePath(pwd_str.c_str());
4664 cwd_str = SystemTools::GetFilenamePath(cwd_str.c_str());
4665 Realpath(pwd_str.c_str(), pwd_path);
4668 // Add the translation to keep the logical path name.
4669 if(!cwd_changed.empty() && !pwd_changed.empty())
4671 SystemTools::AddTranslationPath(cwd_changed.c_str(),
4672 pwd_changed.c_str());
4676 #endif
4679 void SystemTools::ClassFinalize()
4681 delete SystemTools::TranslationMap;
4682 delete SystemTools::LongPathMap;
4683 #ifdef __CYGWIN__
4684 delete SystemTools::Cyg2Win32Map;
4685 #endif
4689 } // namespace KWSYS_NAMESPACE
4691 #if defined(_MSC_VER) && defined(_DEBUG)
4692 # include <crtdbg.h>
4693 # include <stdio.h>
4694 # include <stdlib.h>
4695 namespace KWSYS_NAMESPACE
4698 static int SystemToolsDebugReport(int, char* message, int*)
4700 fprintf(stderr, "%s", message);
4701 fflush(stderr);
4702 return 1; // no further reporting required
4705 void SystemTools::EnableMSVCDebugHook()
4707 if (getenv("DART_TEST_FROM_DART"))
4709 _CrtSetReportHook(SystemToolsDebugReport);
4713 } // namespace KWSYS_NAMESPACE
4714 #else
4715 namespace KWSYS_NAMESPACE
4717 void SystemTools::EnableMSVCDebugHook() {}
4718 } // namespace KWSYS_NAMESPACE
4719 #endif