SystemTools.cxx 104 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>
58
#include <pwd.h>
Andy Cedilnik's avatar
Andy Cedilnik committed
59
#include <termios.h>
60
#include <signal.h>    /* sigprocmask */
61 62
#endif

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

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
// 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
89

90
#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
91
#include <io.h>
92 93
#include <direct.h>
#define _unlink unlink
94 95 96 97 98 99 100 101 102 103
#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
104 105 106 107 108 109 110
#if defined(__WATCOMC__)
#include <direct.h>
#define _mkdir mkdir
#define _rmdir rmdir
#define _getcwd getcwd
#define _chdir chdir
#endif
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
#if defined(__BEOS__) && !defined(__ZETA__)
#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

140
#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__)) 
141 142 143 144
inline int Mkdir(const char* dir)
{
  return _mkdir(dir);
}
145 146 147 148
inline int Rmdir(const char* dir)
{
  return _rmdir(dir);
}
149 150
inline const char* Getcwd(char* buf, unsigned int len)
{
151 152 153 154 155 156 157
  const char* ret = _getcwd(buf, len);
  if(!ret)
    {
    fprintf(stderr, "No current working directory.\n");
    abort();
    }
  return ret;
158 159 160 161 162 163 164 165 166
}
inline int Chdir(const char* dir)
{
  #if defined(__BORLANDC__)
  return chdir(dir);
  #else
  return _chdir(dir);
  #endif
}
167
inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
168 169 170 171 172
{
  char *ptemp;
  char fullpath[MAX_PATH];
  if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
    {
173 174
    resolved_path = fullpath;
    KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
175 176
    }
}
177 178 179 180 181 182 183 184
#else
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
inline int Mkdir(const char* dir)
{
  return mkdir(dir, 00777);
}
185 186 187 188
inline int Rmdir(const char* dir)
{
  return rmdir(dir);
}
189 190
inline const char* Getcwd(char* buf, unsigned int len)
{
191 192 193 194 195 196 197
  const char* ret = getcwd(buf, len);
  if(!ret)
    {
    fprintf(stderr, "No current working directory\n");
    abort();
    }
  return ret;
198
}
199

200 201 202 203
inline int Chdir(const char* dir)
{
  return chdir(dir);
}
204
inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
205
{
206
  char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
207 208 209

  realpath(path, resolved_name);
  resolved_path = resolved_name;
210
}
211 212
#endif

213 214 215 216 217 218 219 220 221 222 223 224
#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
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247

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

248 249 250 251 252
class SystemToolsTranslationMap : 
    public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
{
};

253

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
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)
Andy Cedilnik's avatar
Andy Cedilnik committed
270
    return static_cast<double>(t.tv_sec) + t.tv_usec*0.000001;
271
#else /* !GETTIMEOFDAY_NO_TZ */
Andy Cedilnik's avatar
Andy Cedilnik committed
272 273
  if (gettimeofday(&t, static_cast<struct timezone *>(NULL)) == 0)
    return static_cast<double>(t.tv_sec) + t.tv_usec*0.000001;
274 275 276 277 278 279
#endif /* !GETTIMEOFDAY_NO_TZ */
  }
#endif /* !HAVE_GETTIMEOFDAY */
  {
#if defined(HAVE_FTIME)
  struct TIMEB t;
280
  ::FTIME(&t);
Andy Cedilnik's avatar
Andy Cedilnik committed
281 282
  return static_cast<double>(t.time) +
    static_cast<double>(t.millitm) * static_cast<double>(0.001);
283 284 285
#else /* !HAVE_FTIME */
  time_t secs;
  time(&secs);
Andy Cedilnik's avatar
Andy Cedilnik committed
286
  return static_cast<double>(secs);
287 288 289 290 291
#endif /* !HAVE_FTIME */
  }
}

// adds the elements of the env variable path to the arg passed in
292
void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
293 294 295 296 297 298
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  const char* pathSep = ";";
#else
  const char* pathSep = ":";
