SystemTools.cxx 128 KB
Newer Older
Kitware Robot's avatar
Kitware Robot committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*============================================================================
  KWSys - Kitware System Library
  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium

  Distributed under the OSI-approved BSD License (the "License");
  see accompanying file Copyright.txt for details.

  This software is distributed WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the License for more information.
============================================================================*/

#ifdef __osf__
#  define _OSF_SOURCE
#  define _POSIX_C_SOURCE 199506L
#  define _XOPEN_SOURCE_EXTENDED
#endif

#include "kwsysPrivate.h"
#include KWSYS_HEADER(RegularExpression.hxx)
#include KWSYS_HEADER(SystemTools.hxx)
#include KWSYS_HEADER(Directory.hxx)
Kitware Robot's avatar
Kitware Robot committed
23
24
#include KWSYS_HEADER(FStream.hxx)
#include KWSYS_HEADER(Encoding.hxx)
Kitware Robot's avatar
Kitware Robot committed
25
26
27
28
29
30
31
32
33
34
35
36

#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(ios/fstream)
#include KWSYS_HEADER(ios/sstream)

#include KWSYS_HEADER(stl/set)

// Work-around CMake dependency scanning limitation.  This must
// duplicate the above list of headers.
#if 0
# include "SystemTools.hxx.in"
# include "Directory.hxx.in"
Kitware Robot's avatar
Kitware Robot committed
37
38
# include "FStream.hxx.in"
# include "Encoding.hxx.in"
Kitware Robot's avatar
Kitware Robot committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# include "kwsys_ios_iostream.h.in"
# include "kwsys_ios_fstream.h.in"
# include "kwsys_ios_sstream.h.in"
#endif

#ifdef _MSC_VER
# pragma warning (disable: 4786)
#endif

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

#include <ctype.h>
#include <errno.h>
#ifdef __QNX__
# include <malloc.h> /* for malloc/free on QNX */
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>

// support for realpath call
#ifndef _WIN32
#include <sys/time.h>
#include <utime.h>
#include <limits.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <pwd.h>
#ifndef __VMS
#include <sys/param.h>
#include <termios.h>
#endif
#include <signal.h>    /* sigprocmask */
#endif

// Windows API.
#if defined(_WIN32)
# include <windows.h>
Kitware Robot's avatar
Kitware Robot committed
82
83
84
# ifndef INVALID_FILE_ATTRIBUTES
#  define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
# endif
Kitware Robot's avatar
Kitware Robot committed
85
86
87
88
89
90
91
92
93
94
#elif defined (__CYGWIN__)
# include <windows.h>
# undef _WIN32
#endif

#if !KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H
extern char **environ;
#endif

#ifdef __CYGWIN__
Kitware Robot's avatar
Kitware Robot committed
95
# include <sys/cygwin.h>
Kitware Robot's avatar
Kitware Robot committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#endif

// getpwnam doesn't exist on Windows and Cray Xt3/Catamount
// same for TIOCGWINSZ
#if defined(_WIN32) || defined (__LIBCATAMOUNT__)
# undef HAVE_GETPWNAM
# undef HAVE_TTY_INFO
#else
# define HAVE_GETPWNAM 1
# define HAVE_TTY_INFO 1
#endif

#define VTK_URL_PROTOCOL_REGEX "([a-zA-Z0-9]*)://(.*)"
#define VTK_URL_REGEX "([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]+)(:([0-9]+))?/(.+)?"

#ifdef _MSC_VER
#include <sys/utime.h>
#else
#include <utime.h>
#endif


// 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

#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
#include <io.h>
#include <direct.h>
#define _unlink unlink
#endif

/* The maximum length of a file name.  */
#if defined(PATH_MAX)
# define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
#elif defined(MAXPATHLEN)
# define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
#else
# define KWSYS_SYSTEMTOOLS_MAXPATH 16384
#endif
#if defined(__WATCOMC__)
#include <direct.h>
#define _mkdir mkdir
#define _rmdir rmdir
#define _getcwd getcwd
#define _chdir chdir
#endif

Kitware Robot's avatar
Kitware Robot committed
162
#if defined(__BEOS__) && !defined(__ZETA__)
Kitware Robot's avatar
Kitware Robot committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#include <be/kernel/OS.h>
#include <be/storage/Path.h>

// BeOS 5 doesn't have usleep(), but it has snooze(), which is identical.
static inline void usleep(unsigned int msec)
{
  ::snooze(msec);
}

// BeOS 5 also doesn't have realpath(), but its C++ API offers something close.
static inline char *realpath(const char *path, char *resolved_path)
{
  const size_t maxlen = KWSYS_SYSTEMTOOLS_MAXPATH;
  snprintf(resolved_path, maxlen, "%s", path);
  BPath normalized(resolved_path, NULL, true);
  const char *resolved = normalized.Path();
  if (resolved != NULL)   // NULL == No such file.
    {
    if (snprintf(resolved_path, maxlen, "%s", resolved) < maxlen)
      {
      return resolved_path;
      }
    }
  return NULL;   // something went wrong.
}
#endif

Kitware Robot's avatar
Kitware Robot committed
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#ifdef _WIN32
static time_t windows_filetime_to_posix_time(const FILETIME& ft)
{
  LARGE_INTEGER date;
  date.HighPart = ft.dwHighDateTime;
  date.LowPart = ft.dwLowDateTime;

  // removes the diff between 1970 and 1601
  date.QuadPart -= ((LONGLONG)(369 * 365 + 89) * 24 * 3600 * 10000000);

  // converts back from 100-nanoseconds to seconds
  return date.QuadPart / 10000000;
}
#endif

Kitware Robot's avatar
Kitware Robot committed
205
#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
Kitware Robot's avatar
Kitware Robot committed
206
207
208

#include <wctype.h>

Kitware Robot's avatar
Kitware Robot committed
209
inline int Mkdir(const kwsys_stl::string& dir)
Kitware Robot's avatar
Kitware Robot committed
210
{
Kitware Robot's avatar
Kitware Robot committed
211
212
  return _wmkdir(
    KWSYS_NAMESPACE::SystemTools::ConvertToWindowsExtendedPath(dir).c_str());
Kitware Robot's avatar
Kitware Robot committed
213
}
Kitware Robot's avatar
Kitware Robot committed
214
inline int Rmdir(const kwsys_stl::string& dir)
Kitware Robot's avatar
Kitware Robot committed
215
{
Kitware Robot's avatar
Kitware Robot committed
216
217
  return _wrmdir(
    KWSYS_NAMESPACE::SystemTools::ConvertToWindowsExtendedPath(dir).c_str());
Kitware Robot's avatar
Kitware Robot committed
218
219
220
}
inline const char* Getcwd(char* buf, unsigned int len)
{
Kitware Robot's avatar
Kitware Robot committed
221
222
  std::vector<wchar_t> w_buf(len);
  if(const wchar_t* ret = _wgetcwd(&w_buf[0], len))
Kitware Robot's avatar
Kitware Robot committed
223
    {
Kitware Robot's avatar
Kitware Robot committed
224
    // make sure the drive letter is capital
Kitware Robot's avatar
Kitware Robot committed
225
    if(wcslen(&w_buf[0]) > 1 && w_buf[1] == L':')
Kitware Robot's avatar
Kitware Robot committed
226
      {
Kitware Robot's avatar
Kitware Robot committed
227
      w_buf[0] = towupper(w_buf[0]);
Kitware Robot's avatar
Kitware Robot committed
228
      }
Kitware Robot's avatar
Kitware Robot committed
229
230
231
    std::string tmp = KWSYS_NAMESPACE::Encoding::ToNarrow(&w_buf[0]);
    strcpy(buf, tmp.c_str());
    return buf;
Kitware Robot's avatar
Kitware Robot committed
232
    }
Kitware Robot's avatar
Kitware Robot committed
233
  return 0;
Kitware Robot's avatar
Kitware Robot committed
234
}
Kitware Robot's avatar
Kitware Robot committed
235
inline int Chdir(const kwsys_stl::string& dir)
Kitware Robot's avatar
Kitware Robot committed
236
237
{
  #if defined(__BORLANDC__)
Kitware Robot's avatar
Kitware Robot committed
238
  return chdir(dir.c_str());
Kitware Robot's avatar
Kitware Robot committed
239
  #else
Kitware Robot's avatar
Kitware Robot committed
240
  return _wchdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str());
