SystemTools.cxx 87.8 KB
Newer Older
1
2
3
4
5
/*=========================================================================

  Program:   KWSys - Kitware System Library
  Module:    SystemTools.cxx

Brad King's avatar
Brad King committed
6
7
  Copyright (c) Kitware, Inc., Insight Consortium.  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
8

Brad King's avatar
Brad King committed
9
10
     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11
12
13
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
14
15
#include "kwsysPrivate.h"
#include KWSYS_HEADER(SystemTools.hxx)
16
#include KWSYS_HEADER(Directory.hxx)
17

18
19
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(ios/fstream)
20
#include KWSYS_HEADER(ios/sstream)
21

22
23
24
25
26
27
28
29
30
31
// Work-around CMake dependency scanning limitation.  This must
// duplicate the above list of headers.
#if 0
# include "SystemTools.hxx.in"
# include "Directory.hxx.in"
# include "kwsys_ios_iostream.h.in"
# include "kwsys_ios_fstream.h.in"
# include "kwsys_ios_sstream.h.in"
#endif

32
33
34
35
#ifdef _MSC_VER
# pragma warning (disable: 4786)
#endif

36
37
38
#if defined(__sgi) && !defined(__GNUC__)
# pragma set woff 1375 /* base class destructor not virtual */
#endif
39

40
41
#include <ctype.h>
#include <errno.h>
42
43
#ifdef __QNX__
# include <malloc.h> /* for malloc/free on QNX */
44
#endif
45
46
47
48
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
49
50
51
52
53
54
55
#include <time.h>

// support for realpath call
#ifndef _WIN32
#include <limits.h>
#include <sys/param.h>
#include <sys/wait.h>
56
57
#include <sys/ioctl.h>
#include <unistd.h>
Andy Cedilnik's avatar
Andy Cedilnik committed
58
#include <termios.h>
59
60
#endif

61
62
63
64
65
// Windows API.  Some parts used even on cygwin.
#if defined(_WIN32)
# include <windows.h>
#endif

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// This is a hack to prevent warnings about these functions being
// declared but not referenced.
#if defined(__sgi) && !defined(__GNUC__)
# include <sys/termios.h>
namespace KWSYS_NAMESPACE
{
class SystemToolsHack
{
public:
  enum
  {
    Ref1 = sizeof(cfgetospeed(0)),
    Ref2 = sizeof(cfgetispeed(0)),
    Ref3 = sizeof(tcgetattr(0, 0)),
    Ref4 = sizeof(tcsetattr(0, 0, 0)),
    Ref5 = sizeof(cfsetospeed(0,0)),
    Ref6 = sizeof(cfsetispeed(0,0))
  };
};
}
#endif
87

88
#if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__))
89
#include <io.h>
90
91
92
93
94
95
#include <direct.h>
#define _unlink unlink
inline int Mkdir(const char* dir)
{
  return _mkdir(dir);
}
96
97
98
99
inline int Rmdir(const char* dir)
{
  return _rmdir(dir);
}
100
101
102
103
104
105
106
107
108
109
110
111
inline const char* Getcwd(char* buf, unsigned int len)
{
  return _getcwd(buf, len);
}
inline int Chdir(const char* dir)
{
  #if defined(__BORLANDC__)
  return chdir(dir);
  #else
  return _chdir(dir);
  #endif
}
112
inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
113
114
115
116
117
{
  char *ptemp;
  char fullpath[MAX_PATH];
  if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
    {
118
119
    resolved_path = fullpath;
    KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
120
121
    }
}
122
123
124
125
126
127
128
129
#else
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
inline int Mkdir(const char* dir)
{
  return mkdir(dir, 00777);
}
130
131
132
133
inline int Rmdir(const char* dir)
{
  return rmdir(dir);
}
134
135
136
137
138
139
140
141
inline const char* Getcwd(char* buf, unsigned int len)
{
  return getcwd(buf, len);
}
inline int Chdir(const char* dir)
{
  return chdir(dir);
}
142
inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
143
{
144
145
146
147
148
149
150
151
152
153
154
155
# ifdef MAXPATHLEN
  char resolved_name[MAXPATHLEN];
# else
#  ifdef PATH_MAX
  char resolved_name[PATH_MAX];
#  else
  char resolved_name[5024];
#  endif  //PATH_MAX
# endif //MAXPATHLEN

  realpath(path, resolved_name);
  resolved_path = resolved_name;
156
}
157
158
#endif

159
160
161
162
163
164
165
166
167
168
169
170
#if !defined(_WIN32) && defined(__COMO__)
// Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
extern "C"
{
extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
extern int pclose (FILE *__stream) __THROW;
extern char *realpath (__const char *__restrict __name,
                       char *__restrict __resolved) __THROW;
extern char *strdup (__const char *__s) __THROW;
extern int putenv (char *__string) __THROW;
}
#endif
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193

/* Implement floattime() for various platforms */
// Taken from Python 2.1.3

#if defined( _WIN32 ) && !defined( __CYGWIN__ )
#  include <sys/timeb.h>
#  define HAVE_FTIME
#  if defined( __BORLANDC__)
#    define FTIME ftime
#    define TIMEB timeb
#  else // Visual studio?
#    define FTIME _ftime
#    define TIMEB _timeb
#  endif
#elif defined( __CYGWIN__ ) || defined( __linux__ )
#  include <sys/time.h>
#  include <time.h>
#  define HAVE_GETTIMEOFDAY
#endif