#endif
299 300 301 302
  if(!env)
    {
    env = "PATH";
    }
303 304 305 306 307 308 309
  const char* cpathEnv = SystemTools::GetEnv(env);
  if ( !cpathEnv )
    {
    return;
    }

  kwsys_stl::string pathEnv = cpathEnv;
310 311

  // A hack to make the below algorithm work.
312 313 314 315
  if(pathEnv[pathEnv.length()-1] != ':')
    {
    pathEnv += pathSep;
    }
316
  kwsys_stl::string::size_type start =0;
317 318 319
  bool done = false;
  while(!done)
    {
320 321
    kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
    if(endpos != kwsys_stl::string::npos)
322
      {
323 324 325
      kwsys_stl::string convertedPath;
      Realpath(pathEnv.substr(start, endpos-start).c_str(), convertedPath);
      path.push_back(convertedPath);
326 327 328 329 330 331 332
      start = endpos+1;
      }
    else
      {
      done = true;
      }
    }
333
  for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
334 335 336 337 338 339
      i != path.end(); ++i)
    {
    SystemTools::ConvertToUnixSlashes(*i);
    }
}

Brad King's avatar
Brad King committed
340 341 342 343 344
const char* SystemTools::GetEnv(const char* key)
{
  return getenv(key);
}

345
bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
Brad King's avatar
Brad King committed
346 347 348 349 350 351 352 353 354 355 356 357
{
  const char* v = getenv(key);
  if(v)
    {
    result = v;
    return true;
    }
  else
    {
    return false;
    }
}
358 359 360 361 362 363 364 365 366 367 368 369 370

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


bool SystemTools::MakeDirectory(const char* path)
{
Bill Hoffman's avatar
Bill Hoffman committed
371 372 373 374
  if(!path)
    {
    return false;
    }
375 376
  if(SystemTools::FileExists(path))
    {
377
    return true;
378
    }
379
  kwsys_stl::string dir = path;
380 381 382 383 384 385
  if(dir.size() == 0)
    {
    return false;
    }
  SystemTools::ConvertToUnixSlashes(dir);

386 387
  kwsys_stl::string::size_type pos = dir.find(':');
  if(pos == kwsys_stl::string::npos)
388 389 390
    {
    pos = 0;
    }
391 392
  kwsys_stl::string topdir;
  while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    {
    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
412
    if( (errno != EEXIST)
413
#ifdef __BORLANDC__
414 415
        && (errno != EACCES)
#endif
416 417 418 419 420 421 422 423 424 425 426
      )
      {
      return false;
      }
    }
  return true;
}


// replace replace with with as many times as it shows up in source.
// write the result into source.
427
void SystemTools::ReplaceString(kwsys_stl::string& source,
428 429 430
                                   const char* replace,
                                   const char* with)
{
Ken Martin's avatar
Ken Martin committed
431
  const char *src = source.c_str();
Bill Lorensen's avatar
Bill Lorensen committed
432
  char *searchPos = const_cast<char *>(strstr(src,replace));
Ken Martin's avatar
Ken Martin committed
433
  
434
  // get out quick if string is not found
Ken Martin's avatar
Ken Martin committed
435
  if (!searchPos)
436 437 438
    {
    return;
    }
Ken Martin's avatar
Ken Martin committed
439 440 441 442 443 444 445 446

  // 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
447
  source.erase(source.begin(),source.end());
Ken Martin's avatar
Ken Martin committed
448
  do
449
    {
Ken Martin's avatar
Ken Martin committed
450 451 452 453
    *searchPos = '\0';
    source += currentPos;
    currentPos = searchPos + replaceSize;
    // replace
454
    source += with;
Ken Martin's avatar
Ken Martin committed
455
    searchPos = strstr(currentPos,replace);
456
    }
Ken Martin's avatar
Ken Martin committed
457 458 459 460 461
  while (searchPos);

  // copy any trailing text
  source += currentPos;
  free(orig);
462 463 464 465 466 467 468 469 470 471
}