Kitware Robot's avatar
Kitware Robot committed
241
242
  #endif
}
Kitware Robot's avatar
Kitware Robot committed
243
inline void Realpath(const kwsys_stl::string& path, kwsys_stl::string & resolved_path)
Kitware Robot's avatar
Kitware Robot committed
244
{
Kitware Robot's avatar
Kitware Robot committed
245
246
247
248
249
  kwsys_stl::wstring tmp = KWSYS_NAMESPACE::Encoding::ToWide(path);
  wchar_t *ptemp;
  wchar_t fullpath[MAX_PATH];
  if( GetFullPathNameW(tmp.c_str(), sizeof(fullpath)/sizeof(fullpath[0]),
                       fullpath, &ptemp) )
Kitware Robot's avatar
Kitware Robot committed
250
    {
Kitware Robot's avatar
Kitware Robot committed
251
    resolved_path = KWSYS_NAMESPACE::Encoding::ToNarrow(fullpath);
Kitware Robot's avatar
Kitware Robot committed
252
253
254
255
256
257
258
259
260
261
262
    KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
    }
  else
    {
    resolved_path = path;
    }
}
#else
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
Kitware Robot's avatar
Kitware Robot committed
263
inline int Mkdir(const kwsys_stl::string& dir)
Kitware Robot's avatar
Kitware Robot committed
264
{
Kitware Robot's avatar
Kitware Robot committed
265
  return mkdir(dir.c_str(), 00777);
Kitware Robot's avatar
Kitware Robot committed
266
}
Kitware Robot's avatar
Kitware Robot committed
267
inline int Rmdir(const kwsys_stl::string& dir)
Kitware Robot's avatar
Kitware Robot committed
268
{
Kitware Robot's avatar
Kitware Robot committed
269
  return rmdir(dir.c_str());
Kitware Robot's avatar
Kitware Robot committed
270
271
272
}
inline const char* Getcwd(char* buf, unsigned int len)
{
Kitware Robot's avatar
Kitware Robot committed
273
  return getcwd(buf, len);
Kitware Robot's avatar
Kitware Robot committed
274
275
}

Kitware Robot's avatar
Kitware Robot committed
276
inline int Chdir(const kwsys_stl::string& dir)
Kitware Robot's avatar
Kitware Robot committed
277
{
Kitware Robot's avatar
Kitware Robot committed
278
  return chdir(dir.c_str());
Kitware Robot's avatar
Kitware Robot committed
279
}
Kitware Robot's avatar
Kitware Robot committed
280
inline void Realpath(const kwsys_stl::string& path, kwsys_stl::string & resolved_path)
Kitware Robot's avatar
Kitware Robot committed
281
282
283
{
  char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];

Kitware Robot's avatar
Kitware Robot committed
284
  char *ret = realpath(path.c_str(), resolved_name);
Kitware Robot's avatar
Kitware Robot committed
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
  if(ret)
    {
    resolved_path = ret;
    }
  else
    {
    // if path resolution fails, return what was passed in
    resolved_path = path;
    }
}
#endif

#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

namespace KWSYS_NAMESPACE
{

double SystemTools::GetTime(void)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  FILETIME ft;
  GetSystemTimeAsFileTime(&ft);
  return (429.4967296*ft.dwHighDateTime
          + 0.0000001*ft.dwLowDateTime
          - 11644473600.0);
#else
  struct timeval t;
  gettimeofday(&t, 0);
  return 1.0*double(t.tv_sec) + 0.000001*double(t.tv_usec);
#endif
}

class SystemToolsTranslationMap :
    public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
{
};

// adds the elements of the env variable path to the arg passed in
void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
Kitware Robot's avatar
Kitware Robot committed
337
  const char pathSep = ';';
Kitware Robot's avatar
Kitware Robot committed
338
#else
Kitware Robot's avatar
Kitware Robot committed
339
  const char pathSep = ':';
Kitware Robot's avatar
Kitware Robot committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#endif
  if(!env)
    {
    env = "PATH";
    }
  const char* cpathEnv = SystemTools::GetEnv(env);
  if ( !cpathEnv )
    {
    return;
    }

  kwsys_stl::string pathEnv = cpathEnv;

  // A hack to make the below algorithm work.
Kitware Robot's avatar
Kitware Robot committed
354
  if(!pathEnv.empty() && *pathEnv.rbegin() != pathSep)
Kitware Robot's avatar
Kitware Robot committed
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
    {
    pathEnv += pathSep;
    }
  kwsys_stl::string::size_type start =0;
  bool done = false;
  while(!done)
    {
    kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
    if(endpos != kwsys_stl::string::npos)
      {
      path.push_back(pathEnv.substr(start, endpos-start));
      start = endpos+1;
      }
    else
      {
      done = true;
      }
    }
  for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
      i != path.end(); ++i)
    {
    SystemTools::ConvertToUnixSlashes(*i);
    }
}

const char* SystemTools::GetEnv(const char* key)
{
  return getenv(key);
}

bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
{
  const char* v = getenv(key);
  if(v)
    {
    result = v;
    return true;
    }
  else
    {
    return false;
    }
}

//----------------------------------------------------------------------------

#if defined(__CYGWIN__) || defined(__GLIBC__)
# define KWSYS_PUTENV_NAME  /* putenv("A")  removes A.  */
#elif defined(_WIN32)
# define KWSYS_PUTENV_EMPTY /* putenv("A=") removes A. */
#endif

#if KWSYS_CXX_HAS_UNSETENV
/* unsetenv("A") removes A from the environment.
   On older platforms it returns void instead of int.  */
static int kwsysUnPutEnv(const char* env)
{
  if(const char* eq = strchr(env, '='))
    {
    std::string name(env, eq-env);
    unsetenv(name.c_str());
    }
  else
    {
    unsetenv(env);
    }
  return 0;
}