namespace KWSYS_NAMESPACE
{

194
195
196
197
198
class SystemToolsTranslationMap : 
    public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
{
};

199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
double
SystemTools::GetTime(void)
{
  /* There are three ways to get the time:
     (1) gettimeofday() -- resolution in microseconds
     (2) ftime() -- resolution in milliseconds
     (3) time() -- resolution in seconds
     In all cases the return value is a float in seconds.
     Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
     fail, so we fall back on ftime() or time().
     Note: clock resolution does not imply clock accuracy! */
#ifdef HAVE_GETTIMEOFDAY
  {
  struct timeval t;
#ifdef GETTIMEOFDAY_NO_TZ
  if (gettimeofday(&t) == 0)
    return (double)t.tv_sec + t.tv_usec*0.000001;
#else /* !GETTIMEOFDAY_NO_TZ */
  if (gettimeofday(&t, (struct timezone *)NULL) == 0)
    return (double)t.tv_sec + t.tv_usec*0.000001;
#endif /* !GETTIMEOFDAY_NO_TZ */
  }
#endif /* !HAVE_GETTIMEOFDAY */
  {
#if defined(HAVE_FTIME)
  struct TIMEB t;
225
  ::FTIME(&t);
226
227
228
229
230
231
232
233
234
235
  return (double)t.time + (double)t.millitm * (double)0.001;
#else /* !HAVE_FTIME */
  time_t secs;
  time(&secs);
  return (double)secs;
#endif /* !HAVE_FTIME */
  }
}

// adds the elements of the env variable path to the arg passed in
236
void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
237
238
239
240
241
242
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  const char* pathSep = ";";
#else
  const char* pathSep = ":";
#endif
243
244
245
246
  if(!env)
    {
    env = "PATH";
    }
247
248
249
250
251
252
253
254
  const char* cpathEnv = SystemTools::GetEnv(env);
  if ( !cpathEnv )
    {
    return;
    }

  kwsys_stl::string pathEnv = cpathEnv;
   
255
256
257
258
259
  // A hack to make the below algorithm work.  
  if(pathEnv[pathEnv.length()-1] != ':')
    {
    pathEnv += pathSep;
    }
260
  kwsys_stl::string::size_type start =0;
261
262
263
  bool done = false;
  while(!done)
    {
264
265
    kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
    if(endpos != kwsys_stl::string::npos)
266
267
268
269
270
271
272
273
274
      {
      path.push_back(pathEnv.substr(start, endpos-start));
      start = endpos+1;
      }
    else
      {
      done = true;
      }
    }
275
  for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
276
277
278
279
280
281
      i != path.end(); ++i)
    {
    SystemTools::ConvertToUnixSlashes(*i);
    }
}

Brad King's avatar
Brad King committed
282
283
284
285
286
const char* SystemTools::GetEnv(const char* key)
{
  return getenv(key);
}

287
bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
Brad King's avatar
Brad King committed
288
289
290
291
292
293
294
295
296
297
298
299
{
  const char* v = getenv(key);
  if(v)
    {
    result = v;
    return true;
    }
  else
    {
    return false;
    }
}
300
301
302
303
304
305
306
307
308
309
310
311
312

const char* SystemTools::GetExecutableExtension()
{
#if defined(_WIN32) || defined(__CYGWIN__)
  return ".exe";
#else
  return "";
#endif  
}


bool SystemTools::MakeDirectory(const char* path)
{
313
314
  if(SystemTools::FileExists(path))
    {
315
    return true;
316
    }
317
  kwsys_stl::string dir = path;
318
319
320
321
322
323
  if(dir.size() == 0)
    {
    return false;
    }
  SystemTools::ConvertToUnixSlashes(dir);

324
325
  kwsys_stl::string::size_type pos = dir.find(':');
  if(pos == kwsys_stl::string::npos)
326
327
328
    {
    pos = 0;
    }
329
330
  kwsys_stl::string topdir;
  while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
    {
    topdir = dir.substr(0, pos);
    Mkdir(topdir.c_str());
    pos++;
    }
  if(dir[dir.size()-1] == '/')
    {
    topdir = dir.substr(0, dir.size());
    }
  else
    {
    topdir = dir;
    }
  if(Mkdir(topdir.c_str()) != 0)
    {
    // There is a bug in the Borland Run time library which makes MKDIR
    // return EACCES when it should return EEXISTS
    // if it is some other error besides directory exists
    // then return false
    if( (errno != EEXIST) 
#ifdef __BORLANDC__
        && (errno != EACCES) 
#endif      
      )
      {
      return false;
      }
    }
  return true;
}


// replace replace with with as many times as it shows up in source.
// write the result into source.
365
void SystemTools::ReplaceString(kwsys_stl::string& source,
366
367
368
                                   const char* replace,
                                   const char* with)
{
Ken Martin's avatar
Ken Martin committed
369
  const char *src = source.c_str();
Bill Lorensen's avatar
Bill Lorensen committed
370
  char *searchPos = const_cast<char *>(strstr(src,replace));
Ken Martin's avatar
Ken Martin committed
371
  
372
  // get out quick if string is not found
Ken Martin's avatar
Ken Martin committed
373
  if (!searchPos)
374
375
376
    {
    return;
    }
Ken Martin's avatar
Ken Martin committed
377
378
379
380
381
382
383
384

  // perform replacements until done
  size_t replaceSize = strlen(replace);
  char *orig = strdup(src);
  char *currentPos = orig;
  searchPos = searchPos - src + orig;
  
  // initialize the result
Ken Martin's avatar
Ken Martin committed
385
  source.erase(source.begin(),source.end());
Ken Martin's avatar
Ken Martin committed
386
  do
387
    {
Ken Martin's avatar
Ken Martin committed
388
389
390
391
    *searchPos = '\0';
    source += currentPos;
    currentPos = searchPos + replaceSize;
    // replace
392
    source += with;
Ken Martin's avatar
Ken Martin committed
393
    searchPos = strstr(currentPos,replace);
394
    }
Ken Martin's avatar
Ken Martin committed
395
396
397
398
399
  while (searchPos);

  // copy any trailing text
  source += currentPos;
  free(orig);
400
401
402
403
404
405
406
407
408
409
}

// Read a registry value.
// Example : 
//      HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
//      =>  will return the data of the "default" value of the key
//      HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
//      =>  will return the data of the "Root" value of the key