// 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__)
472
bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value)
473 474
{

475 476 477
  kwsys_stl::string primary = key;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
478 479
 
  size_t start = primary.find("\\");
480
  if (start == kwsys_stl::string::npos)
481 482 483 484 485
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
486
  if (valuenamepos != kwsys_stl::string::npos)
487 488 489 490 491 492 493
    {
    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
494
  HKEY primaryKey = HKEY_CURRENT_USER;
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
  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;
540
        RegCloseKey(hKey);
541 542 543 544 545 546 547
        return true;
        }
      }
    }
  return false;
}
#else
548
bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &)
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
{
  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)
{
565 566 567
  kwsys_stl::string primary = key;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
568 569
 
  size_t start = primary.find("\\");
570
  if (start == kwsys_stl::string::npos)
571 572 573 574 575
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
576
  if (valuenamepos != kwsys_stl::string::npos)
577 578 579 580 581 582 583
    {
    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
584
  HKEY primaryKey = HKEY_CURRENT_USER;
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 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
  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)
{
649 650 651
  kwsys_stl::string primary = key;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
652 653
 
  size_t start = primary.find("\\");
654
  if (start == kwsys_stl::string::npos)
655 656 657 658 659
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
660
  if (valuenamepos != kwsys_stl::string::npos)
661 662 663 664 665 666 667
    {
    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
668
  HKEY primaryKey = HKEY_CURRENT_USER;
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
  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)
      {
704
      RegCloseKey(hKey);
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 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
      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);
757 758
   return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
           fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
           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)
{
782 783
#ifdef _MSC_VER
# define access _access
784
#endif
785 786
#ifndef R_OK
# define R_OK 04
787
#endif
788
  if ( access(filename, R_OK) != 0 )
789 790 791 792 793 794 795 796 797 798
    {
    return false;
    }
  else
    {
    return true;
    }
}


799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
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
846 847 848 849
  // Windows version.  Get the modification time from extended file attributes.
  WIN32_FILE_ATTRIBUTE_DATA f1d;
  WIN32_FILE_ATTRIBUTE_DATA f2d;
  if(!GetFileAttributesEx(f1, GetFileExInfoStandard, &f1d))
850 851 852
    {
    return false;
    }
853
  if(!GetFileAttributesEx(f2, GetFileExInfoStandard, &f2d))
854 855 856 857 858
    {
    return false;
    }

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


865 866
// Return a capitalized string (i.e the first letter is uppercased, all other
// are lowercased)
867
kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
868
{
869
  kwsys_stl::string n;
Bill Hoffman's avatar
Bill Hoffman committed
870 871 872 873
  if(s.size() == 0)
    {
    return n;
    }
874
  n.resize(s.size());
Bill Hoffman's avatar
Bill Hoffman committed
875
  n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
876 877
  for (size_t i = 1; i < s.size(); i++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
878
    n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
879 880 881 882
    }
  return n;
}

883 884 885 886 887 888
// 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++)
    {
889 890 891 892 893 894
#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
895
    if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
896
#endif        
897 898 899 900 901 902 903 904 905 906 907 908 909
      {
      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++)
    {
910 911 912 913 914 915
#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
916
    if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
917
#endif        
918 919 920 921 922 923
      {
      n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
      }
    }
  return n;
}
924

925
// only works for words with at least two letters
926 927 928 929 930 931 932 933 934 935 936 937 938 939
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
940
      n += s[i];
941 942 943 944 945
      }
    }
  return n;
}

946 947 948 949 950 951 952 953 954 955 956 957 958 959 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
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;
}

995
// Return a lower case string 
996
kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
997
{
998
  kwsys_stl::string n;
999 1000 1001
  n.resize(s.size());
  for (size_t i = 0; i < s.size(); i++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
1002
    n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
1003 1004 1005 1006 1007
    }
  return n;
}