#elif defined(KWSYS_PUTENV_EMPTY) || defined(KWSYS_PUTENV_NAME)
/* putenv("A=") or putenv("A") removes A from the environment.  */
static int kwsysUnPutEnv(const char* env)
{
  int err = 0;
  const char* eq = strchr(env, '=');
  size_t const len = eq? (size_t)(eq-env) : strlen(env);
# ifdef KWSYS_PUTENV_EMPTY
  size_t const sz = len + 2;
# else
  size_t const sz = len + 1;
# endif
  char local_buf[256];
  char* buf = sz > sizeof(local_buf) ? (char*)malloc(sz) : local_buf;
  if(!buf)
    {
    return -1;
    }
  strncpy(buf, env, len);
# ifdef KWSYS_PUTENV_EMPTY
  buf[len] = '=';
  buf[len+1] = 0;
  if(putenv(buf) < 0)
    {
    err = errno;
    }
# else
  buf[len] = 0;
  if(putenv(buf) < 0 && errno != EINVAL)
    {
    err = errno;
    }
# endif
  if(buf != local_buf)
    {
    free(buf);
    }
  if(err)
    {
    errno = err;
    return -1;
    }
  return 0;
}

#else
/* Manipulate the "environ" global directly.  */
static int kwsysUnPutEnv(const char* env)
{
  const char* eq = strchr(env, '=');
  size_t const len = eq? (size_t)(eq-env) : strlen(env);
  int in = 0;
  int out = 0;
  while(environ[in])
    {
    if(strlen(environ[in]) > len &&
       environ[in][len] == '=' &&
       strncmp(env, environ[in], len) == 0)
      {
      ++in;
      }
    else
      {
      environ[out++] = environ[in++];
      }
    }
  while(out < in)
    {
    environ[out++] = 0;
    }
  return 0;
}
#endif

//----------------------------------------------------------------------------

#if KWSYS_CXX_HAS_SETENV

/* setenv("A", "B", 1) will set A=B in the environment and makes its
   own copies of the strings.  */
bool SystemTools::PutEnv(const char* env)
{
  if(const char* eq = strchr(env, '='))
    {
    std::string name(env, eq-env);
    return setenv(name.c_str(), eq+1, 1) == 0;
    }
  else
    {
    return kwsysUnPutEnv(env) == 0;
    }
}

bool SystemTools::UnPutEnv(const char* env)
{
  return kwsysUnPutEnv(env) == 0;
}

#else

/* putenv("A=B") will set A=B in the environment.  Most putenv implementations
   put their argument directly in the environment.  They never free the memory
   on program exit.  Keep an active set of pointers to memory we allocate and
   pass to putenv, one per environment key.  At program exit remove any
   environment values that may still reference memory we allocated.  Then free
   the memory.  This will not affect any environment values we never set.  */

# ifdef __INTEL_COMPILER
#  pragma warning disable 444 /* base has non-virtual destructor */
# endif

/* Order by environment key only (VAR from VAR=VALUE).  */
struct kwsysEnvCompare
{
  bool operator() (const char* l, const char* r) const
    {
    const char* leq = strchr(l, '=');
    const char* req = strchr(r, '=');
    size_t llen = leq? (leq-l) : strlen(l);
    size_t rlen = req? (req-r) : strlen(r);
    if(llen == rlen)
      {
      return strncmp(l,r,llen) < 0;
      }
    else
      {
      return strcmp(l,r) < 0;
      }
    }
};

class kwsysEnv: public kwsys_stl::set<const char*, kwsysEnvCompare>
{
  class Free
  {
    const char* Env;
  public:
    Free(const char* env): Env(env) {}
    ~Free() { free(const_cast<char*>(this->Env)); }
  };
public:
  typedef kwsys_stl::set<const char*, kwsysEnvCompare> derived;
  ~kwsysEnv()
    {
    for(derived::iterator i = this->begin(); i != this->end(); ++i)
      {
      kwsysUnPutEnv(*i);
      free(const_cast<char*>(*i));
      }
    }
  const char* Release(const char* env)
    {
    const char* old = 0;
    derived::iterator i = this->find(env);
    if(i != this->end())
      {
      old = *i;
      this->erase(i);
      }
    return old;
    }
  bool Put(const char* env)
    {
    Free oldEnv(this->Release(env));
    static_cast<void>(oldEnv);
    char* newEnv = strdup(env);
    this->insert(newEnv);
    return putenv(newEnv) == 0;
    }
  bool UnPut(const char* env)
    {
    Free oldEnv(this->Release(env));
    static_cast<void>(oldEnv);
    return kwsysUnPutEnv(env) == 0;
    }
};

static kwsysEnv kwsysEnvInstance;

bool SystemTools::PutEnv(const char* env)
{
  return kwsysEnvInstance.Put(env);
}

bool SystemTools::UnPutEnv(const char* env)
{
  return kwsysEnvInstance.UnPut(env);
}

#endif

//----------------------------------------------------------------------------

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

Kitware Robot's avatar
Kitware Robot committed
626
FILE* SystemTools::Fopen(const kwsys_stl::string& file, const char* mode)
Kitware Robot's avatar
Kitware Robot committed
627
628
{
#ifdef _WIN32
Kitware Robot's avatar
Kitware Robot committed
629
  return _wfopen(SystemTools::ConvertToWindowsExtendedPath(file).c_str(),
Kitware Robot's avatar
Kitware Robot committed
630
631
                 Encoding::ToWide(mode).c_str());
#else
Kitware Robot's avatar
Kitware Robot committed
632
  return fopen(file.c_str(), mode);
Kitware Robot's avatar
Kitware Robot committed
633
634
#endif
}
Kitware Robot's avatar
Kitware Robot committed
635
636
637
638
639
640
641

bool SystemTools::MakeDirectory(const char* path)
{
  if(!path)
    {
    return false;
    }
Kitware Robot's avatar
Kitware Robot committed
642
643
644
645
646
  return SystemTools::MakeDirectory(kwsys_stl::string(path));
}