#if defined(_WIN32) && !defined(__CYGWIN__)
410
bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value)
411
412
{

413
414
415
  kwsys_stl::string primary = key;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
416
417
 
  size_t start = primary.find("\\");
418
  if (start == kwsys_stl::string::npos)
419
420
421
422
423
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
424
  if (valuenamepos != kwsys_stl::string::npos)
425
426
427
428
429
430
431
    {
    valuename = primary.substr(valuenamepos+1);
    }

  second = primary.substr(start+1, valuenamepos-start-1);
  primary = primary.substr(0, start);
  
Bill Hoffman's avatar
Bill Hoffman committed
432
  HKEY primaryKey = HKEY_CURRENT_USER;
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
  if (primary == "HKEY_CURRENT_USER")
    {
    primaryKey = HKEY_CURRENT_USER;
    }
  if (primary == "HKEY_CURRENT_CONFIG")
    {
    primaryKey = HKEY_CURRENT_CONFIG;
    }
  if (primary == "HKEY_CLASSES_ROOT")
    {
    primaryKey = HKEY_CLASSES_ROOT;
    }
  if (primary == "HKEY_LOCAL_MACHINE")
    {
    primaryKey = HKEY_LOCAL_MACHINE;
    }
  if (primary == "HKEY_USERS")
    {
    primaryKey = HKEY_USERS;
    }
  
  HKEY hKey;
  if(RegOpenKeyEx(primaryKey, 
                  second.c_str(), 
                  0, 
                  KEY_READ, 
                  &hKey) != ERROR_SUCCESS)
    {
    return false;
    }
  else
    {
    DWORD dwType, dwSize;
    dwSize = 1023;
    char data[1024];
    if(RegQueryValueEx(hKey, 
                       (LPTSTR)valuename.c_str(), 
                       NULL, 
                       &dwType, 
                       (BYTE *)data, 
                       &dwSize) == ERROR_SUCCESS)
      {
      if (dwType == REG_SZ)
        {
        value = data;
478
        RegCloseKey(hKey);
479
480
481
482
483
484
485
        return true;
        }
      }
    }
  return false;
}
#else
486
bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &)
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
{
  return false;
}
#endif


// Write a registry value.
// Example : 
//      HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
//      =>  will set the data of the "default" value of the key
//      HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
//      =>  will set the data of the "Root" value of the key