// Return a lower case string 
1008
kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
1009
{
1010
  kwsys_stl::string n;
1011 1012 1013
  n.resize(s.size());
  for (size_t i = 0; i < s.size(); i++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
1014
    n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
1015 1016 1017 1018
    }
  return n;
}

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 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 1074
// 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)
    {
1075
    if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'F'))
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 1106 1107
      {
      *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;
}

1108
// Returns if string starts with another string
1109
bool SystemTools::StringStartsWith(const char* str1, const char* str2)
1110 1111 1112 1113 1114 1115
{
  if (!str1 || !str2)
    {
    return false;
    }
  size_t len1 = strlen(str1), len2 = strlen(str2);
1116
  return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
1117 1118 1119
}

// Returns if string ends with another string
1120
bool SystemTools::StringEndsWith(const char* str1, const char* str2)
1121 1122 1123 1124 1125 1126 1127 1128 1129
{
  if (!str1 || !str2)
    {
    return false;
    }
  size_t len1 = strlen(str1), len2 = strlen(str2);
  return len1 >= len2 &&  !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
}

1130 1131 1132 1133 1134 1135 1136 1137 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
// 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;
}

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

1198
//----------------------------------------------------------------------------
1199
kwsys_stl::vector<kwsys::String> SystemTools::SplitString(const char* p, char sep, bool isPath)
1200
{
1201 1202
  kwsys_stl::string path = p;
  kwsys_stl::vector<kwsys::String> paths;
1203 1204 1205 1206 1207
  if(isPath && path[0] == '/')
    {
    path.erase(path.begin());
    paths.push_back("/"); 
    }
1208 1209 1210
  kwsys_stl::string::size_type pos1 = 0;
  kwsys_stl::string::size_type pos2 = path.find(sep, pos1+1);
  while(pos2 != kwsys_stl::string::npos)
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
    {
    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;
}

1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
//----------------------------------------------------------------------------
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.

1234
  size_t length = strlen(format);
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 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
  
  // 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;
      }
    }
  
Andy Cedilnik's avatar
Andy Cedilnik committed
1287
  return static_cast<int>(length);
1288 1289
}

1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
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;
}

1325
// convert windows slashes to unix slashes 
1326
void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
1327
{
Andy Cedilnik's avatar
Andy Cedilnik committed
1328 1329 1330 1331 1332
  const char* pathCString = path.c_str();
  bool hasDoubleSlash = false;

  const char* pos0 = pathCString;
  const char* pos1 = pathCString+1;
1333
  for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
1334
    {
1335
    // make sure we don't convert an escaped space to a unix slash
Andy Cedilnik's avatar
Andy Cedilnik committed
1336
    if ( *pos0 == '\\' && *pos1 != ' ' )
1337
      {
Andy Cedilnik's avatar
Andy Cedilnik committed
1338
      path[pos] = '/';
1339
      }
1340

Andy Cedilnik's avatar
Andy Cedilnik committed
1341 1342 1343 1344
    // Also, reuse the loop to check for slash followed by another slash
    if ( !hasDoubleSlash && *pos1 &&
      *pos1 == '/' && *(pos1+1) == '/' )
      {
1345
#ifdef _WIN32
Andy Cedilnik's avatar
Andy Cedilnik committed
1346 1347 1348 1349 1350 1351
      // 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
1352
#else
Andy Cedilnik's avatar
Andy Cedilnik committed
1353
      hasDoubleSlash = true;
1354
#endif
Andy Cedilnik's avatar
Andy Cedilnik committed
1355
      }
1356

Andy Cedilnik's avatar
Andy Cedilnik committed
1357 1358 1359 1360 1361
    pos0 ++;
    pos1 ++;
    }

  if ( hasDoubleSlash )
1362 1363 1364 1365 1366
    {
    SystemTools::ReplaceString(path, "//", "/");
    }
  
  // remove any trailing slash
Andy Cedilnik's avatar
Andy Cedilnik committed
1367
  if(!path.empty())
1368
    {
Andy Cedilnik's avatar
Andy Cedilnik committed
1369
    // if there is a tilda ~ then replace it with HOME
1370
    pathCString = path.c_str();
1371
    if(pathCString[0] == '~' && (pathCString[1] == '/' || pathCString[1] == '\0'))
Andy Cedilnik's avatar
Andy Cedilnik committed
1372 1373 1374 1375 1376 1377 1378
      {
      const char* homeEnv = SystemTools::GetEnv("HOME");
      if (homeEnv)
        {
        path.replace(0,1,homeEnv);
        }
      }
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
#if !defined(_WIN32)
    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
1391 1392
    // remove trailing slash if the path is more than 
    // a single /
1393
    pathCString = path.c_str();
1394
    if(path.size() > 1 && *(pathCString+(path.size()-1)) == '/')
1395
      {
1396 1397 1398 1399 1400
      // if it is c:/ then do not remove the trailing slash
      if(!((path.size() == 3 && pathCString[1] == ':')))
        {
        path = path.substr(0, path.size()-1);
        }
1401 1402 1403 1404 1405
      }
    }
}