bool SystemTools::MakeDirectory(const kwsys_stl::string& path)
{
Kitware Robot's avatar
Kitware Robot committed
647
648
  if(SystemTools::FileExists(path))
    {
Kitware Robot's avatar
Kitware Robot committed
649
    return SystemTools::FileIsDirectory(path);
Kitware Robot's avatar
Kitware Robot committed
650
    }
Kitware Robot's avatar
Kitware Robot committed
651
  if(path.empty())
Kitware Robot's avatar
Kitware Robot committed
652
653
654
    {
    return false;
    }
Kitware Robot's avatar
Kitware Robot committed
655
  kwsys_stl::string dir = path;
Kitware Robot's avatar
Kitware Robot committed
656
657
  SystemTools::ConvertToUnixSlashes(dir);

Kitware Robot's avatar
Kitware Robot committed
658
  kwsys_stl::string::size_type pos = 0;
Kitware Robot's avatar
Kitware Robot committed
659
660
661
662
  kwsys_stl::string topdir;
  while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
    {
    topdir = dir.substr(0, pos);
Kitware Robot's avatar
Kitware Robot committed
663
    Mkdir(topdir);
Kitware Robot's avatar
Kitware Robot committed
664
665
    pos++;
    }
Kitware Robot's avatar
Kitware Robot committed
666
  topdir = dir;
Kitware Robot's avatar
Kitware Robot committed
667
  if(Mkdir(topdir) != 0)
Kitware Robot's avatar
Kitware Robot committed
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
    {
    // 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.
void SystemTools::ReplaceString(kwsys_stl::string& source,
                                   const char* replace,
                                   const char* with)
{
  const char *src = source.c_str();
  char *searchPos = const_cast<char *>(strstr(src,replace));

  // get out quick if string is not found
  if (!searchPos)
    {
    return;
    }

  // perform replacements until done
  size_t replaceSize = strlen(replace);
  // do while hangs if replaceSize is 0
  if(replaceSize == 0)
    {
    return;
    }
  char *orig = strdup(src);
  char *currentPos = orig;
  searchPos = searchPos - src + orig;

  // initialize the result
  source.erase(source.begin(),source.end());
  do
    {
    *searchPos = '\0';
    source += currentPos;
    currentPos = searchPos + replaceSize;
    // replace
    source += with;
    searchPos = strstr(currentPos,replace);
    }
  while (searchPos);

  // copy any trailing text
  source += currentPos;
  free(orig);
}

#if defined(KEY_WOW64_32KEY) && defined(KEY_WOW64_64KEY)
# define KWSYS_ST_KEY_WOW64_32KEY KEY_WOW64_32KEY
# define KWSYS_ST_KEY_WOW64_64KEY KEY_WOW64_64KEY
#else
# define KWSYS_ST_KEY_WOW64_32KEY 0x0200
# define KWSYS_ST_KEY_WOW64_64KEY 0x0100
#endif

#if defined(_WIN32) && !defined(__CYGWIN__)
Kitware Robot's avatar
Kitware Robot committed
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
static bool SystemToolsParseRegistryKey(const char* key,
                                        HKEY& primaryKey,
                                        kwsys_stl::string& second,
                                        kwsys_stl::string& valuename)
{
  kwsys_stl::string primary = key;

  size_t start = primary.find("\\");
  if (start == kwsys_stl::string::npos)
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
  if (valuenamepos != kwsys_stl::string::npos)
    {
    valuename = primary.substr(valuenamepos+1);
    }

  second = primary.substr(start+1, valuenamepos-start-1);
  primary = primary.substr(0, start);

  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;
    }

  return true;
}

Kitware Robot's avatar
Kitware Robot committed
785
786
787
788
static DWORD SystemToolsMakeRegistryMode(DWORD mode,
                                         SystemTools::KeyWOW64 view)
{
  // only add the modes when on a system that supports Wow64.
Kitware Robot's avatar
Kitware Robot committed
789
  static FARPROC wow64p = GetProcAddress(GetModuleHandleW(L"kernel32"),
Kitware Robot's avatar
Kitware Robot committed
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
                                         "IsWow64Process");
  if(wow64p == NULL)
    {
    return mode;
    }

  if(view == SystemTools::KeyWOW64_32)
    {
    return mode | KWSYS_ST_KEY_WOW64_32KEY;
    }
  else if(view == SystemTools::KeyWOW64_64)
    {
    return mode | KWSYS_ST_KEY_WOW64_64KEY;
    }
  return mode;
}
#endif

Kitware Robot's avatar
Kitware Robot committed
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
#if defined(_WIN32) && !defined(__CYGWIN__)
bool
SystemTools::GetRegistrySubKeys(const char *key,
                                kwsys_stl::vector<kwsys_stl::string>& subkeys,
                                KeyWOW64 view)
{
  HKEY primaryKey = HKEY_CURRENT_USER;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
  if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
    {
    return false;
    }

  HKEY hKey;
Kitware Robot's avatar
Kitware Robot committed
823
824
  if(RegOpenKeyExW(primaryKey,
                  Encoding::ToWide(second).c_str(),
Kitware Robot's avatar
Kitware Robot committed
825
826
827
828
829
830
831
832
                  0,
                  SystemToolsMakeRegistryMode(KEY_READ, view),
                  &hKey) != ERROR_SUCCESS)
    {
    return false;
    }
  else
    {
Kitware Robot's avatar
Kitware Robot committed
833
    wchar_t name[1024];
Kitware Robot's avatar
Kitware Robot committed
834
835
836
    DWORD dwNameSize = sizeof(name)/sizeof(name[0]);

    DWORD i = 0;
Kitware Robot's avatar
Kitware Robot committed
837
    while (RegEnumKeyW(hKey, i, name, dwNameSize) == ERROR_SUCCESS)
Kitware Robot's avatar
Kitware Robot committed
838
      {
Kitware Robot's avatar
Kitware Robot committed
839
      subkeys.push_back(Encoding::ToNarrow(name));
Kitware Robot's avatar
Kitware Robot committed
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
      ++i;
      }

    RegCloseKey(hKey);
    }

  return true;
}
#else
bool SystemTools::GetRegistrySubKeys(const char *,
                                     kwsys_stl::vector<kwsys_stl::string>&,
                                     KeyWOW64)
{
  return false;
}
#endif

Kitware Robot's avatar
Kitware Robot committed
857
858
859
860
861
862
863
864
865
866
867
868
// 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__)
bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value,
                                    KeyWOW64 view)
{
  bool valueset = false;
Kitware Robot's avatar
Kitware Robot committed
869
  HKEY primaryKey = HKEY_CURRENT_USER;
Kitware Robot's avatar
Kitware Robot committed
870
871
  kwsys_stl::string second;
  kwsys_stl::string valuename;
Kitware Robot's avatar
Kitware Robot committed
872
  if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
Kitware Robot's avatar
Kitware Robot committed
873
874
875
876
877
    {
    return false;
    }

  HKEY hKey;
Kitware Robot's avatar
Kitware Robot committed
878
879
  if(RegOpenKeyExW(primaryKey,
                  Encoding::ToWide(second).c_str(),
Kitware Robot's avatar
Kitware Robot committed
880
881
882
883
884
885
886
887
888
889
                  0,
                  SystemToolsMakeRegistryMode(KEY_READ, view),
                  &hKey) != ERROR_SUCCESS)
    {
    return false;
    }
  else
    {
    DWORD dwType, dwSize;
    dwSize = 1023;
Kitware Robot's avatar
Kitware Robot committed
890
891
892
    wchar_t data[1024];
    if(RegQueryValueExW(hKey,
                       Encoding::ToWide(valuename).c_str(),
Kitware Robot's avatar
Kitware Robot committed
893
894
895
896
897
898
899
                       NULL,
                       &dwType,
                       (BYTE *)data,
                       &dwSize) == ERROR_SUCCESS)
      {
      if (dwType == REG_SZ)
        {
Kitware Robot's avatar
Kitware Robot committed
900
        value = Encoding::ToNarrow(data);
Kitware Robot's avatar
Kitware Robot committed
901
902
903
904
        valueset = true;
        }
      else if (dwType == REG_EXPAND_SZ)
        {
Kitware Robot's avatar
Kitware Robot committed
905
        wchar_t expanded[1024];
Kitware Robot's avatar
Kitware Robot committed
906
        DWORD dwExpandedSize = sizeof(expanded)/sizeof(expanded[0]);
Kitware Robot's avatar
Kitware Robot committed
907
908
        if(ExpandEnvironmentStringsW(data, expanded,
            dwExpandedSize))
Kitware Robot's avatar
Kitware Robot committed
909
          {
Kitware Robot's avatar
Kitware Robot committed
910
          value = Encoding::ToNarrow(expanded);
Kitware Robot's avatar
Kitware Robot committed
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
936
937
938
939
940
          valueset = true;
          }
        }
      }

    RegCloseKey(hKey);
    }

  return valueset;
}
#else
bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &,
                                    KeyWOW64)
{
  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,
                                     KeyWOW64 view)
{
Kitware Robot's avatar
Kitware Robot committed
941
  HKEY primaryKey = HKEY_CURRENT_USER;
Kitware Robot's avatar
Kitware Robot committed
942
943
  kwsys_stl::string second;
  kwsys_stl::string valuename;
Kitware Robot's avatar
Kitware Robot committed
944
  if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
Kitware Robot's avatar
Kitware Robot committed
945
946
947
948
949
950
    {
    return false;
    }

  HKEY hKey;
  DWORD dwDummy;
Kitware Robot's avatar
Kitware Robot committed
951
952
953
  wchar_t lpClass[] = L"";
  if(RegCreateKeyExW(primaryKey,
                    Encoding::ToWide(second).c_str(),
Kitware Robot's avatar
Kitware Robot committed
954
955
956
957
958
959
960
961
962
963
964
                    0,
                    lpClass,
                    REG_OPTION_NON_VOLATILE,
                    SystemToolsMakeRegistryMode(KEY_WRITE, view),
                    NULL,
                    &hKey,
                    &dwDummy) != ERROR_SUCCESS)
    {
    return false;
    }

Kitware Robot's avatar
Kitware Robot committed
965
966
967
  std::wstring wvalue = Encoding::ToWide(value);
  if(RegSetValueExW(hKey,
                   Encoding::ToWide(valuename).c_str(),
Kitware Robot's avatar
Kitware Robot committed
968
969
                   0,
                   REG_SZ,
Kitware Robot's avatar
Kitware Robot committed
970
971
                   (CONST BYTE *)wvalue.c_str(),
                   (DWORD)(sizeof(wchar_t) * (wvalue.size() + 1))) == ERROR_SUCCESS)
Kitware Robot's avatar
Kitware Robot committed
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
    {
    return true;
    }
  return false;
}
#else
bool SystemTools::WriteRegistryValue(const char *, const char *, KeyWOW64)
{
  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, KeyWOW64 view)
{
Kitware Robot's avatar
Kitware Robot committed
994
  HKEY primaryKey = HKEY_CURRENT_USER;
Kitware Robot's avatar
Kitware Robot committed
995
996
  kwsys_stl::string second;
  kwsys_stl::string valuename;
Kitware Robot's avatar
Kitware Robot committed
997
  if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
Kitware Robot's avatar
Kitware Robot committed
998
999
1000
1001
1002
    {
    return false;
    }

  HKEY hKey;
Kitware Robot's avatar
Kitware Robot committed
1003
1004
  if(RegOpenKeyExW(primaryKey,
                  Encoding::ToWide(second).c_str(),
Kitware Robot's avatar
Kitware Robot committed
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
                  0,
                  SystemToolsMakeRegistryMode(KEY_WRITE, view),
                  &hKey) != ERROR_SUCCESS)
    {
    return false;
    }
  else
    {
    if(RegDeleteValue(hKey,
                      (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
      {
      RegCloseKey(hKey);
      return true;
      }
    }
  return false;
}
#else
bool SystemTools::DeleteRegistryValue(const char *, KeyWOW64)
{
  return false;
}
#endif

Kitware Robot's avatar
Kitware Robot committed
1029
bool SystemTools::SameFile(const kwsys_stl::string& file1, const kwsys_stl::string& file2)
Kitware Robot's avatar
Kitware Robot committed
1030
1031
1032
1033
{
#ifdef _WIN32
  HANDLE hFile1, hFile2;

Kitware Robot's avatar
Kitware Robot committed
1034
  hFile1 = CreateFileW( Encoding::ToWide(file1).c_str(),
Kitware Robot's avatar
Kitware Robot committed
1035
1036
1037
1038
1039
1040
1041
                      GENERIC_READ,
                      FILE_SHARE_READ ,
                      NULL,
                      OPEN_EXISTING,
                      FILE_FLAG_BACKUP_SEMANTICS,
                      NULL
    );
Kitware Robot's avatar
Kitware Robot committed
1042
  hFile2 = CreateFileW( Encoding::ToWide(file2).c_str(),
Kitware Robot's avatar
Kitware Robot committed
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
                      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);
   return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
           fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
           fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
#else
  struct stat fileStat1, fileStat2;
Kitware Robot's avatar
Kitware Robot committed
1074
  if (stat(file1.c_str(), &fileStat1) == 0 && stat(file2.c_str(), &fileStat2) == 0)
Kitware Robot's avatar
Kitware Robot committed
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
    {
    // 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
}

//----------------------------------------------------------------------------
bool SystemTools::FileExists(const char* filename)
{
Kitware Robot's avatar
Kitware Robot committed
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
  if(!filename)
    {
    return false;
    }
  return SystemTools::FileExists(kwsys_stl::string(filename));
}

//----------------------------------------------------------------------------
bool SystemTools::FileExists(const kwsys_stl::string& filename)
{
  if(filename.empty())
Kitware Robot's avatar
Kitware Robot committed
1104
1105
1106
1107
1108
1109
    {
    return false;
    }
#if defined(__CYGWIN__)
  // Convert filename to native windows path if possible.
  char winpath[MAX_PATH];
Kitware Robot's avatar
Kitware Robot committed
1110
  if(SystemTools::PathCygwinToWin32(filename.c_str(), winpath))
Kitware Robot's avatar
Kitware Robot committed
1111
    {
Kitware Robot's avatar
Kitware Robot committed
1112
    return (GetFileAttributesA(winpath) != INVALID_FILE_ATTRIBUTES);
Kitware Robot's avatar
Kitware Robot committed
1113
    }
Kitware Robot's avatar
Kitware Robot committed
1114
  return access(filename.c_str(), R_OK) == 0;
Kitware Robot's avatar
Kitware Robot committed
1115
#elif defined(_WIN32)
Kitware Robot's avatar
Kitware Robot committed
1116
1117
  return (GetFileAttributesW(
            SystemTools::ConvertToWindowsExtendedPath(filename).c_str())
Kitware Robot's avatar
Kitware Robot committed
1118
          != INVALID_FILE_ATTRIBUTES);
Kitware Robot's avatar
Kitware Robot committed
1119
#else
Kitware Robot's avatar
Kitware Robot committed
1120
  return access(filename.c_str(), R_OK) == 0;
Kitware Robot's avatar
Kitware Robot committed
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
#endif
}

//----------------------------------------------------------------------------
bool SystemTools::FileExists(const char* filename, bool isFile)
{
  if(SystemTools::FileExists(filename))
    {
    // If isFile is set return not FileIsDirectory,
    // so this will only be true if it is a file
    return !isFile || !SystemTools::FileIsDirectory(filename);
    }
  return false;
}

Kitware Robot's avatar
Kitware Robot committed
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
//----------------------------------------------------------------------------
bool SystemTools::FileExists(const kwsys_stl::string& filename, bool isFile)
{
  if(SystemTools::FileExists(filename))
    {
    // If isFile is set return not FileIsDirectory,
    // so this will only be true if it is a file
    return !isFile || !SystemTools::FileIsDirectory(filename);
    }
  return false;
}

Kitware Robot's avatar
Kitware Robot committed
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
//----------------------------------------------------------------------------
#ifdef __CYGWIN__
bool SystemTools::PathCygwinToWin32(const char *path, char *win32_path)
{
  SystemToolsTranslationMap::iterator i =
    SystemTools::Cyg2Win32Map->find(path);

  if (i != SystemTools::Cyg2Win32Map->end())
    {
    strncpy(win32_path, i->second.c_str(), MAX_PATH);
    }
  else
    {
Kitware Robot's avatar
Kitware Robot committed
1161
1162
1163
1164
    if(cygwin_conv_path(CCP_POSIX_TO_WIN_A, path, win32_path, MAX_PATH) != 0)
      {
      win32_path[0] = 0;
      }
Kitware Robot's avatar
Kitware Robot committed
1165
1166
1167
1168
1169
1170
1171
    SystemToolsTranslationMap::value_type entry(path, win32_path);
    SystemTools::Cyg2Win32Map->insert(entry);
    }
  return win32_path[0] != 0;
}
#endif

Kitware Robot's avatar
Kitware Robot committed
1172
bool SystemTools::Touch(const kwsys_stl::string& filename, bool create)
Kitware Robot's avatar
Kitware Robot committed
1173
1174
1175
{
  if(create && !SystemTools::FileExists(filename))
    {
Kitware Robot's avatar
Kitware Robot committed
1176
    FILE* file = Fopen(filename, "a+b");
Kitware Robot's avatar
Kitware Robot committed
1177
1178
1179
1180
1181
1182
1183
    if(file)
      {
      fclose(file);
      return true;
      }
    return false;
    }
Kitware Robot's avatar
Kitware Robot committed
1184
#if defined(_WIN32) && !defined(__CYGWIN__)
Kitware Robot's avatar
Kitware Robot committed
1185
1186
1187
1188
1189
  HANDLE h = CreateFileW(
    SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
    FILE_WRITE_ATTRIBUTES,
    FILE_SHARE_WRITE, 0, OPEN_EXISTING,
    FILE_FLAG_BACKUP_SEMANTICS, 0);
Kitware Robot's avatar
Kitware Robot committed
1190
1191
1192
1193
1194
1195
1196
  if(!h)
    {
    return false;
    }
  FILETIME mtime;
  GetSystemTimeAsFileTime(&mtime);
  if(!SetFileTime(h, 0, 0, &mtime))
Kitware Robot's avatar
Kitware Robot committed
1197
    {
Kitware Robot's avatar
Kitware Robot committed
1198
    CloseHandle(h);
Kitware Robot's avatar
Kitware Robot committed
1199
1200
    return false;
    }
Kitware Robot's avatar
Kitware Robot committed
1201
1202
1203
  CloseHandle(h);
#elif KWSYS_CXX_HAS_UTIMENSAT
  struct timespec times[2] = {{0,UTIME_OMIT},{0,UTIME_NOW}};
Kitware Robot's avatar
Kitware Robot committed
1204
  if(utimensat(AT_FDCWD, filename.c_str(), times, 0) < 0)
Kitware Robot's avatar
Kitware Robot committed
1205
1206
1207
    {
    return false;
    }
Kitware Robot's avatar
Kitware Robot committed
1208
1209
#else
  struct stat st;
Kitware Robot's avatar
Kitware Robot committed
1210
  if(stat(filename.c_str(), &st) < 0)
Kitware Robot's avatar
Kitware Robot committed
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
    {
    return false;
    }
  struct timeval mtime;
  gettimeofday(&mtime, 0);
# if KWSYS_CXX_HAS_UTIMES
  struct timeval times[2] =
    {
#  if KWSYS_STAT_HAS_ST_MTIM
      {st.st_atim.tv_sec, st.st_atim.tv_nsec/1000}, /* tv_sec, tv_usec */
#  else
      {st.st_atime, 0},
#  endif
      mtime
    };
Kitware Robot's avatar
Kitware Robot committed
1226
  if(utimes(filename.c_str(), times) < 0)
Kitware Robot's avatar
Kitware Robot committed
1227
1228
1229
1230
1231
    {
    return false;
    }
# else
  struct utimbuf times = {st.st_atime, mtime.tv_sec};
Kitware Robot's avatar
Kitware Robot committed
1232
  if(utime(filename.c_str(), &times) < 0)
Kitware Robot's avatar
Kitware Robot committed
1233
1234
1235
1236
1237
    {
    return false;
    }
# endif
#endif
Kitware Robot's avatar
Kitware Robot committed
1238
1239
1240
  return true;
}

Kitware Robot's avatar
Kitware Robot committed
1241
1242
bool SystemTools::FileTimeCompare(const kwsys_stl::string& f1,
                                  const kwsys_stl::string& f2,
Kitware Robot's avatar
Kitware Robot committed
1243
1244
1245
1246
1247
1248
1249
                                  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;
Kitware Robot's avatar
Kitware Robot committed
1250
  if(stat(f1.c_str(), &s1) != 0)
Kitware Robot's avatar
Kitware Robot committed
1251
1252
1253
1254
    {
    return false;
    }
  struct stat s2;
Kitware Robot's avatar
Kitware Robot committed
1255
  if(stat(f2.c_str(), &s2) != 0)
Kitware Robot's avatar
Kitware Robot committed
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
    {
    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.  Get the modification time from extended file attributes.
  WIN32_FILE_ATTRIBUTE_DATA f1d;
  WIN32_FILE_ATTRIBUTE_DATA f2d;
Kitware Robot's avatar
Kitware Robot committed
1292
1293
1294
  if(!GetFileAttributesExW(
       SystemTools::ConvertToWindowsExtendedPath(f1).c_str(),
       GetFileExInfoStandard, &f1d))
Kitware Robot's avatar
Kitware Robot committed
1295
1296
1297
    {
    return false;
    }
Kitware Robot's avatar
Kitware Robot committed
1298
1299
1300
  if(!GetFileAttributesExW(
       SystemTools::ConvertToWindowsExtendedPath(f2).c_str(),
       GetFileExInfoStandard, &f2d))
Kitware Robot's avatar
Kitware Robot committed
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
    {
    return false;
    }

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


// Return a capitalized string (i.e the first letter is uppercased, all other
// are lowercased)
kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
{
  kwsys_stl::string n;
Kitware Robot's avatar
Kitware Robot committed
1317
  if(s.empty())
Kitware Robot's avatar
Kitware Robot committed
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
    {
    return n;
    }
  n.resize(s.size());
  n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
  for (size_t i = 1; i < s.size(); i++)
    {
    n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
    }
  return n;
}

// 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 defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
    // MS has an assert that will fail if s[i] < 0; setting
    // LC_CTYPE using setlocale() does *not* help. Painful.
    if ((int)s[i] >= 0 && isalpha(s[i]) &&
        (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
#else
    if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
#endif
      {
      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 defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
    // MS has an assert that will fail if s[i] < 0; setting
    // LC_CTYPE using setlocale() does *not* help. Painful.
    if ((int)s[i] >= 0 && isalpha(s[i]) &&
        (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
#else
    if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
#endif
      {
      n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
      }
    }
  return n;
}

// only works for words with at least two letters
kwsys_stl::string SystemTools::AddSpaceBetweenCapitalizedWords(
  const kwsys_stl::string& s)
{
  kwsys_stl::string n;
Kitware Robot's avatar
Kitware Robot committed
1377
  if (!s.empty())
Kitware Robot's avatar
Kitware Robot committed
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
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
1432
1433
1434
1435
1436
1437
1438
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
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
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
    {
    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 += ' ';
        }
      n += s[i];
      }
    }
  return n;
}

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;
}

// Return a lower case string
kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
{
  kwsys_stl::string n;
  n.resize(s.size());
  for (size_t i = 0; i < s.size(); i++)
    {
    n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
    }
  return n;
}

// Return a lower case string
kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
{
  kwsys_stl::string n;
  n.resize(s.size());
  for (size_t i = 0; i < s.size(); i++)
    {
    n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
    }
  return n;
}

// 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 <= 'F'))
      {
      *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;
}

// Returns if string starts with another string
bool SystemTools::StringStartsWith(const char* str1, const char* str2)
{
  if (!str1 || !str2)
    {
    return false;
    }
  size_t len1 = strlen(str1), len2 = strlen(str2);
  return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
}

Kitware Robot's avatar
Kitware Robot committed
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
// Returns if string starts with another string
bool SystemTools::StringStartsWith(const kwsys_stl::string& str1, const char* str2)
{
  if (!str2)
    {
    return false;
    }
  size_t len1 = str1.size(), len2 = strlen(str2);
  return len1 >= len2 && !strncmp(str1.c_str(), str2, len2) ? true : false;
}

Kitware Robot's avatar
Kitware Robot committed
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
// Returns if string ends with another string
bool SystemTools::StringEndsWith(const char* str1, const char* str2)
{
  if (!str1 || !str2)
    {
    return false;
    }
  size_t len1 = strlen(str1), len2 = strlen(str2);
  return len1 >= len2 &&  !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
}

Kitware Robot's avatar
Kitware Robot committed
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
// Returns if string ends with another string
bool SystemTools::StringEndsWith(const kwsys_stl::string& str1, const char* str2)
{
  if (!str2)
    {
    return false;
    }
  size_t len1 = str1.size(), len2 = strlen(str2);
  return len1 >= len2 &&  !strncmp(str1.c_str() + (len1 - len2), str2, len2) ? true : false;
}

Kitware Robot's avatar
Kitware Robot committed
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
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
// 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;
}

// Return a cropped string
kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s,
                                          size_t max_len)
{
  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;
}

//----------------------------------------------------------------------------
Kitware Robot's avatar
Kitware Robot committed
1668
kwsys_stl::vector<kwsys::String> SystemTools::SplitString(const kwsys_stl::string& p, char sep, bool isPath)
Kitware Robot's avatar
Kitware Robot committed
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
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
{
  kwsys_stl::string path = p;
  kwsys_stl::vector<kwsys::String> paths;
  if(path.empty())
    {
    return paths;
    }
  if(isPath && path[0] == '/')
    {
    path.erase(path.begin());
    paths.push_back("/");
    }
  kwsys_stl::string::size_type pos1 = 0;
  kwsys_stl::string::size_type pos2 = path.find(sep, pos1+1);
  while(pos2 != kwsys_stl::string::npos)
    {
    paths.push_back(path.substr(pos1, pos2-pos1));
    pos1 = pos2+1;
    pos2 = path.find(sep, pos1+1);
    }
  paths.push_back(path.substr(pos1, pos2-pos1));

  return paths;
}

//----------------------------------------------------------------------------
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.

  size_t 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 static_cast<int>(length);
}

kwsys_stl::string SystemTools::EscapeChars(
  const char *str,
  const char *chars_to_escape,
  char escape_char)
{
  kwsys_stl::string n;
  if (str)
    {
Kitware Robot's avatar
Kitware Robot committed
1771
    if (!chars_to_escape || !*chars_to_escape)
Kitware Robot's avatar
Kitware Robot committed
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
      {
      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;
}

#ifdef __VMS
static void ConvertVMSToUnix(kwsys_stl::string& path)
{
  kwsys_stl::string::size_type rootEnd = path.find(":[");
  kwsys_stl::string::size_type pathEnd = path.find("]");
  if(rootEnd != path.npos)
    {
    kwsys_stl::string root = path.substr(0, rootEnd);
    kwsys_stl::string pathPart = path.substr(rootEnd+2, pathEnd - rootEnd-2);
    const char* pathCString = pathPart.c_str();
    const char* pos0 = pathCString;
    for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
      {
      if ( *pos0 == '.' )
        {
        pathPart[pos] = '/';
        }
      pos0 ++;
      }
    path = "/"+ root + "/" + pathPart;
    }
}
#endif

// convert windows slashes to unix slashes
void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
{
  const char* pathCString = path.c_str();
  bool hasDoubleSlash = false;
#ifdef __VMS
  ConvertVMSToUnix(path);
#else
  const char* pos0 = pathCString;
  const char* pos1 = pathCString+1;
  for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
    {
    // make sure we don't convert an escaped space to a unix slash
    if ( *pos0 == '\\' && *pos1 != ' ' )
      {
      path[pos] = '/';
      }

    // Also, reuse the loop to check for slash followed by another slash
    if (*pos1 == '/' && *(pos1+1) == '/' && !hasDoubleSlash)
      {
#ifdef _WIN32
      // 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;
        }
#else
      hasDoubleSlash = true;
#endif
      }

    pos0 ++;
    pos1 ++;
    }

  if ( hasDoubleSlash )
    {
    SystemTools::ReplaceString(path, "//", "/");
    }
#endif
  // remove any trailing slash
  if(!path.empty())
    {
    // if there is a tilda ~ then replace it with HOME
    pathCString = path.c_str();
    if(pathCString[0] == '~' && (pathCString[1] == '/' || pathCString[1] == '\0'))
      {
      const char* homeEnv = SystemTools::GetEnv("HOME");
      if (homeEnv)
        {
        path.replace(0,1,homeEnv);
        }
      }
#ifdef HAVE_GETPWNAM
    else if(pathCString[0] == '~')
      {
      kwsys_stl::string::size_type idx = path.find_first_of("/\0");
      kwsys_stl::string user = path.substr(1, idx-1);
      passwd* pw = getpwnam(user.c_str());
      if(pw)
        {
        path.replace(0, idx, pw->pw_dir);
        }
      }
#endif
    // remove trailing slash if the path is more than
    // a single /
    pathCString = path.c_str();
Kitware Robot's avatar
Kitware Robot committed
1892
1893
    size_t size = path.size();
    if(size > 1 && *path.rbegin() == '/')
Kitware Robot's avatar
Kitware Robot committed
1894
1895
      {
      // if it is c:/ then do not remove the trailing slash
Kitware Robot's avatar
Kitware Robot committed
1896
      if(!((size == 3 && pathCString[1] == ':')))
Kitware Robot's avatar
Kitware Robot committed
1897
        {
Kitware Robot's avatar
Kitware Robot committed
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
        path.resize(size - 1);
        }
      }
    }
}

#ifdef _WIN32
// Convert local paths to UNC style paths
kwsys_stl::wstring
SystemTools::ConvertToWindowsExtendedPath(const kwsys_stl::string &source)
{
  kwsys_stl::wstring wsource = Encoding::ToWide(source);

  // Resolve any relative paths
  DWORD wfull_len;

  /* The +3 is a workaround for a bug in some versions of GetFullPathNameW that
   * won't return a large enough buffer size if the input is too small */
  wfull_len = GetFullPathNameW(wsource.c_str(), 0, NULL, NULL) + 3;
  kwsys_stl::vector<wchar_t> wfull(wfull_len);
  GetFullPathNameW(wsource.c_str(), wfull_len, &wfull[0], NULL);

  /* This should get the correct size without any extra padding from the
   * previous size workaround. */
  wfull_len = static_cast<DWORD>(wcslen(&wfull[0]));

  if(wfull_len >= 2 && isalpha(wfull[0]) && wfull[1] == L':')
    { /* C:\Foo\bar\FooBar.txt */
    return L"\\\\?\\" + kwsys_stl::wstring(&wfull[0]);
    }
  else if(wfull_len >= 2 && wfull[0] == L'\\' && wfull[1] == L'\\')
    { /* Starts with \\ */
    if(wfull_len >= 4 && wfull[2] == L'?' && wfull[3] == L'\\')
      { /* Starts with \\?\ */
      if(wfull_len >= 8 && wfull[4] == L'U' && wfull[5] == L'N' &&
                           wfull[6] == L'C' && wfull[7] == L'\\')
        { /* \\?\UNC\Foo\bar\FooBar.txt */
        return kwsys_stl::wstring(&wfull[0]);
Kitware Robot's avatar
Kitware Robot committed
1936
        }
Kitware Robot's avatar
Kitware Robot committed
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
      else if(wfull_len >= 6 && isalpha(wfull[4]) && wfull[5] == L':')
        { /* \\?\C:\Foo\bar\FooBar.txt */
        return kwsys_stl::wstring(&wfull[0]);
        }
      else if(wfull_len >= 5)
        { /* \\?\Foo\bar\FooBar.txt */
        return L"\\\\?\\UNC\\" + kwsys_stl::wstring(&wfull[4]);
        }
      }
    else if(wfull_len >= 4 && wfull[2] == L'.' && wfull[3] == L'\\')
      { /* Starts with \\.\ a device name */
      if(wfull_len >= 6 && isalpha(wfull[4]) && wfull[5] == L':')
        { /* \\.\C:\Foo\bar\FooBar.txt */
        return L"\\\\?\\" + kwsys_stl::wstring(&wfull[4]);
        }
      else if(wfull_len >= 5)
        { /* \\.\Foo\bar\ Device name is left unchanged */
        return kwsys_stl::wstring(&wfull[0]);
        }
      }
    else if(wfull_len >= 3)
      { /* \\Foo\bar\FooBar.txt */
      return L"\\\\?\\UNC\\" + kwsys_stl::wstring(&wfull[2]);
Kitware Robot's avatar
Kitware Robot committed
1960
1961
      }
    }
Kitware Robot's avatar
Kitware Robot committed
1962
1963
1964
1965

  // If this case has been reached, then the path is invalid.  Leave it
  // unchanged
  return Encoding::ToWide(source);
Kitware Robot's avatar
Kitware Robot committed
1966
}
Kitware Robot's avatar
Kitware Robot committed
1967
#endif
Kitware Robot's avatar
Kitware Robot committed
1968
1969

// change // to /, and escape any spaces in the path
Kitware Robot's avatar
Kitware Robot committed
1970
kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const kwsys_stl::string& path)
Kitware Robot's avatar
Kitware Robot committed
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
{
  kwsys_stl::string ret = path;

  // remove // except at the beginning might be a cygwin drive
  kwsys_stl::string::size_type pos=1;
  while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
    {
    ret.erase(pos, 1);
    }
  // escape spaces and () in the path
  if(ret.find_first_of(" ") != kwsys_stl::string::npos)
    {
    kwsys_stl::string result = "";
    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;
}

Kitware Robot's avatar
Kitware Robot committed
2000
kwsys_stl::string SystemTools::ConvertToOutputPath(const kwsys_stl::string& path)
Kitware Robot's avatar
Kitware Robot committed
2001
2002
2003
2004
2005
2006
2007
2008
2009
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  return SystemTools::ConvertToWindowsOutputPath(path);
#else
  return SystemTools::ConvertToUnixOutputPath(path);
#endif
}

// remove double slashes not at the start
Kitware Robot's avatar
Kitware Robot committed
2010
kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const kwsys_stl::string& path)
Kitware Robot's avatar
Kitware Robot committed
2011
2012
2013
{
  kwsys_stl::string ret;
  // make it big enough for all of path and double quotes
Kitware Robot's avatar
Kitware Robot committed
2014
  ret.reserve(path.size()+3);
Kitware Robot's avatar
Kitware Robot committed
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
  // put path into the string
  ret = path;
  kwsys_stl::string::size_type pos = 0;
  // first convert all of the slashes
  while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
    {
    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;
      }
    }
  while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
    {
    ret.erase(pos, 1);
    }
  // now double quote the path if it has spaces in it
  // and is not already double quoted
  if(ret.find(' ') != kwsys_stl::string::npos
     && ret[0] != '\"')
    {
    ret.insert(static_cast<kwsys_stl::string::size_type>(0),
               static_cast<kwsys_stl::string::size_type>(1), '\"');
    ret.append(1, '\"');
    }
  return ret;
}

Kitware Robot's avatar
Kitware Robot committed
2057
2058
bool SystemTools::CopyFileIfDifferent(const kwsys_stl::string& source,
                                      const kwsys_stl::string& destination)
Kitware Robot's avatar
Kitware Robot committed
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
{
  // special check for a destination that is a directory
  // FilesDiffer does not handle file to directory compare
  if(SystemTools::FileIsDirectory(destination))
    {
    kwsys_stl::string new_destination = destination;
    SystemTools::ConvertToUnixSlashes(new_destination);
    new_destination += '/';
    kwsys_stl::string source_name = source;
    new_destination += SystemTools::GetFilenameName(source_name);
Kitware Robot's avatar
Kitware Robot committed
2069
    if(SystemTools::FilesDiffer(source, new_destination))
Kitware Robot's avatar
Kitware Robot committed
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
      {
      return SystemTools::CopyFileAlways(source, destination);
      }
    else
      {
      // the files are the same so the copy is done return
      // true
      return true;
      }
    }
  // source and destination are files so do a copy if they
  // are different
  if(SystemTools::FilesDiffer(source, destination))
    {
    return SystemTools::CopyFileAlways(source, destination);
    }
  // at this point the files must be the same so return true
  return true;
}

#define KWSYS_ST_BUFFER 4096

Kitware Robot's avatar
Kitware Robot committed
2092
2093
bool SystemTools::FilesDiffer(const kwsys_stl::string& source,
                              const kwsys_stl::string& destination)