#if defined(_WIN32) && !defined(__CYGWIN__)
bool SystemTools::WriteRegistryValue(const char *key, const char *value)
{
503
504
505
  kwsys_stl::string primary = key;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
506
507
 
  size_t start = primary.find("\\");
508
  if (start == kwsys_stl::string::npos)
509
510
511
512
513
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
514
  if (valuenamepos != kwsys_stl::string::npos)
515
516
517
518
519
520
521
    {
    valuename = primary.substr(valuenamepos+1);
    }

  second = primary.substr(start+1, valuenamepos-start-1);
  primary = primary.substr(0, start);
  
Bill Hoffman's avatar
Bill Hoffman committed
522
  HKEY primaryKey = HKEY_CURRENT_USER;
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
  if (primary == "HKEY_CURRENT_USER")
    {
    primaryKey = HKEY_CURRENT_USER;
    }
  if (primary == "HKEY_CURRENT_CONFIG")
    {
    primaryKey = HKEY_CURRENT_CONFIG;
    }
  if (primary == "HKEY_CLASSES_ROOT")
    {
    primaryKey = HKEY_CLASSES_ROOT;
    }
  if (primary == "HKEY_LOCAL_MACHINE")
    {
    primaryKey = HKEY_LOCAL_MACHINE;
    }
  if (primary == "HKEY_USERS")
    {
    primaryKey = HKEY_USERS;
    }
  
  HKEY hKey;
  DWORD dwDummy;
  if(RegCreateKeyEx(primaryKey, 
                    second.c_str(), 
                    0, 
                    "",
                    REG_OPTION_NON_VOLATILE,
                    KEY_WRITE,
                    NULL,
                    &hKey,
                    &dwDummy) != ERROR_SUCCESS)
    {
    return false;
    }

  if(RegSetValueEx(hKey, 
                   (LPTSTR)valuename.c_str(), 
                   0, 
                   REG_SZ, 
                   (CONST BYTE *)value, 
                   (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
    {
    return true;
    }
  return false;
}
#else
bool SystemTools::WriteRegistryValue(const char *, const char *)
{
  return false;
}
#endif

// Delete a registry value.
// Example : 
//      HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
//      =>  will delete the data of the "default" value of the key
//      HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
//      =>  will delete  the data of the "Root" value of the key

#if defined(_WIN32) && !defined(__CYGWIN__)
bool SystemTools::DeleteRegistryValue(const char *key)
{
587
588
589
  kwsys_stl::string primary = key;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
590
591
 
  size_t start = primary.find("\\");
592
  if (start == kwsys_stl::string::npos)
593
594
595
596
597
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
598
  if (valuenamepos != kwsys_stl::string::npos)
599
600
601
602
603
604
605
    {
    valuename = primary.substr(valuenamepos+1);
    }

  second = primary.substr(start+1, valuenamepos-start-1);
  primary = primary.substr(0, start);
  
Bill Hoffman's avatar
Bill Hoffman committed
606
  HKEY primaryKey = HKEY_CURRENT_USER;
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
  if (primary == "HKEY_CURRENT_USER")
    {
    primaryKey = HKEY_CURRENT_USER;
    }
  if (primary == "HKEY_CURRENT_CONFIG")
    {
    primaryKey = HKEY_CURRENT_CONFIG;
    }
  if (primary == "HKEY_CLASSES_ROOT")
    {
    primaryKey = HKEY_CLASSES_ROOT;
    }
  if (primary == "HKEY_LOCAL_MACHINE")
    {
    primaryKey = HKEY_LOCAL_MACHINE;
    }
  if (primary == "HKEY_USERS")
    {
    primaryKey = HKEY_USERS;
    }
  
  HKEY hKey;
  if(RegOpenKeyEx(primaryKey, 
                  second.c_str(), 
                  0, 
                  KEY_WRITE, 
                  &hKey) != ERROR_SUCCESS)
    {
    return false;
    }
  else
    {
    if(RegDeleteValue(hKey, 
                      (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
      {
642
      RegCloseKey(hKey);
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
      return true;
      }
    }
  return false;
}
#else
bool SystemTools::DeleteRegistryValue(const char *)
{
  return false;
}
#endif

bool SystemTools::SameFile(const char* file1, const char* file2)
{
#ifdef _WIN32
  HANDLE hFile1, hFile2;

  hFile1 = CreateFile( file1, 
                      GENERIC_READ, 
                      FILE_SHARE_READ ,
                      NULL,
                      OPEN_EXISTING,
                      FILE_FLAG_BACKUP_SEMANTICS,
                      NULL
    );
  hFile2 = CreateFile( file2, 
                      GENERIC_READ, 
                      FILE_SHARE_READ, 
                      NULL,
                      OPEN_EXISTING,
                      FILE_FLAG_BACKUP_SEMANTICS,
                      NULL
    );
  if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
    {
    if(hFile1 != INVALID_HANDLE_VALUE)
      {
      CloseHandle(hFile1);
      }
    if(hFile2 != INVALID_HANDLE_VALUE)
      {
      CloseHandle(hFile2);
      }
    return false;
    }

   BY_HANDLE_FILE_INFORMATION fiBuf1;
   BY_HANDLE_FILE_INFORMATION fiBuf2;
   GetFileInformationByHandle( hFile1, &fiBuf1 );
   GetFileInformationByHandle( hFile2, &fiBuf2 );
   CloseHandle(hFile1);
   CloseHandle(hFile2);
695
696
   return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
           fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
           fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
#else
  struct stat fileStat1, fileStat2;
  if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
    {
    // see if the files are the same file
    // check the device inode and size
    if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 && 
       memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
       fileStat2.st_size == fileStat1.st_size 
      ) 
      {
      return true;
      }
    }
  return false;
#endif
}


// return true if the file exists
bool SystemTools::FileExists(const char* filename)
{
720
721
#ifdef _MSC_VER
# define access _access
722
#endif
723
724
#ifndef R_OK
# define R_OK 04
725
#endif
726
  if ( access(filename, R_OK) != 0 )
727
728
729
730
731
732
733
734
735
736
    {
    return false;
    }
  else
    {
    return true;
    }
}


737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
                                  int* result)
{
  // Default to same time.
  *result = 0;
#if !defined(_WIN32) || defined(__CYGWIN__)
  // POSIX version.  Use stat function to get file modification time.
  struct stat s1;
  if(stat(f1, &s1) != 0)
    {
    return false;
    }
  struct stat s2;
  if(stat(f2, &s2) != 0)
    {
    return false;
    }
# if KWSYS_STAT_HAS_ST_MTIM
  // Compare using nanosecond resolution.
  if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
    {
    *result = -1;
    }
  else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
    {
    *result = 1;
    }
  else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
    {
    *result = -1;
    }
  else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
    {
    *result = 1;
    }
# else
  // Compare using 1 second resolution.
  if(s1.st_mtime < s2.st_mtime)
    {
    *result = -1;
    }
  else if(s1.st_mtime > s2.st_mtime)
    {
    *result = 1;
    }
# endif
#else
  // Windows version.  Create file handles and get the modification times.
  HANDLE hf1 = CreateFile(f1, GENERIC_READ, FILE_SHARE_READ,
                          NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
                          NULL);
  if(hf1 == INVALID_HANDLE_VALUE)
    {
    return false;
    }
  FILETIME tf1;
  if(!GetFileTime(hf1, 0, 0, &tf1))
    {
    CloseHandle(hf1);
    return false;
    }
  CloseHandle(hf1);
  HANDLE hf2 = CreateFile(f2, GENERIC_READ, FILE_SHARE_READ,
                          NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
                          NULL);
  if(hf2 == INVALID_HANDLE_VALUE)
    {
    return false;
    }
  FILETIME tf2;
  if(!GetFileTime(hf2, 0, 0, &tf2))
    {
    CloseHandle(hf2);
    return false;
    }
  CloseHandle(hf2);

  // Compare the file times using resolution provided by system call.
  *result = (int)CompareFileTime(&tf1, &tf2);
#endif
  return true;
}


821
822
// Return a capitalized string (i.e the first letter is uppercased, all other
// are lowercased)
823
kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
824
{
825
  kwsys_stl::string n;
Bill Hoffman's avatar
Bill Hoffman committed
826
827
828
829
  if(s.size() == 0)
    {
    return n;
    }
830
  n.resize(s.size());
Bill Hoffman's avatar
Bill Hoffman committed
831
  n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
832
833
  for (size_t i = 1; i < s.size(); i++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
834
    n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
835
836
837
838
    }
  return n;
}

839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
// Return capitalized words
kwsys_stl::string SystemTools::CapitalizedWords(const kwsys_stl::string& s)
{
  kwsys_stl::string n(s);
  for (size_t i = 0; i < s.size(); i++)
    {
    if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
      {
      n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
      }
    }
  return n;
}

// Return uncapitalized words
kwsys_stl::string SystemTools::UnCapitalizedWords(const kwsys_stl::string& s)
{
  kwsys_stl::string n(s);
  for (size_t i = 0; i < s.size(); i++)
    {
    if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
      {
      n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
      }
    }
  return n;
}
866

867
868
869
870
871
872
873
874
875
876
877
878
879
880
kwsys_stl::string SystemTools::AddSpaceBetweenCapitalizedWords(
  const kwsys_stl::string& s)
{
  kwsys_stl::string n;
  if (s.size())
    {
    n.reserve(s.size());
    n += s[0];
    for (size_t i = 1; i < s.size(); i++)
      {
      if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1]))
        {
        n += ' ';
        }
Sebastien Barre's avatar
Sebastien Barre committed
881
      n += s[i];
882
883
884
885
886
      }
    }
  return n;
}

887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
char* SystemTools::AppendStrings(const char* str1, const char* str2)
{
  if (!str1)
    {
    return SystemTools::DuplicateString(str2);
    }
  if (!str2)
    {
    return SystemTools::DuplicateString(str1);
    }
  size_t len1 = strlen(str1);
  char *newstr = new char[len1 + strlen(str2) + 1];
  if (!newstr)
    {
    return 0;
    }
  strcpy(newstr, str1);
  strcat(newstr + len1, str2);
  return newstr;
}

char* SystemTools::AppendStrings(
  const char* str1, const char* str2, const char* str3)
{
  if (!str1)
    {
    return SystemTools::AppendStrings(str2, str3);
    }
  if (!str2)
    {
    return SystemTools::AppendStrings(str1, str3);
    }
  if (!str3)
    {
    return SystemTools::AppendStrings(str1, str2);
    }

  size_t len1 = strlen(str1), len2 = strlen(str2);
  char *newstr = new char[len1 + len2 + strlen(str3) + 1];
  if (!newstr)
    {
    return 0;
    }
  strcpy(newstr, str1);
  strcat(newstr + len1, str2);
  strcat(newstr + len1 + len2, str3);
  return newstr;
}

936
// Return a lower case string 
937
kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
938
{
939
  kwsys_stl::string n;
940
941
942
  n.resize(s.size());
  for (size_t i = 0; i < s.size(); i++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
943
    n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
944
945
946
947
948
    }
  return n;
}

// Return a lower case string 
949
kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
950
{
951
  kwsys_stl::string n;
952
953
954
  n.resize(s.size());
  for (size_t i = 0; i < s.size(); i++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
955
    n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
956
957
958
959
    }
  return n;
}

960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
// Count char in string
size_t SystemTools::CountChar(const char* str, char c)
{
  size_t count = 0;

  if (str)
    {
    while (*str)
      {
      if (*str == c)
        {
        ++count;
        }
      ++str;
      }
    }
  return count;
}

// Remove chars in string
char* SystemTools::RemoveChars(const char* str, const char *toremove)
{
  if (!str)
    {
    return NULL;
    }
  char *clean_str = new char [strlen(str) + 1];
  char *ptr = clean_str;
  while (*str)
    {
    const char *str2 = toremove;
    while (*str2 && *str != *str2)
      {
      ++str2;
      }
    if (!*str2)
      {
      *ptr++ = *str;
      }
    ++str;
    }
  *ptr = '\0';
  return clean_str;
}

// Remove chars in string
char* SystemTools::RemoveCharsButUpperHex(const char* str)
{
  if (!str)
    {
    return 0;
    }
  char *clean_str = new char [strlen(str) + 1];
  char *ptr = clean_str;
  while (*str)
    {
    if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'H'))
      {
      *ptr++ = *str;
      }
    ++str;
    }
  *ptr = '\0';
  return clean_str;
}