// change // to /, and escape any spaces in the path
1406
kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
1407
{
1408
  kwsys_stl::string ret = path;
1409 1410
  
  // remove // except at the beginning might be a cygwin drive
1411
  kwsys_stl::string::size_type pos=0;
1412
  while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
1413 1414 1415
    {
    ret.erase(pos, 1);
    }
1416
  // escape spaces and () in the path
1417
  if(ret.find_first_of(" ") != kwsys_stl::string::npos)
1418
    {
1419
    kwsys_stl::string result = "";
1420 1421 1422 1423
    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
1424
      if((*ch == ' ') && lastch != '\\')
1425
        {
1426
        result += '\\';
1427 1428 1429 1430 1431 1432 1433 1434 1435
        }
      result += *ch;
      lastch = *ch;
      }
    ret = result;
    }
  return ret;
}

1436
kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
1437 1438 1439 1440 1441 1442 1443 1444 1445
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  return SystemTools::ConvertToWindowsOutputPath(path);
#else
  return SystemTools::ConvertToUnixOutputPath(path);
#endif
}

// remove double slashes not at the start
1446
kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
1447
{  
1448 1449 1450 1451 1452
  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);
1453
  kwsys_stl::string::size_type pos = 0;
1454
  // first convert all of the slashes
1455
  while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
    {
    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;
      }
    }
1477
  while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
1478 1479 1480 1481 1482
    {
    ret.erase(pos, 1);
    }
  // now double quote the path if it has spaces in it
  // and is not already double quoted
1483
  if(ret.find(' ') != kwsys_stl::string::npos
1484 1485
     && ret[0] != '\"')
    {
Bill Hoffman's avatar
Bill Hoffman committed
1486 1487
    ret.insert(static_cast<kwsys_stl::string::size_type>(0),
               static_cast<kwsys_stl::string::size_type>(1), '\"');
1488
    ret.append(1, '\"');
1489 1490 1491 1492 1493
    }
  return ret;
}

bool SystemTools::CopyFileIfDifferent(const char* source,
1494
                                      const char* destination)
1495
{
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
  // 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);
    if(SystemTools::FilesDiffer(source, new_destination.c_str()))
      {
      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
1518 1519
  if(SystemTools::FilesDiffer(source, destination))
    {
1520
    return SystemTools::CopyFileAlways(source, destination);
1521
    }
1522
  // at this point the files must be the same so return true
1523
  return true;
1524 1525
}

1526 1527
#define KWSYS_ST_BUFFER 4096

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
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__)
1554 1555 1556 1557
  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));
1558
#else
1559 1560
  kwsys_ios::ifstream finSource(source);
  kwsys_ios::ifstream finDestination(destination);
1561 1562 1563 1564 1565 1566
#endif
  if(!finSource || !finDestination)
    {
    return true;
    }

