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.
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"
34 # pragma warning (disable: 4786)
37 #if defined(__sgi) && !defined(__GNUC__)
38 # pragma set woff 1375 /* base class destructor not virtual */
44 # include <malloc.h> /* for malloc/free on QNX */
52 // support for realpath call
57 #include <sys/ioctl.h>
61 #include <sys/param.h>
64 #include <signal.h> /* sigprocmask */
67 // Windows API. Some parts used even on cygwin.
68 #if defined(_WIN32) || defined (__CYGWIN__)
74 extern "C" void cygwin_conv_to_win32_path(const char *path
, char *win32_path
);
77 // getpwnam doesn't exist on Windows and Cray Xt3/Catamount
78 // same for TIOCGWINSZ
79 #if defined(_WIN32) || defined (__LIBCATAMOUNT__)
83 # define HAVE_GETPWNAM 1
84 # define HAVE_TTY_INFO 1
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]+))?/(.+)?"
91 #include <sys/utime.h>
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
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))
119 #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
122 #define _unlink unlink
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
131 # define KWSYS_SYSTEMTOOLS_MAXPATH 16384
133 #if defined(__WATCOMC__)
137 #define _getcwd getcwd
141 #if defined(__HAIKU__)
142 #include <os/kernel/OS.h>
143 #include <os/storage/Path.h>
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
)
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.
174 #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
175 inline int Mkdir(const char* dir
)
179 inline int Rmdir(const char* dir
)
183 inline const char* Getcwd(char* buf
, unsigned int len
)
185 const char* ret
= _getcwd(buf
, len
);
188 fprintf(stderr
, "No current working directory.\n");
191 // make sure the drive letter is capital
192 if(strlen(buf
) > 1 && buf
[1] == ':')
194 buf
[0] = toupper(buf
[0]);
198 inline int Chdir(const char* dir
)
200 #if defined(__BORLANDC__)
206 inline void Realpath(const char *path
, kwsys_stl::string
& resolved_path
)
209 char fullpath
[MAX_PATH
];
210 if( GetFullPathName(path
, sizeof(fullpath
), fullpath
, &ptemp
) )
212 resolved_path
= fullpath
;
213 KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path
);
217 resolved_path
= path
;
221 #include <sys/types.h>
224 inline int Mkdir(const char* dir
)
226 return mkdir(dir
, 00777);
228 inline int Rmdir(const char* dir
)
232 inline const char* Getcwd(char* buf
, unsigned int len
)
234 const char* ret
= getcwd(buf
, len
);
237 fprintf(stderr
, "No current working directory\n");
243 inline int Chdir(const char* 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
);
258 // if path resolution fails, return what was passed in
259 resolved_path
= path
;
264 #if !defined(_WIN32) && defined(__COMO__)
265 // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
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
;
277 /* Implement floattime() for various platforms */
278 // Taken from Python 2.1.3
280 #if defined( _WIN32 ) && !defined( __CYGWIN__ )
281 # include <sys/timeb.h>
283 # if defined( __BORLANDC__)
286 # else // Visual studio?
287 # define FTIME _ftime
288 # define TIMEB _timeb
290 #elif defined( __CYGWIN__ ) || defined( __linux__ )
291 # include <sys/time.h>
293 # define HAVE_GETTIMEOFDAY
296 namespace KWSYS_NAMESPACE
299 class SystemToolsTranslationMap
:
300 public kwsys_stl::map
<kwsys_stl::string
,kwsys_stl::string
>
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
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)
332 return static_cast<double>(t
.time
) +
333 static_cast<double>(t
.millitm
) * static_cast<double>(0.001);
334 #else /* !HAVE_FTIME */
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
= ";";
348 const char* pathSep
= ":";
354 const char* cpathEnv
= SystemTools::GetEnv(env
);
360 kwsys_stl::string pathEnv
= cpathEnv
;
362 // A hack to make the below algorithm work.
363 if(pathEnv
[pathEnv
.length()-1] != ':')
367 kwsys_stl::string::size_type start
=0;
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
);
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
)
396 bool SystemTools::GetEnv(const char* key
, kwsys_stl::string
& result
)
398 const char* v
= getenv(key
);
410 class kwsysDeletingCharVector
: public kwsys_stl::vector
<char*>
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
)
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
);
439 const char* SystemTools::GetExecutableExtension()
441 #if defined(_WIN32) || defined(__CYGWIN__) || defined(__VMS)
449 bool SystemTools::MakeDirectory(const char* path
)
455 if(SystemTools::FileExists(path
))
459 kwsys_stl::string dir
= path
;
464 SystemTools::ConvertToUnixSlashes(dir
);
466 kwsys_stl::string::size_type pos
= dir
.find(':');
467 if(pos
== kwsys_stl::string::npos
)
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());
478 if(dir
[dir
.size()-1] == '/')
480 topdir
= dir
.substr(0, dir
.size());
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
492 if( (errno
!= EEXIST
)
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
,
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
520 // perform replacements until done
521 size_t replaceSize
= strlen(replace
);
522 // do while hangs if replaceSize is 0
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());
536 source
+= currentPos
;
537 currentPos
= searchPos
+ replaceSize
;
540 searchPos
= strstr(currentPos
,replace
);
544 // copy any trailing text
545 source
+= currentPos
;
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
553 # define KWSYS_ST_KEY_WOW64_32KEY 0x0200
554 # define KWSYS_ST_KEY_WOW64_64KEY 0x0100
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
;
573 // Read a registry value.
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
,
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
)
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
;
627 if(RegOpenKeyEx(primaryKey
,
630 SystemToolsMakeRegistryMode(KEY_READ
, view
),
631 &hKey
) != ERROR_SUCCESS
)
637 DWORD dwType
, dwSize
;
640 if(RegQueryValueEx(hKey
,
641 (LPTSTR
)valuename
.c_str(),
645 &dwSize
) == ERROR_SUCCESS
)
647 if (dwType
== REG_SZ
)
652 else if (dwType
== REG_EXPAND_SZ
)
655 DWORD dwExpandedSize
= sizeof(expanded
)/sizeof(expanded
[0]);
656 if(ExpandEnvironmentStrings(data
, expanded
, dwExpandedSize
))
670 bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string
&,
678 // Write a registry value.
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
,
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
)
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
;
732 if(RegCreateKeyEx(primaryKey
,
736 REG_OPTION_NON_VOLATILE
,
737 SystemToolsMakeRegistryMode(KEY_WRITE
, view
),
740 &dwDummy
) != ERROR_SUCCESS
)
745 if(RegSetValueEx(hKey
,
746 (LPTSTR
)valuename
.c_str(),
750 (DWORD
)(strlen(value
) + 1)) == ERROR_SUCCESS
)
757 bool SystemTools::WriteRegistryValue(const char *, const char *, KeyWOW64
)
763 // Delete a registry value.
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
)
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
;
815 if(RegOpenKeyEx(primaryKey
,
818 SystemToolsMakeRegistryMode(KEY_WRITE
, view
),
819 &hKey
) != ERROR_SUCCESS
)
825 if(RegDeleteValue(hKey
,
826 (LPTSTR
)valuename
.c_str()) == ERROR_SUCCESS
)
835 bool SystemTools::DeleteRegistryValue(const char *, KeyWOW64
)
841 bool SystemTools::SameFile(const char* file1
, const char* file2
)
844 HANDLE hFile1
, hFile2
;
846 hFile1
= CreateFile( file1
,
851 FILE_FLAG_BACKUP_SEMANTICS
,
854 hFile2
= CreateFile( file2
,
859 FILE_FLAG_BACKUP_SEMANTICS
,
862 if( hFile1
== INVALID_HANDLE_VALUE
|| hFile2
== INVALID_HANDLE_VALUE
)
864 if(hFile1
!= INVALID_HANDLE_VALUE
)
868 if(hFile2
!= INVALID_HANDLE_VALUE
)
875 BY_HANDLE_FILE_INFORMATION fiBuf1
;
876 BY_HANDLE_FILE_INFORMATION fiBuf2
;
877 GetFileInformationByHandle( hFile1
, &fiBuf1
);
878 GetFileInformationByHandle( hFile2
, &fiBuf2
);
881 return (fiBuf1
.dwVolumeSerialNumber
== fiBuf2
.dwVolumeSerialNumber
&&
882 fiBuf1
.nFileIndexHigh
== fiBuf2
.nFileIndexHigh
&&
883 fiBuf1
.nFileIndexLow
== fiBuf2
.nFileIndexLow
);
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
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;
911 //----------------------------------------------------------------------------
912 bool SystemTools::FileExists(const char* filename
)
914 if(!(filename
&& *filename
))
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
);
929 return access(filename
, R_OK
) == 0;
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
);
945 //----------------------------------------------------------------------------
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
);
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;
966 bool SystemTools::Touch(const char* filename
, bool create
)
968 if(create
&& !SystemTools::FileExists(filename
))
970 FILE* file
= fopen(filename
, "a+b");
980 #define utimbuf _utimbuf
982 struct stat fromStat
;
983 if(stat(filename
, &fromStat
) < 0)
988 buf
.actime
= fromStat
.st_atime
;
989 buf
.modtime
= static_cast<time_t>(SystemTools::GetTime());
990 if(utime(filename
, &buf
) < 0)
997 bool SystemTools::FileTimeCompare(const char* f1
, const char* f2
,
1000 // Default to same time.
1002 #if !defined(_WIN32) || defined(__CYGWIN__)
1003 // POSIX version. Use stat function to get file modification time.
1005 if(stat(f1
, &s1
) != 0)
1010 if(stat(f2
, &s2
) != 0)
1014 # if KWSYS_STAT_HAS_ST_MTIM
1015 // Compare using nanosecond resolution.
1016 if(s1
.st_mtim
.tv_sec
< s2
.st_mtim
.tv_sec
)
1020 else if(s1
.st_mtim
.tv_sec
> s2
.st_mtim
.tv_sec
)
1024 else if(s1
.st_mtim
.tv_nsec
< s2
.st_mtim
.tv_nsec
)
1028 else if(s1
.st_mtim
.tv_nsec
> s2
.st_mtim
.tv_nsec
)
1033 // Compare using 1 second resolution.
1034 if(s1
.st_mtime
< s2
.st_mtime
)
1038 else if(s1
.st_mtime
> s2
.st_mtime
)
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
))
1051 if(!GetFileAttributesEx(f2
, GetFileExInfoStandard
, &f2d
))
1056 // Compare the file times using resolution provided by system call.
1057 *result
= (int)CompareFileTime(&f1d
.ftLastWriteTime
, &f2d
.ftLastWriteTime
);
1063 // Return a capitalized string (i.e the first letter is uppercased, all other
1065 kwsys_stl::string
SystemTools::Capitalized(const kwsys_stl::string
& s
)
1067 kwsys_stl::string n
;
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
]));
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]))))
1093 if (isalpha(s
[i
]) && (i
== 0 || isspace(s
[i
- 1])))
1096 n
[i
] = static_cast<kwsys_stl::string::value_type
>(toupper(s
[i
]));
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]))))
1114 if (isalpha(s
[i
]) && (i
== 0 || isspace(s
[i
- 1])))
1117 n
[i
] = static_cast<kwsys_stl::string::value_type
>(tolower(s
[i
]));
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
;
1130 n
.reserve(s
.size());
1132 for (size_t i
= 1; i
< s
.size(); i
++)
1134 if (isupper(s
[i
]) && !isspace(s
[i
- 1]) && !isupper(s
[i
- 1]))
1144 char* SystemTools::AppendStrings(const char* str1
, const char* str2
)
1148 return SystemTools::DuplicateString(str2
);
1152 return SystemTools::DuplicateString(str1
);
1154 size_t len1
= strlen(str1
);
1155 char *newstr
= new char[len1
+ strlen(str2
) + 1];
1160 strcpy(newstr
, str1
);
1161 strcat(newstr
+ len1
, str2
);
1165 char* SystemTools::AppendStrings(
1166 const char* str1
, const char* str2
, const char* str3
)
1170 return SystemTools::AppendStrings(str2
, str3
);
1174 return SystemTools::AppendStrings(str1
, 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];
1187 strcpy(newstr
, str1
);
1188 strcat(newstr
+ len1
, str2
);
1189 strcat(newstr
+ len1
+ len2
, str3
);
1193 // Return a lower case string
1194 kwsys_stl::string
SystemTools::LowerCase(const kwsys_stl::string
& s
)
1196 kwsys_stl::string n
;
1198 for (size_t i
= 0; i
< s
.size(); i
++)
1200 n
[i
] = static_cast<kwsys_stl::string::value_type
>(tolower(s
[i
]));
1205 // Return a lower case string
1206 kwsys_stl::string
SystemTools::UpperCase(const kwsys_stl::string
& s
)
1208 kwsys_stl::string n
;
1210 for (size_t i
= 0; i
< s
.size(); i
++)
1212 n
[i
] = static_cast<kwsys_stl::string::value_type
>(toupper(s
[i
]));
1217 // Count char in string
1218 size_t SystemTools::CountChar(const char* str
, char c
)
1236 // Remove chars in string
1237 char* SystemTools::RemoveChars(const char* str
, const char *toremove
)
1243 char *clean_str
= new char [strlen(str
) + 1];
1244 char *ptr
= clean_str
;
1247 const char *str2
= toremove
;
1248 while (*str2
&& *str
!= *str2
)
1262 // Remove chars in string
1263 char* SystemTools::RemoveCharsButUpperHex(const char* str
)
1269 char *clean_str
= new char [strlen(str
) + 1];
1270 char *ptr
= clean_str
;
1273 if ((*str
>= '0' && *str
<= '9') || (*str
>= 'A' && *str
<= 'F'))
1283 // Replace chars in string
1284 char* SystemTools::ReplaceChars(char* str
, const char *toreplace
, char replacement
)
1291 const char *ptr2
= toreplace
;
1306 // Returns if string starts with another string
1307 bool SystemTools::StringStartsWith(const char* str1
, const char* str2
)
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
)
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
)
1336 size_t len1
= strlen(str1
), len2
= strlen(str2
);
1339 const char *ptr
= str1
+ len1
- len2
;
1342 if (!strncmp(ptr
, str2
, len2
))
1346 } while (ptr
-- != str1
);
1353 char* SystemTools::DuplicateString(const char* str
)
1357 char *newstr
= new char [strlen(str
) + 1];
1358 return strcpy(newstr
, str
);
1363 // Return a cropped string
1364 kwsys_stl::string
SystemTools::CropString(const kwsys_stl::string
& s
,
1367 if (!s
.size() || max_len
== 0 || max_len
>= s
.size())
1372 kwsys_stl::string n
;
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
);
1385 n
[middle
- 1] = '.';
1388 n
[middle
+ 1] = '.';
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
));
1412 pos2
= path
.find(sep
, pos1
+1);
1414 paths
.push_back(path
.substr(pos1
, pos2
-pos1
));
1419 //----------------------------------------------------------------------------
1420 int SystemTools::EstimateFormatLength(const char *format
, va_list ap
)
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
;
1441 // Skip "%%" since it doesn't correspond to a va_arg.
1444 while(!int(isalpha(*cur
)))
1452 // Check the length of the string.
1453 char* s
= va_arg(ap
, char*);
1456 length
+= strlen(s
);
1463 // Assume the argument contributes no more than 64 characters.
1466 // Eat the argument.
1467 static_cast<void>(va_arg(ap
, double));
1471 // Assume the argument contributes no more than 64 characters.
1474 // Eat the argument.
1475 static_cast<void>(va_arg(ap
, int));
1480 // Move past the characters just tested.
1485 return static_cast<int>(length
);
1488 kwsys_stl::string
SystemTools::EscapeChars(
1490 const char *chars_to_escape
,
1493 kwsys_stl::string n
;
1496 if (!chars_to_escape
| !*chars_to_escape
)
1502 n
.reserve(strlen(str
));
1505 const char *ptr
= chars_to_escape
;
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
)
1538 pathPart
[pos
] = '/';
1542 path
= "/"+ root
+ "/" + pathPart
;
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;
1553 ConvertVMSToUnix(path
);
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
!= ' ' )
1565 // Also, reuse the loop to check for slash followed by another slash
1566 if (*pos1
== '/' && *(pos1
+1) == '/' && !hasDoubleSlash
)
1569 // However, on windows if the first characters are both slashes,
1570 // then keep them that way, so that network paths can be handled.
1573 hasDoubleSlash
= true;
1576 hasDoubleSlash
= true;
1584 if ( hasDoubleSlash
)
1586 SystemTools::ReplaceString(path
, "//", "/");
1589 // remove any trailing slash
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");
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());
1610 path
.replace(0, idx
, pw
->pw_dir
);
1614 // remove trailing slash if the path is more than
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
)
1639 // escape spaces and () in the path
1640 if(ret
.find_first_of(" ") != kwsys_stl::string::npos
)
1642 kwsys_stl::string result
= "";
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
!= '\\')
1659 kwsys_stl::string
SystemTools::ConvertToOutputPath(const char* path
)
1661 #if defined(_WIN32) && !defined(__CYGWIN__)
1662 return SystemTools::ConvertToWindowsOutputPath(path
);
1664 return SystemTools::ConvertToUnixOutputPath(path
);
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
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
)
1684 // check for really small paths
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
1692 pos
= 1; // start at position 1
1695 pos
= 2; // if the string is already quoted then start at 2
1701 while((pos
= ret
.find("\\\\", pos
)) != kwsys_stl::string::npos
)
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
1710 ret
.insert(static_cast<kwsys_stl::string::size_type
>(0),
1711 static_cast<kwsys_stl::string::size_type
>(1), '\"');
1712 ret
.append(1, '\"');
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
,
1737 // the files are the same so the copy is done return
1742 // source and destination are files so do a copy if they
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
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)
1763 struct stat statDestination
;
1764 if (stat(destination
, &statDestination
) != 0)
1769 if(statSource
.st_size
!= statDestination
.st_size
)
1774 if(statSource
.st_size
== 0)
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
));
1785 kwsys_ios::ifstream
finSource(source
);
1786 kwsys_ios::ifstream
finDestination(destination
);
1788 if(!finSource
|| !finDestination
)
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
;
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
)
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)
1819 // Update the byte count remaining.
1823 // No differences found.
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
) )
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());
1869 #if defined(_WIN32) || defined(__CYGWIN__)
1870 kwsys_ios::ifstream
fin(source
,
1871 kwsys_ios::ios::binary
| kwsys_ios::ios::in
);
1873 kwsys_ios::ifstream
fin(source
);
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
);
1890 kwsys_ios::ofstream
fout(destination
,
1891 kwsys_ios::ios::out
| kwsys_ios::ios::trunc
);
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.
1905 fin
.read(buffer
, bufferSize
);
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
1921 struct stat statSource
, statDestination
;
1922 statSource
.st_size
= 12345;
1923 statDestination
.st_size
= 12345;
1924 if(stat(source
, &statSource
) != 0)
1928 else if(stat(destination
, &statDestination
) != 0)
1932 else if(statSource
.st_size
!= statDestination
.st_size
)
1936 if ( copyPermissions
&& perms
)
1938 if ( !SystemTools::SetPermissions(destination
, perm
) )
1946 //----------------------------------------------------------------------------
1947 bool SystemTools::CopyAFile(const char* source
, const char* destination
,
1948 bool always
, bool copyPermissions
)
1952 return SystemTools::CopyFileAlways(source
, destination
, copyPermissions
);
1956 return SystemTools::CopyFileIfDifferent(source
, destination
, copyPermissions
);
1961 * Copy a directory content from "source" directory to the directory named by
1964 bool SystemTools::CopyADirectory(const char* source
, const char* destination
,
1965 bool always
, bool copyPermissions
)
1970 if ( !SystemTools::MakeDirectory(destination
) )
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
;
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(),
1997 if(!SystemTools::CopyAFile(fullPath
.c_str(), destination
, always
,
2010 // return size of file; also returns zero if no file exists
2011 unsigned long SystemTools::FileLength(const char* filename
)
2014 if (stat(filename
, &fs
) != 0)
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
)))
2034 return tolower(*s1
) - tolower(*s2
);
2037 // return file's modified time
2038 long int SystemTools::ModifiedTime(const char* filename
)
2041 if (stat(filename
, &fs
) != 0)
2047 return static_cast<long int>(fs
.st_mtime
);
2051 // return file's creation time
2052 long int SystemTools::CreationTime(const char* filename
)
2055 if (stat(filename
, &fs
) != 0)
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)
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";
2086 strcpy(buffer
, str
);
2089 char *ptr
= strstr(month_names
, buffer
);
2095 int month
= static_cast<int>((ptr
- month_names
) / 3);
2096 int day
= atoi(buffer
+ 4);
2097 int year
= atoi(buffer
+ 7);
2106 tmt2
.tm_mon
= month
;
2107 tmt2
.tm_year
= year
- 1900;
2109 *tmt
= mktime(&tmt2
);
2113 bool SystemTools::ConvertTimeStampMacroString(const char *str
, time_t *tmt
)
2115 if (!str
|| !tmt
|| strlen(str
) > 26)
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
2128 // index: 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";
2137 strcpy(buffer
, str
);
2140 char *ptr
= strstr(month_names
, buffer
+ 4);
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);
2154 tmt2
.tm_hour
= hour
;
2160 tmt2
.tm_mon
= month
;
2161 tmt2
.tm_year
= year
- 1900;
2163 *tmt
= mktime(&tmt2
);
2167 kwsys_stl::string
SystemTools::GetLastSystemError()
2173 bool SystemTools::RemoveFile(const char* source
)
2177 if ( !SystemTools::GetPermissions(source
, mode
) )
2181 /* Win32 unlink is stupid --- it fails if the file is read-only */
2182 SystemTools::SetPermissions(source
, S_IWRITE
);
2184 bool res
= unlink(source
) != 0 ? false : true;
2188 SystemTools::SetPermissions(source
, mode
);
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.
2199 if(SystemTools::GetPermissions(source
, mode
))
2201 #if defined(_WIN32) && !defined(__CYGWIN__)
2206 SystemTools::SetPermissions(source
, mode
);
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
;
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()))
2230 if(!SystemTools::RemoveFile(fullPath
.c_str()))
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
)
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] != '/')
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
)
2292 if(SystemTools::FileExists(tryPath
.c_str()))
2297 // Couldn't find the file.
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.
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.
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(
2346 const kwsys_stl::vector
<kwsys_stl::string
>& userPaths
,
2347 bool no_system_path
)
2349 if(!nameIn
|| !*nameIn
)
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
2359 if(name
.size() > 3 && name
[name
.size()-4] == '.')
2361 hasExtension
= true;
2363 // on windows try .com then .exe
2366 extensions
.push_back(".com");
2367 extensions
.push_back(".exe");
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
)
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
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
)
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] != '/')
2422 for(kwsys_stl::vector
<kwsys_stl::string
>::iterator p
= path
.begin();
2423 p
!= path
.end(); ++p
)
2426 // Remove double quotes from the path on windows
2427 SystemTools::ReplaceString(*p
, "\"", "");
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
)
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
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.
2458 kwsys_stl::string
SystemTools::FindProgram(
2459 const kwsys_stl::vector
<kwsys_stl::string
>& names
,
2460 const kwsys_stl::vector
<kwsys_stl::string
>& path
,
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(),
2470 if ( !result
.empty() )
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
)
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] != '/')
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__)
2524 tryPath
+= ".framework";
2525 if(SystemTools::FileExists(tryPath
.c_str())
2526 && SystemTools::FileIsDirectory(tryPath
.c_str()))
2528 return SystemTools::CollapseFullPath(tryPath
.c_str());
2531 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
2535 if(SystemTools::FileExists(tryPath
.c_str())
2536 && !SystemTools::FileIsDirectory(tryPath
.c_str()))
2538 return SystemTools::CollapseFullPath(tryPath
.c_str());
2545 if(SystemTools::FileExists(tryPath
.c_str())
2546 && !SystemTools::FileIsDirectory(tryPath
.c_str()))
2548 return SystemTools::CollapseFullPath(tryPath
.c_str());
2554 if(SystemTools::FileExists(tryPath
.c_str())
2555 && !SystemTools::FileIsDirectory(tryPath
.c_str()))
2557 return SystemTools::CollapseFullPath(tryPath
.c_str());
2563 if(SystemTools::FileExists(tryPath
.c_str())
2564 && !SystemTools::FileIsDirectory(tryPath
.c_str()))
2566 return SystemTools::CollapseFullPath(tryPath
.c_str());
2571 tryPath
+= ".dylib";
2572 if(SystemTools::FileExists(tryPath
.c_str())
2573 && !SystemTools::FileIsDirectory(tryPath
.c_str()))
2575 return SystemTools::CollapseFullPath(tryPath
.c_str());
2581 if(SystemTools::FileExists(tryPath
.c_str())
2582 && !SystemTools::FileIsDirectory(tryPath
.c_str()))
2584 return SystemTools::CollapseFullPath(tryPath
.c_str());
2589 // Couldn't find the library.
2593 kwsys_stl::string
SystemTools::GetRealPath(const char* path
)
2595 kwsys_stl::string ret
;
2596 Realpath(path
, 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
);
2613 // Now check the file node type.
2615 if(stat(name
, &fs
) == 0)
2617 #if defined( _WIN32 )
2618 return ((fs
.st_mode
& _S_IFDIR
) != 0);
2620 return S_ISDIR(fs
.st_mode
);
2629 bool SystemTools::FileIsSymlink(const char* name
)
2631 #if defined( _WIN32 )
2636 if(lstat(name
, &fs
) == 0)
2638 return S_ISLNK(fs
.st_mode
);
2647 #if defined(_WIN32) && !defined(__CYGWIN__)
2648 bool SystemTools::CreateSymlink(const char*, const char*)
2653 bool SystemTools::CreateSymlink(const char* origName
, const char* newName
)
2655 return symlink(origName
, newName
) >= 0;
2659 #if defined(_WIN32) && !defined(__CYGWIN__)
2660 bool SystemTools::ReadSymlink(const char*, kwsys_stl::string
&)
2665 bool SystemTools::ReadSymlink(const char* newName
,
2666 kwsys_stl::string
& origName
)
2668 char buf
[KWSYS_SYSTEMTOOLS_MAXPATH
+1];
2670 static_cast<int>(readlink(newName
, buf
, KWSYS_SYSTEMTOOLS_MAXPATH
));
2673 // Add null-terminator.
2685 int SystemTools::ChangeDirectory(const char *dir
)
2690 kwsys_stl::string
SystemTools::GetCurrentWorkingDirectory(bool collapse
)
2693 const char* cwd
= Getcwd(buf
, 2048);
2694 kwsys_stl::string path
;
2701 return SystemTools::CollapseFullPath(path
.c_str());
2706 kwsys_stl::string
SystemTools::GetProgramPath(const char* in_name
)
2708 kwsys_stl::string dir
, file
;
2709 SystemTools::SplitProgramPath(in_name
, dir
, file
);
2713 bool SystemTools::SplitProgramPath(const char* in_name
,
2714 kwsys_stl::string
& dir
,
2715 kwsys_stl::string
& 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
);
2736 if(!(dir
== "") && !SystemTools::FileIsDirectory(dir
.c_str()))
2738 kwsys_stl::string oldDir
= in_name
;
2739 SystemTools::ConvertToUnixSlashes(oldDir
);
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()))
2762 kwsys_stl::string intdir
= ".";
2764 intdir
= CMAKE_INTDIR
;
2771 self
+= SystemTools::GetExecutableExtension();
2776 if(!SystemTools::FileExists(self
.c_str()))
2778 failures
.push_back(self
);
2779 self
= installPrefix
;
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 ";
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();
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
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] != '/')
2838 if(path_b
.size() && path_b
[path_b
.size() -1] != '/')
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
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).
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();
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());
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
;
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
;
2929 // Use the given base path.
2930 SystemTools::SplitPath(in_base
, base_components
);
2934 // Use the current working directory as a base path.
2936 if(const char* cwd
= Getcwd(buf
, 2048))
2938 SystemTools::SplitPath(cwd
, base_components
);
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
);
2977 newPath
= SystemTools::GetActualCaseForPath(newPath
.c_str());
2978 SystemTools::ConvertToUnixSlashes(newPath
);
2980 // Return the reconstructed path.
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
))
2991 if(!SystemTools::FileIsFullPath(remote
))
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;
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
3011 localSplit
[sameCount
] == remoteSplit
[sameCount
]
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
] = "";
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.
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
)
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
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)
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
;
3097 // if FindFirstFile fails, return the error code
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");
3119 FARPROC proc
= GetProcAddress(lh
, "GetLongPathNameA");
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)
3137 return OldWindowsGetLongPath(pathIn
, longPath
);
3142 //----------------------------------------------------------------------------
3143 kwsys_stl::string
SystemTools::GetActualCaseForPath(const char* p
)
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())
3156 kwsys_stl::string shortPath
;
3157 if(!SystemTools::GetShortPath(p
, shortPath
))
3161 kwsys_stl::string longPath
;
3162 int len
= PortableGetLongPathName(shortPath
.c_str(), longPath
);
3163 if(len
== 0 || len
> MAX_PATH
+1)
3167 // Use original path if conversion back to a long path failed.
3168 if(longPath
== shortPath
)
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
;
3182 //----------------------------------------------------------------------------
3183 const char* SystemTools::SplitPathRootComponent(const char* p
,
3184 kwsys_stl::string
* root
)
3186 // Identify the root component.
3188 if((c
[0] == '/' && c
[1] == '/') || (c
[0] == '\\' && c
[1] == '\\'))
3197 else if(c
[0] == '/')
3206 else if(c
[0] && c
[1] == ':' && (c
[2] == '/' || c
[2] == '\\'))
3216 else if(c
[0] && c
[1] == ':')
3218 // Path relative to a windows drive working directory.
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"
3240 while(c
[n
] && c
[n
] != '/')
3264 // Return the remaining path.
3268 //----------------------------------------------------------------------------
3269 void SystemTools::SplitPath(const char* p
,
3270 kwsys_stl::vector
<kwsys_stl::string
>& components
,
3271 bool expand_home_dir
)
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"))
3295 if(const char* h
= getenv("HOME"))
3300 #ifdef HAVE_GETPWNAM
3301 else if(passwd
* pw
= getpwnam(root
.c_str()+1))
3305 homedir
= pw
->pw_dir
;
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
);
3318 components
.push_back(root
);
3322 // Parse the remaining components.
3323 const char* first
= c
;
3324 const char* last
= first
;
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
>(
3337 // Save the last component unless there were no components.
3340 components
.push_back(
3341 kwsys_stl::string(first
,static_cast<kwsys_stl::string::size_type
>(
3346 //----------------------------------------------------------------------------
3348 SystemTools::JoinPath(const kwsys_stl::vector
<kwsys_stl::string
>& components
)
3350 return SystemTools::JoinPath(components
.begin(), components
.end());
3353 //----------------------------------------------------------------------------
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.
3365 result
.append(*first
++);
3369 result
.append(*first
++);
3372 // All remaining components are always separated with a slash.
3373 while(first
!= last
)
3376 result
.append((*first
++));
3379 // Return the concatenated result.
3383 //----------------------------------------------------------------------------
3384 bool SystemTools::ComparePath(const char* c1
, const char* c2
)
3386 #if defined(_WIN32) || defined(__APPLE__)
3388 return _stricmp(c1
, c2
) == 0;
3389 # elif defined(__APPLE__) || defined(__GNUC__)
3390 return strcasecmp(c1
, c2
) == 0;
3392 return SystemTools::Strucmp(c1
, c2
) == 0;
3395 return strcmp(c1
, c2
) == 0;
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
));
3415 // Line ends in a "\n", remove the character.
3416 lines
.push_back(data
.substr(lpos
, rpos
-lpos
));
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
));
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
));
3444 // Line ends in a "\n", remove the character.
3445 lines
.push_back(data
.substr(lpos
, rpos
-lpos
));
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] == ':')
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
)
3488 kwsys_stl::string::size_type slash_pos
= filename
.find_last_of("/\\");
3490 kwsys_stl::string::size_type slash_pos
= filename
.find_last_of("/");
3492 if(slash_pos
!= kwsys_stl::string::npos
)
3494 return filename
.substr(slash_pos
+ 1);
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
);
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
);
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
);
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
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
);
3578 bool SystemTools::FileHasSignature(const char *filename
,
3579 const char *signature
,
3582 if (!filename
|| !signature
)
3588 fp
= fopen(filename
, "rb");
3594 fseek(fp
, offset
, SEEK_SET
);
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);
3611 SystemTools::FileTypeEnum
3612 SystemTools::DetectFileType(const char *filename
,
3613 unsigned long length
,
3616 if (!filename
|| percent_bin
< 0)
3618 return SystemTools::FileTypeUnknown
;
3622 fp
= fopen(filename
, "rb");
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
);
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) ||
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
,
3673 kwsys_stl::string
& filename_found
,
3674 int try_filename_dirs
)
3676 if (!filename
|| !dir
)
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] != ':')
3696 real_dir
= SystemTools::GetFilenamePath(dir
);
3697 dir
= real_dir
.c_str();
3698 #if defined( _WIN32 )
3703 // Try to find the file in 'dir'
3706 if (filename_base
.size() && dir
)
3708 size_t dir_len
= strlen(dir
);
3710 (dir_len
&& dir
[dir_len
- 1] != '/' && dir
[dir_len
- 1] != '\\');
3712 kwsys_stl::string temp
= dir
;
3717 temp
+= filename_base
;
3719 if (SystemTools::FileExists(temp
.c_str()))
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] == ':')
3743 if (!filename_dir_base
.size())
3749 filename_dir_bases
= filename_dir_base
+ "/" + filename_dir_bases
;
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());
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)
3786 // On UNIX, the name must be at least one character long.
3787 if(name
.length() < 1)
3792 #if !defined(_WIN32)
3798 // On UNIX, the name must begin in a '/'.
3799 // On Windows, if the name begins in a '/', then it is a full
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
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';
3824 strcpy(tempPath
,path
);
3828 ret
= GetShortPathName(tempPath
, buffer
, size
);
3830 if(buffer
[0] == 0 || ret
> size
)
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
))
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
);
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()))
3882 // remove trailing spaces from program
3883 kwsys_stl::string::size_type pos
= program
.size()-1;
3884 while(program
[pos
] == ' ')
3889 args
= dir
.substr(spacePos
, dir
.size()-spacePos
);
3892 // Now try and find the the program in the path
3893 findProg
= SystemTools::FindProgram(tryProg
.c_str(), e
);
3897 // remove trailing spaces from program
3898 kwsys_stl::string::size_type pos
= program
.size()-1;
3899 while(program
[pos
] == ' ')
3904 args
= dir
.substr(spacePos
, dir
.size()-spacePos
);
3907 // move past the space for the next search
3909 spacePos
= dir
.rfind(' ', spacePos
);
3916 kwsys_stl::string
SystemTools::GetCurrentDateTime(const char* format
)
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)
3933 kwsys_stl::string
permited_chars("_"
3934 "abcdefghijklmnopqrstuvwxyz"
3935 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3937 kwsys_stl::string::size_type pos
= 0;
3938 while ((pos
= str
.find_first_not_of(permited_chars
, pos
)) != kwsys_stl::string::npos
)
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.
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
&&
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.
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()))
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
3990 if (static_cast<long>(length
) > leftToRead
)
3992 buffer
[leftToRead
-1] = 0;
3997 leftToRead
-= static_cast<long>(length
);
4001 // Append the data read to the line.
4002 line
.append(buffer
);
4005 // Return the results.
4008 *has_newline
= haveNewline
;
4013 int SystemTools::GetTerminalWidth()
4016 #ifdef HAVE_TTY_INFO
4018 char *columns
; /* Unix98 environment variable */
4019 if(ioctl(1, TIOCGWINSZ
, &ws
) != -1 && ws
.ws_col
>0 && ws
.ws_row
>0)
4023 if(!isatty(STDOUT_FILENO
))
4027 columns
= getenv("COLUMNS");
4028 if(columns
&& *columns
)
4032 t
= strtol(columns
, &endptr
, 0);
4033 if(endptr
&& !*endptr
&& (t
>0) && (t
<1000))
4035 width
= static_cast<int>(t
);
4046 bool SystemTools::GetPermissions(const char* file
, mode_t
& mode
)
4054 if ( stat(file
, &st
) < 0 )
4062 bool SystemTools::SetPermissions(const char* file
, mode_t mode
)
4068 if ( !SystemTools::FileExists(file
) )
4072 if ( chmod(file
, mode
) < 0 )
4080 kwsys_stl::string
SystemTools::GetParentDirectory(const char* fileOrDir
)
4082 return SystemTools::GetFilenamePath(fileOrDir
);
4085 bool SystemTools::IsSubDirectory(const char* cSubdir
, const char* cDir
)
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()))
4103 while ( path
.size() > dir
.size() );
4107 void SystemTools::Delay(unsigned int msec
)
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.
4122 usleep((msec
% 1000) * 1000);
4126 usleep(msec
* 1000);
4131 void SystemTools::ConvertWindowsCommandLineToUnixArguments(
4132 const char *cmd_line
, int *argc
, char ***argv
)
4134 if (!cmd_line
|| !argc
|| !argv
)
4139 // A space delimites an argument except when it is inside a quote
4143 size_t cmd_line_len
= strlen(cmd_line
);
4146 for (i
= 0; i
< cmd_line_len
; i
++)
4148 while (isspace(cmd_line
[i
]) && i
< cmd_line_len
)
4152 if (i
< cmd_line_len
)
4154 if (cmd_line
[i
] == '\"')
4157 while (cmd_line
[i
] != '\"' && i
< cmd_line_len
)
4165 while (!isspace(cmd_line
[i
]) && i
< cmd_line_len
)
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];
4181 ::GetModuleFileName(0, (*argv
)[0], 1024);
4183 (*argv
)[0][0] = '\0';
4186 // Allocate the others
4189 for (j
= 1; j
< (*argc
); j
++)
4191 (*argv
)[j
] = new char [cmd_line_len
+ 10];
4199 for (i
= 0; i
< cmd_line_len
; i
++)
4201 while (isspace(cmd_line
[i
]) && i
< cmd_line_len
)
4205 if (i
< cmd_line_len
)
4207 if (cmd_line
[i
] == '\"')
4211 while (cmd_line
[i
] != '\"' && i
< cmd_line_len
)
4215 memcpy((*argv
)[argc_idx
], &cmd_line
[pos
], i
- pos
);
4216 (*argv
)[argc_idx
][i
- pos
] = '\0';
4222 while (!isspace(cmd_line
[i
]) && i
< cmd_line_len
)
4226 memcpy((*argv
)[argc_idx
], &cmd_line
[pos
], i
- pos
);
4227 (*argv
)[argc_idx
][i
- pos
] = '\0';
4234 kwsys_stl::string
SystemTools::GetOperatingSystemNameAndVersion()
4236 kwsys_stl::string res
;
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
))
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";
4277 res
+= "Microsoft Windows Server 2008 family";
4280 res
+= "Microsoft Windows Vista or Windows Server 2008";
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";
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";
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";
4370 else if (osvi
.dwMajorVersion
<= 4) // Windows NT 4.0
4372 if (osvi
.wSuiteMask
& VER_SUITE_ENTERPRISE
)
4374 res
+= " Server 4.0, Enterprise Edition";
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
4391 char szProductType
[BUFSIZE
];
4392 DWORD dwBufLen
=BUFSIZE
;
4395 lRet
= RegOpenKeyEx(
4397 "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
4398 0, KEY_QUERY_VALUE
, &hKey
);
4399 if (lRet
!= ERROR_SUCCESS
)
4404 lRet
= RegQueryValueEx(hKey
, "ProductType", NULL
, NULL
,
4405 (LPBYTE
) szProductType
, &dwBufLen
);
4407 if ((lRet
!= ERROR_SUCCESS
) || (dwBufLen
> BUFSIZE
))
4414 if (lstrcmpi("WINNT", szProductType
) == 0)
4416 res
+= " Workstation";
4418 if (lstrcmpi("LANMANNT", szProductType
) == 0)
4422 if (lstrcmpi("SERVERNT", szProductType
) == 0)
4424 res
+= " Advanced Server";
4428 sprintf(buffer
, "%ld", osvi
.dwMajorVersion
);
4431 sprintf(buffer
, "%ld", osvi
.dwMinorVersion
);
4435 // Display service pack (if any) and build number.
4437 if (osvi
.dwMajorVersion
== 4 &&
4438 lstrcmpi(osvi
.szCSDVersion
, "Service Pack 6") == 0)
4443 // Test for SP6 versus SP6a.
4445 lRet
= RegOpenKeyEx(
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);
4457 else // Windows NT 4.0 prior to SP6a
4460 res
+= osvi
.szCSDVersion
;
4462 sprintf(buffer
, "%ld", osvi
.dwBuildNumber
& 0xFFFF);
4469 else // Windows NT 3.51 and earlier or Windows 2000 and later
4472 res
+= osvi
.szCSDVersion
;
4474 sprintf(buffer
, "%ld", osvi
.dwBuildNumber
& 0xFFFF);
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')
4494 if (osvi
.dwMajorVersion
== 4 && osvi
.dwMinorVersion
== 10)
4496 res
+= "Microsoft Windows 98";
4497 if (osvi
.szCSDVersion
[1] == 'A')
4503 if (osvi
.dwMajorVersion
== 4 && osvi
.dwMinorVersion
== 90)
4505 res
+= "Microsoft Windows Millennium Edition";
4509 case VER_PLATFORM_WIN32s
:
4511 res
+= "Microsoft Win32s";
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
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 );
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;
4551 // match 2 mangled user
4553 // match 4 mangled password
4556 // match 7 mangled port
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 );
4570 // ----------------------------------------------------------------------
4571 // These must NOT be initialized. Default initialization to zero is
4573 unsigned int SystemToolsManagerCount
;
4574 SystemToolsTranslationMap
*SystemTools::TranslationMap
;
4575 SystemToolsTranslationMap
*SystemTools::LongPathMap
;
4577 SystemToolsTranslationMap
*SystemTools::Cyg2Win32Map
;
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();
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
)
4611 i
= decc$
feature_get_index(name
);
4612 return i
>= 0 && (decc$
feature_set_value(i
, 1, value
) >= 0 || errno
== 0);
4616 void SystemTools::ClassInitialize()
4619 SetVMSFeature("DECC$FILENAME_UNIX_ONLY", 1);
4621 // Allocate the translation map first.
4622 SystemTools::TranslationMap
= new SystemToolsTranslationMap
;
4623 SystemTools::LongPathMap
= new SystemToolsTranslationMap
;
4625 SystemTools::Cyg2Win32Map
= new SystemToolsTranslationMap
;
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
4639 if(const char* pwd
= getenv("PWD"))
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
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());
4679 void SystemTools::ClassFinalize()
4681 delete SystemTools::TranslationMap
;
4682 delete SystemTools::LongPathMap
;
4684 delete SystemTools::Cyg2Win32Map
;
4689 } // namespace KWSYS_NAMESPACE
4691 #if defined(_MSC_VER) && defined(_DEBUG)
4692 # include <crtdbg.h>
4694 # include <stdlib.h>
4695 namespace KWSYS_NAMESPACE
4698 static int SystemToolsDebugReport(int, char* message
, int*)
4700 fprintf(stderr
, "%s", message
);
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
4715 namespace KWSYS_NAMESPACE
4717 void SystemTools::EnableMSVCDebugHook() {}
4718 } // namespace KWSYS_NAMESPACE