// Replace chars in string
char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
{
  if (str)
    {
    char *ptr = str;
    while (*ptr)
      {
      const char *ptr2 = toreplace;
      while (*ptr2)
        {
        if (*ptr == *ptr2)
          {
          *ptr = replacement;
          }
        ++ptr2;
        }
      ++ptr;
      }
    }
  return str;
}

1049
// Returns if string starts with another string
1050
bool SystemTools::StringStartsWith(const char* str1, const char* str2)
1051
1052
1053
1054
1055
1056
{
  if (!str1 || !str2)
    {
    return false;
    }
  size_t len1 = strlen(str1), len2 = strlen(str2);
1057
  return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
1058
1059
1060
}

// Returns if string ends with another string
1061
bool SystemTools::StringEndsWith(const char* str1, const char* str2)
1062
1063
1064
1065
1066
1067
1068
1069
1070
{
  if (!str1 || !str2)
    {
    return false;
    }
  size_t len1 = strlen(str1), len2 = strlen(str2);
  return len1 >= len2 &&  !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
}

1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
// Returns a pointer to the last occurence of str2 in str1
const char* SystemTools::FindLastString(const char* str1, const char* str2)
{
  if (!str1 || !str2)
    {
    return NULL;
    }
  
  size_t len1 = strlen(str1), len2 = strlen(str2);
  if (len1 >= len2)
    {
    const char *ptr = str1 + len1 - len2;
    do
      {
      if (!strncmp(ptr, str2, len2))
        {
        return ptr;
        }
      } while (ptr-- != str1);
    }

  return NULL;
}

// Duplicate string
char* SystemTools::DuplicateString(const char* str)
{
  if (str)
    {
    char *newstr = new char [strlen(str) + 1];
    return strcpy(newstr, str);
    }
  return NULL;
}

1106
// Return a cropped string 
1107
1108
kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s, 
                                          size_t max_len)
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
{
  if (!s.size() || max_len == 0 || max_len >= s.size())
    {
    return s;
    }

  kwsys_stl::string n;
  n.reserve(max_len);

  size_t middle = max_len / 2;

  n += s.substr(0, middle);
  n += s.substr(s.size() - (max_len - middle), kwsys_stl::string::npos);

  if (max_len > 2)
    {
    n[middle] = '.';
    if (max_len > 3)
      {
      n[middle - 1] = '.';
      if (max_len > 4)
        {
        n[middle + 1] = '.';
        }
      }
    }

  return n;
}
1138