1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
  // Compare the files a block at a time.
  char source_buf[KWSYS_ST_BUFFER];
  char dest_buf[KWSYS_ST_BUFFER];
  long nleft = statSource.st_size;
  while(nleft > 0)
    {
    // Read a block from each file.
    long nnext = (nleft > KWSYS_ST_BUFFER)? KWSYS_ST_BUFFER : nleft;
    finSource.read(source_buf, nnext);
    finDestination.read(dest_buf, nnext);
1577

1578 1579 1580 1581 1582 1583
    // If either failed to read assume they are different.
    if(static_cast<long>(finSource.gcount()) != nnext ||
       static_cast<long>(finDestination.gcount()) != nnext)
      {
      return true;
      }
1584

1585
    // If this block differs the file differs.
Andy Cedilnik's avatar
Andy Cedilnik committed
1586 1587
    if(memcmp(static_cast<const void*>(source_buf),
        static_cast<const void*>(dest_buf), nnext) != 0)
1588 1589 1590
      {
      return true;
      }
1591

1592 1593 1594
    // Update the byte count remaining.
    nleft -= nnext;
    }
1595

1596 1597
  // No differences found.
  return false;
1598 1599 1600 1601 1602 1603 1604 1605
}


/**
 * Copy a file named by "source" to the file named by "destination".
 */
bool SystemTools::CopyFileAlways(const char* source, const char* destination)
{
1606 1607 1608 1609 1610
  // If files are the same do not copy
  if ( SystemTools::SameFile(source, destination) )
    {
    return true;
    }
1611 1612 1613
  mode_t perm = 0;
  bool perms = SystemTools::GetPermissions(source, perm);

1614 1615 1616 1617 1618 1619
  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.

1620
  kwsys_stl::string new_destination;
1621 1622 1623 1624 1625 1626
  if(SystemTools::FileExists(destination) &&
     SystemTools::FileIsDirectory(destination))
    {
    new_destination = destination;
    SystemTools::ConvertToUnixSlashes(new_destination);
    new_destination += '/';
1627
    kwsys_stl::string source_name = source;
1628 1629 1630 1631 1632 1633
    new_destination += SystemTools::GetFilenameName(source_name);
    destination = new_destination.c_str();
    }

  // Create destination directory

1634
  kwsys_stl::string destination_dir = destination;
1635 1636 1637 1638 1639 1640
  destination_dir = SystemTools::GetFilenamePath(destination_dir);
  SystemTools::MakeDirectory(destination_dir.c_str());

  // Open files

#if defined(_WIN32) || defined(__CYGWIN__)
1641 1642
  kwsys_ios::ifstream fin(source, 
                    kwsys_ios::ios::binary | kwsys_ios::ios::in);
1643
#else
1644
  kwsys_ios::ifstream fin(source);
1645 1646 1647 1648 1649
#endif
  if(!fin)
    {
    return false;
    }
1650 1651 1652 1653 1654 1655
 
  // 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);
1656

1657
#if defined(_WIN32) || defined(__CYGWIN__)
1658 1659
  kwsys_ios::ofstream fout(destination, 
                     kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
1660
#else
1661 1662
  kwsys_ios::ofstream fout(destination, 
                     kwsys_ios::ios::out | kwsys_ios::ios::trunc);
1663 1664 1665 1666 1667 1668 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
#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)
    {
1705
   return false;
1706
    }
1707 1708 1709 1710 1711 1712 1713
  if ( perms )
    {
    if ( !SystemTools::SetPermissions(destination, perm) )
      {
      return false;
      }
    }
1714 1715 1716
  return true;
}

1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
//----------------------------------------------------------------------------
bool SystemTools::CopyAFile(const char* source, const char* destination,
                            bool always)
{
  if(always)
    {
    return SystemTools::CopyFileAlways(source, destination);
    }
  else
    {
    return SystemTools::CopyFileIfDifferent(source, destination);
    }
}

1731 1732 1733 1734
/**
 * Copy a directory content from "source" directory to the directory named by
 * "destination".
 */
1735 1736
bool SystemTools::CopyADirectory(const char* source, const char* destination,
                                 bool always)
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
{
  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>