1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
//----------------------------------------------------------------------------
int SystemTools::EstimateFormatLength(const char *format, va_list ap)
{
  if (!format)
    {
    return 0;
    }

  // Quick-hack attempt at estimating the length of the string.
  // Should never under-estimate.
  
  // Start with the length of the format string itself.

  int length = strlen(format);
  
  // Increase the length for every argument in the format.

  const char* cur = format;
  while(*cur)
    {
    if(*cur++ == '%')
      {
      // Skip "%%" since it doesn't correspond to a va_arg.
      if(*cur != '%')
        {
        while(!int(isalpha(*cur)))
          {
          ++cur;
          }
        switch (*cur)
          {
          case 's':
          {
          // Check the length of the string.
          char* s = va_arg(ap, char*);
          if(s)
            {
            length += strlen(s);
            }
          } break;
          case 'e':
          case 'f':
          case 'g':
          {
          // Assume the argument contributes no more than 64 characters.
          length += 64;
            
          // Eat the argument.
          static_cast<void>(va_arg(ap, double));
          } break;
          default:
          {
          // Assume the argument contributes no more than 64 characters.
          length += 64;
            
          // Eat the argument.
          static_cast<void>(va_arg(ap, int));
          } break;
          }
        }
      
      // Move past the characters just tested.
      ++cur;
      }
    }
  
  return length;
}

1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
kwsys_stl::string SystemTools::EscapeChars(
  const char *str, 
  const char *chars_to_escape, 
  char escape_char)
{
  kwsys_stl::string n;
  if (str)
    {
    if (!chars_to_escape | !*chars_to_escape)
      {
      n.append(str);
      }
    else
      {
      n.reserve(strlen(str));
      while (*str)
        {
        const char *ptr = chars_to_escape;
        while (*ptr)
          {
          if (*str == *ptr)
            {
            n += escape_char;
            break;
            }
          ++ptr;
          }
        n += *str;
        ++str;
        }
      }
    }
  return n;
}

1243
// convert windows slashes to unix slashes 
1244
void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
1245
{
Andy Cedilnik's avatar
Andy Cedilnik committed
1246
1247
1248
1249
1250
  const char* pathCString = path.c_str();
  bool hasDoubleSlash = false;

  const char* pos0 = pathCString;
  const char* pos1 = pathCString+1;
1251
  for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
1252
    {
1253
    // make sure we don't convert an escaped space to a unix slash
Andy Cedilnik's avatar
Andy Cedilnik committed
1254
    if ( *pos0 == '\\' && *pos1 != ' ' )
1255
      {
Andy Cedilnik's avatar
Andy Cedilnik committed
1256
      path[pos] = '/';
1257
      }
1258

Andy Cedilnik's avatar
Andy Cedilnik committed
1259
1260
1261
1262
    // Also, reuse the loop to check for slash followed by another slash
    if ( !hasDoubleSlash && *pos1 &&
      *pos1 == '/' && *(pos1+1) == '/' )
      {
1263
#ifdef _WIN32
Andy Cedilnik's avatar
Andy Cedilnik committed
1264
1265
1266
1267
1268
1269
      // However, on windows if the first characters are both slashes,
      // then keep them that way, so that network paths can be handled.
      if ( pos > 0)
        {
        hasDoubleSlash = true;
        }
Ken Martin's avatar
Ken Martin committed
1270
#else
Andy Cedilnik's avatar
Andy Cedilnik committed
1271
      hasDoubleSlash = true;
1272
#endif
Andy Cedilnik's avatar
Andy Cedilnik committed
1273
      }
1274

Andy Cedilnik's avatar
Andy Cedilnik committed
1275
1276
1277
1278
1279
    pos0 ++;
    pos1 ++;
    }

  if ( hasDoubleSlash )
1280
1281
1282
1283
1284
    {
    SystemTools::ReplaceString(path, "//", "/");
    }
  
  // remove any trailing slash
Andy Cedilnik's avatar
Andy Cedilnik committed
1285
  if(!path.empty())
1286
    {
Andy Cedilnik's avatar
Andy Cedilnik committed
1287
    // if there is a tilda ~ then replace it with HOME
1288
    pathCString = path.c_str();
Andy Cedilnik's avatar
Andy Cedilnik committed
1289
1290
1291
1292
1293
1294
1295
1296
    if(*pathCString == '~')
      {
      const char* homeEnv = SystemTools::GetEnv("HOME");
      if (homeEnv)
        {
        path.replace(0,1,homeEnv);
        }
      }
1297

1298
    pathCString = path.c_str();
Andy Cedilnik's avatar
Andy Cedilnik committed
1299
    if (*(pathCString+(path.size()-1)) == '/')
1300
      {
Andy Cedilnik's avatar
Andy Cedilnik committed
1301
      path = path.substr(0, path.size()-1);
1302
      }
Andy Cedilnik's avatar
Andy Cedilnik committed
1303

1304
1305
1306
1307
    }
}

// change // to /, and escape any spaces in the path
1308
kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
1309
{
1310
  kwsys_stl::string ret = path;
1311
1312
  
  // remove // except at the beginning might be a cygwin drive
1313
  kwsys_stl::string::size_type pos=0;
1314
  while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
1315
1316
1317
1318
    {
    ret.erase(pos, 1);
    }
  // now escape spaces if there is a space in the path
1319
  if(ret.find(" ") != kwsys_stl::string::npos)
1320
    {
1321
    kwsys_stl::string result = "";
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
    char lastch = 1;
    for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
      {
        // if it is already escaped then don't try to escape it again
      if(*ch == ' ' && lastch != '\\')
        {
        result += '\\';
        }
      result += *ch;
      lastch = *ch;
      }
    ret = result;
    }
  return ret;
}

1338
kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
1339
1340
1341
1342
1343
1344
1345
1346
1347
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  return SystemTools::ConvertToWindowsOutputPath(path);
#else
  return SystemTools::ConvertToUnixOutputPath(path);
#endif
}

// remove double slashes not at the start
1348
kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
1349
{  
1350
1351
1352
1353
1354
  kwsys_stl::string ret;
  // make it big enough for all of path and double quotes
  ret.reserve(strlen(path)+3);
  // put path into the string
  ret.insert(0,path);
1355
  kwsys_stl::string::size_type pos = 0;
1356
  // first convert all of the slashes
1357
  while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
    {
    ret[pos] = '\\';
    pos++;
    }
  // check for really small paths
  if(ret.size() < 2)
    {
    return ret;
    }
  // now clean up a bit and remove double slashes
  // Only if it is not the first position in the path which is a network
  // path on windows
  pos = 1; // start at position 1
  if(ret[0] == '\"')
    {
    pos = 2;  // if the string is already quoted then start at 2
    if(ret.size() < 3)
      {
      return ret;
      }
    }
1379
  while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
1380
1381
1382
1383
1384
    {
    ret.erase(pos, 1);
    }
  // now double quote the path if it has spaces in it
  // and is not already double quoted
1385
  if(ret.find(' ') != kwsys_stl::string::npos
1386
1387
     && ret[0] != '\"')
    {
Bill Hoffman's avatar
Bill Hoffman committed
1388
1389
    ret.insert(static_cast<kwsys_stl::string::size_type>(0),
               static_cast<kwsys_stl::string::size_type>(1), '\"');
1390
    ret.append(1, '\"');
1391
1392
1393
1394
1395
    }
  return ret;
}

bool SystemTools::CopyFileIfDifferent(const char* source,
1396
                                      const char* destination)
1397
1398
1399
{
  if(SystemTools::FilesDiffer(source, destination))
    {
1400
    return SystemTools::CopyFileAlways(source, destination);
1401
    }
1402
  return true;
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
}

  
bool SystemTools::FilesDiffer(const char* source,
                                const char* destination)
{
  struct stat statSource;
  if (stat(source, &statSource) != 0) 
    {
    return true;
    }

  struct stat statDestination;
  if (stat(destination, &statDestination) != 0) 
    {
    return true;
    }

  if(statSource.st_size != statDestination.st_size)
    {
    return true;
    }

  if(statSource.st_size == 0)
    {
    return false;
    }

#if defined(_WIN32) || defined(__CYGWIN__)
1432
1433
1434
1435
  kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
                                         kwsys_ios::ios::in));
  kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
                                                   kwsys_ios::ios::in));
1436
#else
1437
1438
  kwsys_ios::ifstream finSource(source);
  kwsys_ios::ifstream finDestination(destination);
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
#endif
  if(!finSource || !finDestination)
    {
    return true;
    }

  char* source_buf = new char[statSource.st_size];
  char* dest_buf = new char[statSource.st_size];

  finSource.read(source_buf, statSource.st_size);
  finDestination.read(dest_buf, statSource.st_size);

  if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
     statSource.st_size != static_cast<long>(finDestination.gcount()))
    {
    // Failed to read files.
    delete [] source_buf;
    delete [] dest_buf;
    return true;
    }
  int ret = memcmp((const void*)source_buf, 
                   (const void*)dest_buf, 
                   statSource.st_size);

  delete [] dest_buf;
  delete [] source_buf;

  return ret != 0;
}


/**
 * Copy a file named by "source" to the file named by "destination".
 */
bool SystemTools::CopyFileAlways(const char* source, const char* destination)
{
1475
1476
1477
1478
1479
  // If files are the same do not copy
  if ( SystemTools::SameFile(source, destination) )
    {
    return true;
    }
1480
1481
1482
1483

  mode_t perm = 0;
  bool perms = SystemTools::GetPermissions(source, perm);

1484
1485
1486
1487
1488
1489
  const int bufferSize = 4096;
  char buffer[bufferSize];

  // If destination is a directory, try to create a file with the same
  // name as the source in that directory.

1490
  kwsys_stl::string new_destination;
1491
1492
1493
1494
1495
1496
  if(SystemTools::FileExists(destination) &&
     SystemTools::FileIsDirectory(destination))
    {
    new_destination = destination;
    SystemTools::ConvertToUnixSlashes(new_destination);
    new_destination += '/';
1497
    kwsys_stl::string source_name = source;
1498
1499
1500
1501
1502
1503
    new_destination += SystemTools::GetFilenameName(source_name);
    destination = new_destination.c_str();
    }

  // Create destination directory

1504
  kwsys_stl::string destination_dir = destination;
1505
1506
1507
1508
1509
1510
  destination_dir = SystemTools::GetFilenamePath(destination_dir);
  SystemTools::MakeDirectory(destination_dir.c_str());

  // Open files

#if defined(_WIN32) || defined(__CYGWIN__)
1511
1512
  kwsys_ios::ifstream fin(source, 
                    kwsys_ios::ios::binary | kwsys_ios::ios::in);
1513
#else
1514
  kwsys_ios::ifstream fin(source);
1515
1516
1517
1518
1519
#endif
  if(!fin)
    {
    return false;
    }
1520
1521
1522
1523
1524
1525
 
  // try and remove the destination file so that read only destination files
  // can be written to.
  // If the remove fails continue so that files in read only directories
  // that do not allow file removal can be modified.
  SystemTools::RemoveFile(destination);
1526

1527
#if defined(_WIN32) || defined(__CYGWIN__)
1528
1529
  kwsys_ios::ofstream fout(destination, 
                     kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
1530
#else
1531
1532
  kwsys_ios::ofstream fout(destination, 
                     kwsys_ios::ios::out | kwsys_ios::ios::trunc);
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
#endif
  if(!fout)
    {
    return false;
    }
  
  // This copy loop is very sensitive on certain platforms with
  // slightly broken stream libraries (like HPUX).  Normally, it is
  // incorrect to not check the error condition on the fin.read()
  // before using the data, but the fin.gcount() will be zero if an
  // error occurred.  Therefore, the loop should be safe everywhere.
  while(fin)
    {
    fin.read(buffer, bufferSize);
    if(fin.gcount())
      {
      fout.write(buffer, fin.gcount());
      }
    }
  
  // Make sure the operating system has finished writing the file
  // before closing it.  This will ensure the file is finished before
  // the check below.
  fout.flush();
  
  fin.close();
  fout.close();

  // More checks.
  struct stat statSource, statDestination;
  statSource.st_size = 12345;
  statDestination.st_size = 12345;
  if(stat(source, &statSource) != 0)
    {
    return false;
    }
  else if(stat(destination, &statDestination) != 0)
    {
    return false;
    }
  else if(statSource.st_size != statDestination.st_size)
    {
    return false;
    }
1577
1578
1579
1580
1581
1582
1583
  if ( perms )
    {
    if ( !SystemTools::SetPermissions(destination, perm) )
      {
      return false;
      }
    }
1584
1585
1586
  return true;
}

1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
/**
 * Copy a directory content from "source" directory to the directory named by
 * "destination".
 */
bool SystemTools::CopyADirectory(const char* source, const char* destination)
{
  Directory dir;
  dir.Load(source);
  size_t fileNum;
  if ( !SystemTools::MakeDirectory(destination) )
    {
    return false;
    }
  for (fileNum = 0; fileNum <  dir.GetNumberOfFiles(); ++fileNum)
    {
    if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
        strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
      {
      kwsys_stl::string fullPath = source;
      fullPath += "/";
      fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
      if(SystemTools::FileIsDirectory(fullPath.c_str()))
        {
        kwsys_stl::string fullDestPath = destination;
        fullDestPath += "/";
        fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
        if (!SystemTools::CopyADirectory(fullPath.c_str(), fullDestPath.c_str()))
          {
          return false;
          }
        }
      else
        {
        if(!SystemTools::CopyFileAlways(fullPath.c_str(), destination))
          {
          return false;
          }
        }
      }
    }

  return true;
}


1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
// return size of file; also returns zero if no file exists
unsigned long SystemTools::FileLength(const char* filename)
{
  struct stat fs;
  if (stat(filename, &fs) != 0) 
    {
      return 0;
    }
  else
    {
Sebastien Barre's avatar
Sebastien Barre committed
1642
      return static_cast<unsigned long>(fs.st_size);
1643
1644
1645
1646
1647
    }
}

int SystemTools::Strucmp(const char *s1, const char *s2)
{
1648
1649
// lifted from Graphvis http://www.graphviz.org 
  while ((*s1 != '\0') 
1650
         && (tolower(*s1) == tolower(*s2)))
1651
1652
1653
1654
1655
    {
      s1++;
      s2++;
    }
 
1656
  return tolower(*s1) - tolower(*s2);
1657

1658
1659
}

1660
// return file's modified time
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
long int SystemTools::ModifiedTime(const char* filename)
{
  struct stat fs;
  if (stat(filename, &fs) != 0) 
    {
    return 0;
    }
  else
    {
    return (long int)fs.st_mtime;
    }
}

1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
// return file's creation time
long int SystemTools::CreationTime(const char* filename)
{
  struct stat fs;
  if (stat(filename, &fs) != 0) 
    {
    return 0;
    }
  else
    {
    return fs.st_ctime >= 0 ? (long int)fs.st_ctime : 0;
    }
}
1687

1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
{
  if (!str || !tmt || strlen(str) < 12)
    {
    return false;
    }

  struct tm tmt2;

  // __DATE__
  // The compilation date of the current source file. The date is a string
  // literal of the form Mmm dd yyyy. The month name Mmm is the same as for
  // dates generated by the library function asctime declared in TIME.H. 

  // index:   012345678901
  // format:  Mmm dd yyyy
  // example: Dec 19 2003

  static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";

  char buffer[12];
  strcpy(buffer, str);

  buffer[3] = 0;
  char *ptr = strstr(month_names, buffer);
  if (!ptr)
    {
    return false;
    }

  int month = (ptr - month_names) / 3;
  int day = atoi(buffer + 4);
  int year = atoi(buffer + 7);

  tmt2.tm_isdst = -1;
  tmt2.tm_hour  = 0;
  tmt2.tm_min   = 0;
  tmt2.tm_sec   = 0;
  tmt2.tm_wday  = 0;
  tmt2.tm_yday  = 0;
  tmt2.tm_mday  = day;
  tmt2.tm_mon   = month;
  tmt2.tm_year  = year - 1900;

  *tmt = mktime(&tmt2);
  return true;
}

bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
{
  if (!str || !tmt || strlen(str) < 27)
    {
    return false;
    }

  struct tm tmt2;

  // __TIMESTAMP__
  // The date and time of the last modification of the current source file, 
  // expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy, 
  /// where Ddd is the abbreviated day of the week and Date is an integer 
  // from 1 to 31.

  // index:   0123456789
  //                    0123456789
  //                              0123456789
  // format:  Ddd Mmm Date hh:mm:ss yyyy
  // example: Fri Dec 19 14:34:58 2003

  static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";

  char buffer[27];
  strcpy(buffer, str);

  buffer[7] = 0;
  char *ptr = strstr(month_names, buffer + 4);
  if (!ptr)
    {
    return false;
    }

  int month = (ptr - month_names) / 3;
  int day = atoi(buffer + 8);
  int hour = atoi(buffer + 11);
  int min = atoi(buffer + 14);
  int sec = atoi(buffer + 17);
  int year = atoi(buffer + 20);

  tmt2.tm_isdst = -1;
  tmt2.tm_hour  = hour;
  tmt2.tm_min   = min;
  tmt2.tm_sec   = sec;
  tmt2.tm_wday  = 0;
  tmt2.tm_yday  = 0;
  tmt2.tm_mday  = day;
  tmt2.tm_mon   = month;
  tmt2.tm_year  = year - 1900;

  *tmt = mktime(&tmt2);
  return true;
}

1790
kwsys_stl::string SystemTools::GetLastSystemError()
1791
1792
1793
1794
1795
1796
1797
{
  int e = errno;
  return strerror(e);
}