PageRenderTime 64ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/cmake-2.8.9-rc2/Source/kwsys/SystemTools.cxx

#
C++ | 4856 lines | 4615 code | 106 blank | 135 comment | 245 complexity | 6fe2fe033c87c70c5c039e3d0ea59b61 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, Apache-2.0
  1. /*============================================================================
  2. KWSys - Kitware System Library
  3. Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
  4. Distributed under the OSI-approved BSD License (the "License");
  5. see accompanying file Copyright.txt for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even the
  7. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the License for more information.
  9. ============================================================================*/
  10. #ifdef __osf__
  11. # define _OSF_SOURCE
  12. # define _POSIX_C_SOURCE 199506L
  13. # define _XOPEN_SOURCE_EXTENDED
  14. #endif
  15. #include "kwsysPrivate.h"
  16. #include KWSYS_HEADER(RegularExpression.hxx)
  17. #include KWSYS_HEADER(SystemTools.hxx)
  18. #include KWSYS_HEADER(Directory.hxx)
  19. #include KWSYS_HEADER(ios/iostream)
  20. #include KWSYS_HEADER(ios/fstream)
  21. #include KWSYS_HEADER(ios/sstream)
  22. #include KWSYS_HEADER(stl/set)
  23. // Work-around CMake dependency scanning limitation. This must
  24. // duplicate the above list of headers.
  25. #if 0
  26. # include "SystemTools.hxx.in"
  27. # include "Directory.hxx.in"
  28. # include "kwsys_ios_iostream.h.in"
  29. # include "kwsys_ios_fstream.h.in"
  30. # include "kwsys_ios_sstream.h.in"
  31. #endif
  32. #ifdef _MSC_VER
  33. # pragma warning (disable: 4786)
  34. #endif
  35. #if defined(__sgi) && !defined(__GNUC__)
  36. # pragma set woff 1375 /* base class destructor not virtual */
  37. #endif
  38. #include <ctype.h>
  39. #include <errno.h>
  40. #ifdef __QNX__
  41. # include <malloc.h> /* for malloc/free on QNX */
  42. #endif
  43. #include <stdio.h>
  44. #include <stdlib.h>
  45. #include <string.h>
  46. #include <sys/stat.h>
  47. #include <time.h>
  48. // support for realpath call
  49. #ifndef _WIN32
  50. #include <sys/time.h>
  51. #include <utime.h>
  52. #include <limits.h>
  53. #include <sys/wait.h>
  54. #include <sys/ioctl.h>
  55. #include <unistd.h>
  56. #include <pwd.h>
  57. #ifndef __VMS
  58. #include <sys/param.h>
  59. #include <termios.h>
  60. #endif
  61. #include <signal.h> /* sigprocmask */
  62. #endif
  63. // Windows API.
  64. #if defined(_WIN32)
  65. # include <windows.h>
  66. #elif defined (__CYGWIN__)
  67. # include <windows.h>
  68. # undef _WIN32
  69. #endif
  70. #if !KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H
  71. extern char **environ;
  72. #endif
  73. #ifdef __CYGWIN__
  74. extern "C" void cygwin_conv_to_win32_path(const char *path, char *win32_path);
  75. #endif
  76. // getpwnam doesn't exist on Windows and Cray Xt3/Catamount
  77. // same for TIOCGWINSZ
  78. #if defined(_WIN32) || defined (__LIBCATAMOUNT__)
  79. # undef HAVE_GETPWNAM
  80. # undef HAVE_TTY_INFO
  81. #else
  82. # define HAVE_GETPWNAM 1
  83. # define HAVE_TTY_INFO 1
  84. #endif
  85. #define VTK_URL_PROTOCOL_REGEX "([a-zA-Z0-9]*)://(.*)"
  86. #define VTK_URL_REGEX "([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]+)(:([0-9]+))?/(.+)?"
  87. #ifdef _MSC_VER
  88. #include <sys/utime.h>
  89. #else
  90. #include <utime.h>
  91. #endif
  92. // This is a hack to prevent warnings about these functions being
  93. // declared but not referenced.
  94. #if defined(__sgi) && !defined(__GNUC__)
  95. # include <sys/termios.h>
  96. namespace KWSYS_NAMESPACE
  97. {
  98. class SystemToolsHack
  99. {
  100. public:
  101. enum
  102. {
  103. Ref1 = sizeof(cfgetospeed(0)),
  104. Ref2 = sizeof(cfgetispeed(0)),
  105. Ref3 = sizeof(tcgetattr(0, 0)),
  106. Ref4 = sizeof(tcsetattr(0, 0, 0)),
  107. Ref5 = sizeof(cfsetospeed(0,0)),
  108. Ref6 = sizeof(cfsetispeed(0,0))
  109. };
  110. };
  111. }
  112. #endif
  113. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
  114. #include <io.h>
  115. #include <direct.h>
  116. #define _unlink unlink
  117. #endif
  118. /* The maximum length of a file name. */
  119. #if defined(PATH_MAX)
  120. # define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
  121. #elif defined(MAXPATHLEN)
  122. # define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
  123. #else
  124. # define KWSYS_SYSTEMTOOLS_MAXPATH 16384
  125. #endif
  126. #if defined(__WATCOMC__)
  127. #include <direct.h>
  128. #define _mkdir mkdir
  129. #define _rmdir rmdir
  130. #define _getcwd getcwd
  131. #define _chdir chdir
  132. #endif
  133. #if defined(__HAIKU__)
  134. #include <os/kernel/OS.h>
  135. #include <os/storage/Path.h>
  136. #endif
  137. #if defined(__BEOS__) && !defined(__ZETA__) && !defined(__HAIKU__)
  138. #include <be/kernel/OS.h>
  139. #include <be/storage/Path.h>
  140. // BeOS 5 doesn't have usleep(), but it has snooze(), which is identical.
  141. static inline void usleep(unsigned int msec)
  142. {
  143. ::snooze(msec);
  144. }
  145. // BeOS 5 also doesn't have realpath(), but its C++ API offers something close.
  146. static inline char *realpath(const char *path, char *resolved_path)
  147. {
  148. const size_t maxlen = KWSYS_SYSTEMTOOLS_MAXPATH;
  149. snprintf(resolved_path, maxlen, "%s", path);
  150. BPath normalized(resolved_path, NULL, true);
  151. const char *resolved = normalized.Path();
  152. if (resolved != NULL) // NULL == No such file.
  153. {
  154. if (snprintf(resolved_path, maxlen, "%s", resolved) < maxlen)
  155. {
  156. return resolved_path;
  157. }
  158. }
  159. return NULL; // something went wrong.
  160. }
  161. #endif
  162. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
  163. inline int Mkdir(const char* dir)
  164. {
  165. return _mkdir(dir);
  166. }
  167. inline int Rmdir(const char* dir)
  168. {
  169. return _rmdir(dir);
  170. }
  171. inline const char* Getcwd(char* buf, unsigned int len)
  172. {
  173. const char* ret = _getcwd(buf, len);
  174. if(!ret)
  175. {
  176. fprintf(stderr, "No current working directory.\n");
  177. abort();
  178. }
  179. // make sure the drive letter is capital
  180. if(strlen(buf) > 1 && buf[1] == ':')
  181. {
  182. buf[0] = toupper(buf[0]);
  183. }
  184. return ret;
  185. }
  186. inline int Chdir(const char* dir)
  187. {
  188. #if defined(__BORLANDC__)
  189. return chdir(dir);
  190. #else
  191. return _chdir(dir);
  192. #endif
  193. }
  194. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  195. {
  196. char *ptemp;
  197. char fullpath[MAX_PATH];
  198. if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
  199. {
  200. resolved_path = fullpath;
  201. KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
  202. }
  203. else
  204. {
  205. resolved_path = path;
  206. }
  207. }
  208. #else
  209. #include <sys/types.h>
  210. #include <fcntl.h>
  211. #include <unistd.h>
  212. inline int Mkdir(const char* dir)
  213. {
  214. return mkdir(dir, 00777);
  215. }
  216. inline int Rmdir(const char* dir)
  217. {
  218. return rmdir(dir);
  219. }
  220. inline const char* Getcwd(char* buf, unsigned int len)
  221. {
  222. const char* ret = getcwd(buf, len);
  223. if(!ret)
  224. {
  225. fprintf(stderr, "No current working directory\n");
  226. abort();
  227. }
  228. return ret;
  229. }
  230. inline int Chdir(const char* dir)
  231. {
  232. return chdir(dir);
  233. }
  234. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  235. {
  236. char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
  237. char *ret = realpath(path, resolved_name);
  238. if(ret)
  239. {
  240. resolved_path = ret;
  241. }
  242. else
  243. {
  244. // if path resolution fails, return what was passed in
  245. resolved_path = path;
  246. }
  247. }
  248. #endif
  249. #if !defined(_WIN32) && defined(__COMO__)
  250. // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
  251. extern "C"
  252. {
  253. extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
  254. extern int pclose (FILE *__stream) __THROW;
  255. extern char *realpath (__const char *__restrict __name,
  256. char *__restrict __resolved) __THROW;
  257. extern char *strdup (__const char *__s) __THROW;
  258. extern int putenv (char *__string) __THROW;
  259. }
  260. #endif
  261. namespace KWSYS_NAMESPACE
  262. {
  263. double SystemTools::GetTime(void)
  264. {
  265. #if defined(_WIN32) && !defined(__CYGWIN__)
  266. FILETIME ft;
  267. GetSystemTimeAsFileTime(&ft);
  268. return (429.4967296*ft.dwHighDateTime
  269. + 0.0000001*ft.dwLowDateTime
  270. - 11644473600.0);
  271. #else
  272. struct timeval t;
  273. gettimeofday(&t, 0);
  274. return 1.0*double(t.tv_sec) + 0.000001*double(t.tv_usec);
  275. #endif
  276. }
  277. class SystemToolsTranslationMap :
  278. public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
  279. {
  280. };
  281. // adds the elements of the env variable path to the arg passed in
  282. void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
  283. {
  284. #if defined(_WIN32) && !defined(__CYGWIN__)
  285. const char* pathSep = ";";
  286. #else
  287. const char* pathSep = ":";
  288. #endif
  289. if(!env)
  290. {
  291. env = "PATH";
  292. }
  293. const char* cpathEnv = SystemTools::GetEnv(env);
  294. if ( !cpathEnv )
  295. {
  296. return;
  297. }
  298. kwsys_stl::string pathEnv = cpathEnv;
  299. // A hack to make the below algorithm work.
  300. if(!pathEnv.empty() && pathEnv[pathEnv.length()-1] != pathSep[0])
  301. {
  302. pathEnv += pathSep;
  303. }
  304. kwsys_stl::string::size_type start =0;
  305. bool done = false;
  306. while(!done)
  307. {
  308. kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
  309. if(endpos != kwsys_stl::string::npos)
  310. {
  311. path.push_back(pathEnv.substr(start, endpos-start));
  312. start = endpos+1;
  313. }
  314. else
  315. {
  316. done = true;
  317. }
  318. }
  319. for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
  320. i != path.end(); ++i)
  321. {
  322. SystemTools::ConvertToUnixSlashes(*i);
  323. }
  324. }
  325. const char* SystemTools::GetEnv(const char* key)
  326. {
  327. return getenv(key);
  328. }
  329. bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
  330. {
  331. const char* v = getenv(key);
  332. if(v)
  333. {
  334. result = v;
  335. return true;
  336. }
  337. else
  338. {
  339. return false;
  340. }
  341. }
  342. //----------------------------------------------------------------------------
  343. #if defined(__CYGWIN__) || defined(__GLIBC__)
  344. # define KWSYS_PUTENV_NAME /* putenv("A") removes A. */
  345. #elif defined(_WIN32)
  346. # define KWSYS_PUTENV_EMPTY /* putenv("A=") removes A. */
  347. #endif
  348. #if KWSYS_CXX_HAS_UNSETENV
  349. /* unsetenv("A") removes A from the environment.
  350. On older platforms it returns void instead of int. */
  351. static int kwsysUnPutEnv(const char* env)
  352. {
  353. if(const char* eq = strchr(env, '='))
  354. {
  355. std::string name(env, eq-env);
  356. unsetenv(name.c_str());
  357. }
  358. else
  359. {
  360. unsetenv(env);
  361. }
  362. return 0;
  363. }
  364. #elif defined(KWSYS_PUTENV_EMPTY) || defined(KWSYS_PUTENV_NAME)
  365. /* putenv("A=") or putenv("A") removes A from the environment. */
  366. static int kwsysUnPutEnv(const char* env)
  367. {
  368. int err = 0;
  369. const char* eq = strchr(env, '=');
  370. size_t const len = eq? (size_t)(eq-env) : strlen(env);
  371. # ifdef KWSYS_PUTENV_EMPTY
  372. size_t const sz = len + 2;
  373. # else
  374. size_t const sz = len + 1;
  375. # endif
  376. char local_buf[256];
  377. char* buf = sz > sizeof(local_buf) ? (char*)malloc(sz) : local_buf;
  378. if(!buf)
  379. {
  380. return -1;
  381. }
  382. strncpy(buf, env, len);
  383. # ifdef KWSYS_PUTENV_EMPTY
  384. buf[len] = '=';
  385. buf[len+1] = 0;
  386. if(putenv(buf) < 0)
  387. {
  388. err = errno;
  389. }
  390. # else
  391. buf[len] = 0;
  392. if(putenv(buf) < 0 && errno != EINVAL)
  393. {
  394. err = errno;
  395. }
  396. # endif
  397. if(buf != local_buf)
  398. {
  399. free(buf);
  400. }
  401. if(err)
  402. {
  403. errno = err;
  404. return -1;
  405. }
  406. return 0;
  407. }
  408. #else
  409. /* Manipulate the "environ" global directly. */
  410. static int kwsysUnPutEnv(const char* env)
  411. {
  412. const char* eq = strchr(env, '=');
  413. size_t const len = eq? (size_t)(eq-env) : strlen(env);
  414. int in = 0;
  415. int out = 0;
  416. while(environ[in])
  417. {
  418. if(strlen(environ[in]) > len &&
  419. environ[in][len] == '=' &&
  420. strncmp(env, environ[in], len) == 0)
  421. {
  422. ++in;
  423. }
  424. else
  425. {
  426. environ[out++] = environ[in++];
  427. }
  428. }
  429. while(out < in)
  430. {
  431. environ[out++] = 0;
  432. }
  433. return 0;
  434. }
  435. #endif
  436. //----------------------------------------------------------------------------
  437. #if KWSYS_CXX_HAS_SETENV
  438. /* setenv("A", "B", 1) will set A=B in the environment and makes its
  439. own copies of the strings. */
  440. bool SystemTools::PutEnv(const char* env)
  441. {
  442. if(const char* eq = strchr(env, '='))
  443. {
  444. std::string name(env, eq-env);
  445. return setenv(name.c_str(), eq+1, 1) == 0;
  446. }
  447. else
  448. {
  449. return kwsysUnPutEnv(env) == 0;
  450. }
  451. }
  452. bool SystemTools::UnPutEnv(const char* env)
  453. {
  454. return kwsysUnPutEnv(env) == 0;
  455. }
  456. #else
  457. /* putenv("A=B") will set A=B in the environment. Most putenv implementations
  458. put their argument directly in the environment. They never free the memory
  459. on program exit. Keep an active set of pointers to memory we allocate and
  460. pass to putenv, one per environment key. At program exit remove any
  461. environment values that may still reference memory we allocated. Then free
  462. the memory. This will not affect any environment values we never set. */
  463. # ifdef __INTEL_COMPILER
  464. # pragma warning disable 444 /* base has non-virtual destructor */
  465. # endif
  466. /* Order by environment key only (VAR from VAR=VALUE). */
  467. struct kwsysEnvCompare
  468. {
  469. bool operator() (const char* l, const char* r) const
  470. {
  471. const char* leq = strchr(l, '=');
  472. const char* req = strchr(r, '=');
  473. size_t llen = leq? (leq-l) : strlen(l);
  474. size_t rlen = req? (req-r) : strlen(r);
  475. if(llen == rlen)
  476. {
  477. return strncmp(l,r,llen) < 0;
  478. }
  479. else
  480. {
  481. return strcmp(l,r) < 0;
  482. }
  483. }
  484. };
  485. class kwsysEnv: public kwsys_stl::set<const char*, kwsysEnvCompare>
  486. {
  487. class Free
  488. {
  489. const char* Env;
  490. public:
  491. Free(const char* env): Env(env) {}
  492. ~Free() { free(const_cast<char*>(this->Env)); }
  493. };
  494. public:
  495. typedef kwsys_stl::set<const char*, kwsysEnvCompare> derived;
  496. ~kwsysEnv()
  497. {
  498. for(derived::iterator i = this->begin(); i != this->end(); ++i)
  499. {
  500. kwsysUnPutEnv(*i);
  501. free(const_cast<char*>(*i));
  502. }
  503. }
  504. const char* Release(const char* env)
  505. {
  506. const char* old = 0;
  507. derived::iterator i = this->find(env);
  508. if(i != this->end())
  509. {
  510. old = *i;
  511. this->erase(i);
  512. }
  513. return old;
  514. }
  515. bool Put(const char* env)
  516. {
  517. Free oldEnv(this->Release(env));
  518. static_cast<void>(oldEnv);
  519. char* newEnv = strdup(env);
  520. this->insert(newEnv);
  521. return putenv(newEnv) == 0;
  522. }
  523. bool UnPut(const char* env)
  524. {
  525. Free oldEnv(this->Release(env));
  526. static_cast<void>(oldEnv);
  527. return kwsysUnPutEnv(env) == 0;
  528. }
  529. };
  530. static kwsysEnv kwsysEnvInstance;
  531. bool SystemTools::PutEnv(const char* env)
  532. {
  533. return kwsysEnvInstance.Put(env);
  534. }
  535. bool SystemTools::UnPutEnv(const char* env)
  536. {
  537. return kwsysEnvInstance.UnPut(env);
  538. }
  539. #endif
  540. //----------------------------------------------------------------------------
  541. const char* SystemTools::GetExecutableExtension()
  542. {
  543. #if defined(_WIN32) || defined(__CYGWIN__) || defined(__VMS)
  544. return ".exe";
  545. #else
  546. return "";
  547. #endif
  548. }
  549. bool SystemTools::MakeDirectory(const char* path)
  550. {
  551. if(!path)
  552. {
  553. return false;
  554. }
  555. if(SystemTools::FileExists(path))
  556. {
  557. return true;
  558. }
  559. kwsys_stl::string dir = path;
  560. if(dir.size() == 0)
  561. {
  562. return false;
  563. }
  564. SystemTools::ConvertToUnixSlashes(dir);
  565. kwsys_stl::string::size_type pos = dir.find(':');
  566. if(pos == kwsys_stl::string::npos)
  567. {
  568. pos = 0;
  569. }
  570. kwsys_stl::string topdir;
  571. while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
  572. {
  573. topdir = dir.substr(0, pos);
  574. Mkdir(topdir.c_str());
  575. pos++;
  576. }
  577. if(dir[dir.size()-1] == '/')
  578. {
  579. topdir = dir.substr(0, dir.size());
  580. }
  581. else
  582. {
  583. topdir = dir;
  584. }
  585. if(Mkdir(topdir.c_str()) != 0)
  586. {
  587. // There is a bug in the Borland Run time library which makes MKDIR
  588. // return EACCES when it should return EEXISTS
  589. // if it is some other error besides directory exists
  590. // then return false
  591. if( (errno != EEXIST)
  592. #ifdef __BORLANDC__
  593. && (errno != EACCES)
  594. #endif
  595. )
  596. {
  597. return false;
  598. }
  599. }
  600. return true;
  601. }
  602. // replace replace with with as many times as it shows up in source.
  603. // write the result into source.
  604. void SystemTools::ReplaceString(kwsys_stl::string& source,
  605. const char* replace,
  606. const char* with)
  607. {
  608. const char *src = source.c_str();
  609. char *searchPos = const_cast<char *>(strstr(src,replace));
  610. // get out quick if string is not found
  611. if (!searchPos)
  612. {
  613. return;
  614. }
  615. // perform replacements until done
  616. size_t replaceSize = strlen(replace);
  617. // do while hangs if replaceSize is 0
  618. if(replaceSize == 0)
  619. {
  620. return;
  621. }
  622. char *orig = strdup(src);
  623. char *currentPos = orig;
  624. searchPos = searchPos - src + orig;
  625. // initialize the result
  626. source.erase(source.begin(),source.end());
  627. do
  628. {
  629. *searchPos = '\0';
  630. source += currentPos;
  631. currentPos = searchPos + replaceSize;
  632. // replace
  633. source += with;
  634. searchPos = strstr(currentPos,replace);
  635. }
  636. while (searchPos);
  637. // copy any trailing text
  638. source += currentPos;
  639. free(orig);
  640. }
  641. #if defined(KEY_WOW64_32KEY) && defined(KEY_WOW64_64KEY)
  642. # define KWSYS_ST_KEY_WOW64_32KEY KEY_WOW64_32KEY
  643. # define KWSYS_ST_KEY_WOW64_64KEY KEY_WOW64_64KEY
  644. #else
  645. # define KWSYS_ST_KEY_WOW64_32KEY 0x0200
  646. # define KWSYS_ST_KEY_WOW64_64KEY 0x0100
  647. #endif
  648. #if defined(_WIN32) && !defined(__CYGWIN__)
  649. static DWORD SystemToolsMakeRegistryMode(DWORD mode,
  650. SystemTools::KeyWOW64 view)
  651. {
  652. // only add the modes when on a system that supports Wow64.
  653. static FARPROC wow64p = GetProcAddress(GetModuleHandle("kernel32"),
  654. "IsWow64Process");
  655. if(wow64p == NULL)
  656. {
  657. return mode;
  658. }
  659. if(view == SystemTools::KeyWOW64_32)
  660. {
  661. return mode | KWSYS_ST_KEY_WOW64_32KEY;
  662. }
  663. else if(view == SystemTools::KeyWOW64_64)
  664. {
  665. return mode | KWSYS_ST_KEY_WOW64_64KEY;
  666. }
  667. return mode;
  668. }
  669. #endif
  670. // Read a registry value.
  671. // Example :
  672. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  673. // => will return the data of the "default" value of the key
  674. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  675. // => will return the data of the "Root" value of the key
  676. #if defined(_WIN32) && !defined(__CYGWIN__)
  677. bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value,
  678. KeyWOW64 view)
  679. {
  680. bool valueset = false;
  681. kwsys_stl::string primary = key;
  682. kwsys_stl::string second;
  683. kwsys_stl::string valuename;
  684. size_t start = primary.find("\\");
  685. if (start == kwsys_stl::string::npos)
  686. {
  687. return false;
  688. }
  689. size_t valuenamepos = primary.find(";");
  690. if (valuenamepos != kwsys_stl::string::npos)
  691. {
  692. valuename = primary.substr(valuenamepos+1);
  693. }
  694. second = primary.substr(start+1, valuenamepos-start-1);
  695. primary = primary.substr(0, start);
  696. HKEY primaryKey = HKEY_CURRENT_USER;
  697. if (primary == "HKEY_CURRENT_USER")
  698. {
  699. primaryKey = HKEY_CURRENT_USER;
  700. }
  701. if (primary == "HKEY_CURRENT_CONFIG")
  702. {
  703. primaryKey = HKEY_CURRENT_CONFIG;
  704. }
  705. if (primary == "HKEY_CLASSES_ROOT")
  706. {
  707. primaryKey = HKEY_CLASSES_ROOT;
  708. }
  709. if (primary == "HKEY_LOCAL_MACHINE")
  710. {
  711. primaryKey = HKEY_LOCAL_MACHINE;
  712. }
  713. if (primary == "HKEY_USERS")
  714. {
  715. primaryKey = HKEY_USERS;
  716. }
  717. HKEY hKey;
  718. if(RegOpenKeyEx(primaryKey,
  719. second.c_str(),
  720. 0,
  721. SystemToolsMakeRegistryMode(KEY_READ, view),
  722. &hKey) != ERROR_SUCCESS)
  723. {
  724. return false;
  725. }
  726. else
  727. {
  728. DWORD dwType, dwSize;
  729. dwSize = 1023;
  730. char data[1024];
  731. if(RegQueryValueEx(hKey,
  732. (LPTSTR)valuename.c_str(),
  733. NULL,
  734. &dwType,
  735. (BYTE *)data,
  736. &dwSize) == ERROR_SUCCESS)
  737. {
  738. if (dwType == REG_SZ)
  739. {
  740. value = data;
  741. valueset = true;
  742. }
  743. else if (dwType == REG_EXPAND_SZ)
  744. {
  745. char expanded[1024];
  746. DWORD dwExpandedSize = sizeof(expanded)/sizeof(expanded[0]);
  747. if(ExpandEnvironmentStrings(data, expanded, dwExpandedSize))
  748. {
  749. value = expanded;
  750. valueset = true;
  751. }
  752. }
  753. }
  754. RegCloseKey(hKey);
  755. }
  756. return valueset;
  757. }
  758. #else
  759. bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &,
  760. KeyWOW64)
  761. {
  762. return false;
  763. }
  764. #endif
  765. // Write a registry value.
  766. // Example :
  767. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  768. // => will set the data of the "default" value of the key
  769. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  770. // => will set the data of the "Root" value of the key
  771. #if defined(_WIN32) && !defined(__CYGWIN__)
  772. bool SystemTools::WriteRegistryValue(const char *key, const char *value,
  773. KeyWOW64 view)
  774. {
  775. kwsys_stl::string primary = key;
  776. kwsys_stl::string second;
  777. kwsys_stl::string valuename;
  778. size_t start = primary.find("\\");
  779. if (start == kwsys_stl::string::npos)
  780. {
  781. return false;
  782. }
  783. size_t valuenamepos = primary.find(";");
  784. if (valuenamepos != kwsys_stl::string::npos)
  785. {
  786. valuename = primary.substr(valuenamepos+1);
  787. }
  788. second = primary.substr(start+1, valuenamepos-start-1);
  789. primary = primary.substr(0, start);
  790. HKEY primaryKey = HKEY_CURRENT_USER;
  791. if (primary == "HKEY_CURRENT_USER")
  792. {
  793. primaryKey = HKEY_CURRENT_USER;
  794. }
  795. if (primary == "HKEY_CURRENT_CONFIG")
  796. {
  797. primaryKey = HKEY_CURRENT_CONFIG;
  798. }
  799. if (primary == "HKEY_CLASSES_ROOT")
  800. {
  801. primaryKey = HKEY_CLASSES_ROOT;
  802. }
  803. if (primary == "HKEY_LOCAL_MACHINE")
  804. {
  805. primaryKey = HKEY_LOCAL_MACHINE;
  806. }
  807. if (primary == "HKEY_USERS")
  808. {
  809. primaryKey = HKEY_USERS;
  810. }
  811. HKEY hKey;
  812. DWORD dwDummy;
  813. char lpClass[] = "";
  814. if(RegCreateKeyEx(primaryKey,
  815. second.c_str(),
  816. 0,
  817. lpClass,
  818. REG_OPTION_NON_VOLATILE,
  819. SystemToolsMakeRegistryMode(KEY_WRITE, view),
  820. NULL,
  821. &hKey,
  822. &dwDummy) != ERROR_SUCCESS)
  823. {
  824. return false;
  825. }
  826. if(RegSetValueEx(hKey,
  827. (LPTSTR)valuename.c_str(),
  828. 0,
  829. REG_SZ,
  830. (CONST BYTE *)value,
  831. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  832. {
  833. return true;
  834. }
  835. return false;
  836. }
  837. #else
  838. bool SystemTools::WriteRegistryValue(const char *, const char *, KeyWOW64)
  839. {
  840. return false;
  841. }
  842. #endif
  843. // Delete a registry value.
  844. // Example :
  845. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  846. // => will delete the data of the "default" value of the key
  847. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  848. // => will delete the data of the "Root" value of the key
  849. #if defined(_WIN32) && !defined(__CYGWIN__)
  850. bool SystemTools::DeleteRegistryValue(const char *key, KeyWOW64 view)
  851. {
  852. kwsys_stl::string primary = key;
  853. kwsys_stl::string second;
  854. kwsys_stl::string valuename;
  855. size_t start = primary.find("\\");
  856. if (start == kwsys_stl::string::npos)
  857. {
  858. return false;
  859. }
  860. size_t valuenamepos = primary.find(";");
  861. if (valuenamepos != kwsys_stl::string::npos)
  862. {
  863. valuename = primary.substr(valuenamepos+1);
  864. }
  865. second = primary.substr(start+1, valuenamepos-start-1);
  866. primary = primary.substr(0, start);
  867. HKEY primaryKey = HKEY_CURRENT_USER;
  868. if (primary == "HKEY_CURRENT_USER")
  869. {
  870. primaryKey = HKEY_CURRENT_USER;
  871. }
  872. if (primary == "HKEY_CURRENT_CONFIG")
  873. {
  874. primaryKey = HKEY_CURRENT_CONFIG;
  875. }
  876. if (primary == "HKEY_CLASSES_ROOT")
  877. {
  878. primaryKey = HKEY_CLASSES_ROOT;
  879. }
  880. if (primary == "HKEY_LOCAL_MACHINE")
  881. {
  882. primaryKey = HKEY_LOCAL_MACHINE;
  883. }
  884. if (primary == "HKEY_USERS")
  885. {
  886. primaryKey = HKEY_USERS;
  887. }
  888. HKEY hKey;
  889. if(RegOpenKeyEx(primaryKey,
  890. second.c_str(),
  891. 0,
  892. SystemToolsMakeRegistryMode(KEY_WRITE, view),
  893. &hKey) != ERROR_SUCCESS)
  894. {
  895. return false;
  896. }
  897. else
  898. {
  899. if(RegDeleteValue(hKey,
  900. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  901. {
  902. RegCloseKey(hKey);
  903. return true;
  904. }
  905. }
  906. return false;
  907. }
  908. #else
  909. bool SystemTools::DeleteRegistryValue(const char *, KeyWOW64)
  910. {
  911. return false;
  912. }
  913. #endif
  914. bool SystemTools::SameFile(const char* file1, const char* file2)
  915. {
  916. #ifdef _WIN32
  917. HANDLE hFile1, hFile2;
  918. hFile1 = CreateFile( file1,
  919. GENERIC_READ,
  920. FILE_SHARE_READ ,
  921. NULL,
  922. OPEN_EXISTING,
  923. FILE_FLAG_BACKUP_SEMANTICS,
  924. NULL
  925. );
  926. hFile2 = CreateFile( file2,
  927. GENERIC_READ,
  928. FILE_SHARE_READ,
  929. NULL,
  930. OPEN_EXISTING,
  931. FILE_FLAG_BACKUP_SEMANTICS,
  932. NULL
  933. );
  934. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  935. {
  936. if(hFile1 != INVALID_HANDLE_VALUE)
  937. {
  938. CloseHandle(hFile1);
  939. }
  940. if(hFile2 != INVALID_HANDLE_VALUE)
  941. {
  942. CloseHandle(hFile2);
  943. }
  944. return false;
  945. }
  946. BY_HANDLE_FILE_INFORMATION fiBuf1;
  947. BY_HANDLE_FILE_INFORMATION fiBuf2;
  948. GetFileInformationByHandle( hFile1, &fiBuf1 );
  949. GetFileInformationByHandle( hFile2, &fiBuf2 );
  950. CloseHandle(hFile1);
  951. CloseHandle(hFile2);
  952. return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
  953. fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  954. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  955. #else
  956. struct stat fileStat1, fileStat2;
  957. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  958. {
  959. // see if the files are the same file
  960. // check the device inode and size
  961. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  962. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  963. fileStat2.st_size == fileStat1.st_size
  964. )
  965. {
  966. return true;
  967. }
  968. }
  969. return false;
  970. #endif
  971. }
  972. //----------------------------------------------------------------------------
  973. #if defined(_WIN32) || defined(__CYGWIN__)
  974. static bool WindowsFileExists(const char* filename)
  975. {
  976. WIN32_FILE_ATTRIBUTE_DATA fd;
  977. return GetFileAttributesExA(filename, GetFileExInfoStandard, &fd) != 0;
  978. }
  979. #endif
  980. //----------------------------------------------------------------------------
  981. bool SystemTools::FileExists(const char* filename)
  982. {
  983. if(!(filename && *filename))
  984. {
  985. return false;
  986. }
  987. #if defined(__CYGWIN__)
  988. // Convert filename to native windows path if possible.
  989. char winpath[MAX_PATH];
  990. if(SystemTools::PathCygwinToWin32(filename, winpath))
  991. {
  992. return WindowsFileExists(winpath);
  993. }
  994. return access(filename, R_OK) == 0;
  995. #elif defined(_WIN32)
  996. return WindowsFileExists(filename);
  997. #else
  998. return access(filename, R_OK) == 0;
  999. #endif
  1000. }
  1001. //----------------------------------------------------------------------------
  1002. bool SystemTools::FileExists(const char* filename, bool isFile)
  1003. {
  1004. if(SystemTools::FileExists(filename))
  1005. {
  1006. // If isFile is set return not FileIsDirectory,
  1007. // so this will only be true if it is a file
  1008. return !isFile || !SystemTools::FileIsDirectory(filename);
  1009. }
  1010. return false;
  1011. }
  1012. //----------------------------------------------------------------------------
  1013. #ifdef __CYGWIN__
  1014. bool SystemTools::PathCygwinToWin32(const char *path, char *win32_path)
  1015. {
  1016. SystemToolsTranslationMap::iterator i =
  1017. SystemTools::Cyg2Win32Map->find(path);
  1018. if (i != SystemTools::Cyg2Win32Map->end())
  1019. {
  1020. strncpy(win32_path, i->second.c_str(), MAX_PATH);
  1021. }
  1022. else
  1023. {
  1024. cygwin_conv_to_win32_path(path, win32_path);
  1025. SystemToolsTranslationMap::value_type entry(path, win32_path);
  1026. SystemTools::Cyg2Win32Map->insert(entry);
  1027. }
  1028. return win32_path[0] != 0;
  1029. }
  1030. #endif
  1031. bool SystemTools::Touch(const char* filename, bool create)
  1032. {
  1033. if(create && !SystemTools::FileExists(filename))
  1034. {
  1035. FILE* file = fopen(filename, "a+b");
  1036. if(file)
  1037. {
  1038. fclose(file);
  1039. return true;
  1040. }
  1041. return false;
  1042. }
  1043. #ifdef _MSC_VER
  1044. #define utime _utime
  1045. #define utimbuf _utimbuf
  1046. #endif
  1047. struct stat fromStat;
  1048. if(stat(filename, &fromStat) < 0)
  1049. {
  1050. return false;
  1051. }
  1052. struct utimbuf buf;
  1053. buf.actime = fromStat.st_atime;
  1054. buf.modtime = static_cast<time_t>(SystemTools::GetTime());
  1055. if(utime(filename, &buf) < 0)
  1056. {
  1057. return false;
  1058. }
  1059. return true;
  1060. }
  1061. bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
  1062. int* result)
  1063. {
  1064. // Default to same time.
  1065. *result = 0;
  1066. #if !defined(_WIN32) || defined(__CYGWIN__)
  1067. // POSIX version. Use stat function to get file modification time.
  1068. struct stat s1;
  1069. if(stat(f1, &s1) != 0)
  1070. {
  1071. return false;
  1072. }
  1073. struct stat s2;
  1074. if(stat(f2, &s2) != 0)
  1075. {
  1076. return false;
  1077. }
  1078. # if KWSYS_STAT_HAS_ST_MTIM
  1079. // Compare using nanosecond resolution.
  1080. if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
  1081. {
  1082. *result = -1;
  1083. }
  1084. else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
  1085. {
  1086. *result = 1;
  1087. }
  1088. else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
  1089. {
  1090. *result = -1;
  1091. }
  1092. else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
  1093. {
  1094. *result = 1;
  1095. }
  1096. # else
  1097. // Compare using 1 second resolution.
  1098. if(s1.st_mtime < s2.st_mtime)
  1099. {
  1100. *result = -1;
  1101. }
  1102. else if(s1.st_mtime > s2.st_mtime)
  1103. {
  1104. *result = 1;
  1105. }
  1106. # endif
  1107. #else
  1108. // Windows version. Get the modification time from extended file attributes.
  1109. WIN32_FILE_ATTRIBUTE_DATA f1d;
  1110. WIN32_FILE_ATTRIBUTE_DATA f2d;
  1111. if(!GetFileAttributesEx(f1, GetFileExInfoStandard, &f1d))
  1112. {
  1113. return false;
  1114. }
  1115. if(!GetFileAttributesEx(f2, GetFileExInfoStandard, &f2d))
  1116. {
  1117. return false;
  1118. }
  1119. // Compare the file times using resolution provided by system call.
  1120. *result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime);
  1121. #endif
  1122. return true;
  1123. }
  1124. // Return a capitalized string (i.e the first letter is uppercased, all other
  1125. // are lowercased)
  1126. kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
  1127. {
  1128. kwsys_stl::string n;
  1129. if(s.size() == 0)
  1130. {
  1131. return n;
  1132. }
  1133. n.resize(s.size());
  1134. n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
  1135. for (size_t i = 1; i < s.size(); i++)
  1136. {
  1137. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  1138. }
  1139. return n;
  1140. }
  1141. // Return capitalized words
  1142. kwsys_stl::string SystemTools::CapitalizedWords(const kwsys_stl::string& s)
  1143. {
  1144. kwsys_stl::string n(s);
  1145. for (size_t i = 0; i < s.size(); i++)
  1146. {
  1147. #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
  1148. // MS has an assert that will fail if s[i] < 0; setting
  1149. // LC_CTYPE using setlocale() does *not* help. Painful.
  1150. if ((int)s[i] >= 0 && isalpha(s[i]) &&
  1151. (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
  1152. #else
  1153. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  1154. #endif
  1155. {
  1156. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  1157. }
  1158. }
  1159. return n;
  1160. }
  1161. // Return uncapitalized words
  1162. kwsys_stl::string SystemTools::UnCapitalizedWords(const kwsys_stl::string& s)
  1163. {
  1164. kwsys_stl::string n(s);
  1165. for (size_t i = 0; i < s.size(); i++)
  1166. {
  1167. #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
  1168. // MS has an assert that will fail if s[i] < 0; setting
  1169. // LC_CTYPE using setlocale() does *not* help. Painful.
  1170. if ((int)s[i] >= 0 && isalpha(s[i]) &&
  1171. (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
  1172. #else
  1173. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  1174. #endif
  1175. {
  1176. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  1177. }
  1178. }
  1179. return n;
  1180. }
  1181. // only works for words with at least two letters
  1182. kwsys_stl::string SystemTools::AddSpaceBetweenCapitalizedWords(
  1183. const kwsys_stl::string& s)
  1184. {
  1185. kwsys_stl::string n;
  1186. if (s.size())
  1187. {
  1188. n.reserve(s.size());
  1189. n += s[0];
  1190. for (size_t i = 1; i < s.size(); i++)
  1191. {
  1192. if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1]))
  1193. {
  1194. n += ' ';
  1195. }
  1196. n += s[i];
  1197. }
  1198. }
  1199. return n;
  1200. }
  1201. char* SystemTools::AppendStrings(const char* str1, const char* str2)
  1202. {
  1203. if (!str1)
  1204. {
  1205. return SystemTools::DuplicateString(str2);
  1206. }
  1207. if (!str2)
  1208. {
  1209. return SystemTools::DuplicateString(str1);
  1210. }
  1211. size_t len1 = strlen(str1);
  1212. char *newstr = new char[len1 + strlen(str2) + 1];
  1213. if (!newstr)
  1214. {
  1215. return 0;
  1216. }
  1217. strcpy(newstr, str1);
  1218. strcat(newstr + len1, str2);
  1219. return newstr;
  1220. }
  1221. char* SystemTools::AppendStrings(
  1222. const char* str1, const char* str2, const char* str3)
  1223. {
  1224. if (!str1)
  1225. {
  1226. return SystemTools::AppendStrings(str2, str3);
  1227. }
  1228. if (!str2)
  1229. {
  1230. return SystemTools::AppendStrings(str1, str3);
  1231. }
  1232. if (!str3)
  1233. {
  1234. return SystemTools::AppendStrings(str1, str2);
  1235. }
  1236. size_t len1 = strlen(str1), len2 = strlen(str2);
  1237. char *newstr = new char[len1 + len2 + strlen(str3) + 1];
  1238. if (!newstr)
  1239. {
  1240. return 0;
  1241. }
  1242. strcpy(newstr, str1);
  1243. strcat(newstr + len1, str2);
  1244. strcat(newstr + len1 + len2, str3);
  1245. return newstr;
  1246. }
  1247. // Return a lower case string
  1248. kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
  1249. {
  1250. kwsys_stl::string n;
  1251. n.resize(s.size());
  1252. for (size_t i = 0; i < s.size(); i++)
  1253. {
  1254. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  1255. }
  1256. return n;
  1257. }
  1258. // Return a lower case string
  1259. kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
  1260. {
  1261. kwsys_stl::string n;
  1262. n.resize(s.size());
  1263. for (size_t i = 0; i < s.size(); i++)
  1264. {
  1265. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  1266. }
  1267. return n;
  1268. }
  1269. // Count char in string
  1270. size_t SystemTools::CountChar(const char* str, char c)
  1271. {
  1272. size_t count = 0;
  1273. if (str)
  1274. {
  1275. while (*str)
  1276. {
  1277. if (*str == c)
  1278. {
  1279. ++count;
  1280. }
  1281. ++str;
  1282. }
  1283. }
  1284. return count;
  1285. }
  1286. // Remove chars in string
  1287. char* SystemTools::RemoveChars(const char* str, const char *toremove)
  1288. {
  1289. if (!str)
  1290. {
  1291. return NULL;
  1292. }
  1293. char *clean_str = new char [strlen(str) + 1];
  1294. char *ptr = clean_str;
  1295. while (*str)
  1296. {
  1297. const char *str2 = toremove;
  1298. while (*str2 && *str != *str2)
  1299. {
  1300. ++str2;
  1301. }
  1302. if (!*str2)
  1303. {
  1304. *ptr++ = *str;
  1305. }
  1306. ++str;
  1307. }
  1308. *ptr = '\0';
  1309. return clean_str;
  1310. }
  1311. // Remove chars in string
  1312. char* SystemTools::RemoveCharsButUpperHex(const char* str)
  1313. {
  1314. if (!str)
  1315. {
  1316. return 0;
  1317. }
  1318. char *clean_str = new char [strlen(str) + 1];
  1319. char *ptr = clean_str;
  1320. while (*str)
  1321. {
  1322. if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'F'))
  1323. {
  1324. *ptr++ = *str;
  1325. }
  1326. ++str;
  1327. }
  1328. *ptr = '\0';
  1329. return clean_str;
  1330. }
  1331. // Replace chars in string
  1332. char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
  1333. {
  1334. if (str)
  1335. {
  1336. char *ptr = str;
  1337. while (*ptr)
  1338. {
  1339. const char *ptr2 = toreplace;
  1340. while (*ptr2)
  1341. {
  1342. if (*ptr == *ptr2)
  1343. {
  1344. *ptr = replacement;
  1345. }
  1346. ++ptr2;
  1347. }
  1348. ++ptr;
  1349. }
  1350. }
  1351. return str;
  1352. }
  1353. // Returns if string starts with another string
  1354. bool SystemTools::StringStartsWith(const char* str1, const char* str2)
  1355. {
  1356. if (!str1 || !str2)
  1357. {
  1358. return false;
  1359. }
  1360. size_t len1 = strlen(str1), len2 = strlen(str2);
  1361. return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
  1362. }
  1363. // Returns if string ends with another string
  1364. bool SystemTools::StringEndsWith(const char* str1, const char* str2)
  1365. {
  1366. if (!str1 || !str2)
  1367. {
  1368. return false;
  1369. }
  1370. size_t len1 = strlen(str1), len2 = strlen(str2);
  1371. return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
  1372. }
  1373. // Returns a pointer to the last occurence of str2 in str1
  1374. const char* SystemTools::FindLastString(const char* str1, const char* str2)
  1375. {
  1376. if (!str1 || !str2)
  1377. {
  1378. return NULL;
  1379. }
  1380. size_t len1 = strlen(str1), len2 = strlen(str2);
  1381. if (len1 >= len2)
  1382. {
  1383. const char *ptr = str1 + len1 - len2;
  1384. do
  1385. {
  1386. if (!strncmp(ptr, str2, len2))
  1387. {
  1388. return ptr;
  1389. }
  1390. } while (ptr-- != str1);
  1391. }
  1392. return NULL;
  1393. }
  1394. // Duplicate string
  1395. char* SystemTools::DuplicateString(const char* str)
  1396. {
  1397. if (str)
  1398. {
  1399. char *newstr = new char [strlen(str) + 1];
  1400. return strcpy(newstr, str);
  1401. }
  1402. return NULL;
  1403. }
  1404. // Return a cropped string
  1405. kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s,
  1406. size_t max_len)
  1407. {
  1408. if (!s.size() || max_len == 0 || max_len >= s.size())
  1409. {
  1410. return s;
  1411. }
  1412. kwsys_stl::string n;
  1413. n.reserve(max_len);
  1414. size_t middle = max_len / 2;
  1415. n += s.substr(0, middle);
  1416. n += s.substr(s.size() - (max_len - middle), kwsys_stl::string::npos);
  1417. if (max_len > 2)
  1418. {
  1419. n[middle] = '.';
  1420. if (max_len > 3)
  1421. {
  1422. n[middle - 1] = '.';
  1423. if (max_len > 4)
  1424. {
  1425. n[middle + 1] = '.';
  1426. }
  1427. }
  1428. }
  1429. return n;
  1430. }
  1431. //----------------------------------------------------------------------------
  1432. kwsys_stl::vector<kwsys::String> SystemTools::SplitString(const char* p, char sep, bool isPath)
  1433. {
  1434. kwsys_stl::string path = p;
  1435. kwsys_stl::vector<kwsys::String> paths;
  1436. if(path.empty())
  1437. {
  1438. return paths;
  1439. }
  1440. if(isPath && path[0] == '/')
  1441. {
  1442. path.erase(path.begin());
  1443. paths.push_back("/");
  1444. }
  1445. kwsys_stl::string::size_type pos1 = 0;
  1446. kwsys_stl::string::size_type pos2 = path.find(sep, pos1+1);
  1447. while(pos2 != kwsys_stl::string::npos)
  1448. {
  1449. paths.push_back(path.substr(pos1, pos2-pos1));
  1450. pos1 = pos2+1;
  1451. pos2 = path.find(sep, pos1+1);
  1452. }
  1453. paths.push_back(path.substr(pos1, pos2-pos1));
  1454. return paths;
  1455. }
  1456. //----------------------------------------------------------------------------
  1457. int SystemTools::EstimateFormatLength(const char *format, va_list ap)
  1458. {
  1459. if (!format)
  1460. {
  1461. return 0;
  1462. }
  1463. // Quick-hack attempt at estimating the length of the string.
  1464. // Should never under-estimate.
  1465. // Start with the length of the format string itself.
  1466. size_t length = strlen(format);
  1467. // Increase the length for every argument in the format.
  1468. const char* cur = format;
  1469. while(*cur)
  1470. {
  1471. if(*cur++ == '%')
  1472. {
  1473. // Skip "%%" since it doesn't correspond to a va_arg.
  1474. if(*cur != '%')
  1475. {
  1476. while(!int(isalpha(*cur)))
  1477. {
  1478. ++cur;
  1479. }
  1480. switch (*cur)
  1481. {
  1482. case 's':
  1483. {
  1484. // Check the length of the string.
  1485. char* s = va_arg(ap, char*);
  1486. if(s)
  1487. {
  1488. length += strlen(s);
  1489. }
  1490. } break;
  1491. case 'e':
  1492. case 'f':
  1493. case 'g':
  1494. {
  1495. // Assume the argument contributes no more than 64 characters.
  1496. length += 64;
  1497. // Eat the argument.
  1498. static_cast<void>(va_arg(ap, double));
  1499. } break;
  1500. default:
  1501. {
  1502. // Assume the argument contributes no more than 64 characters.
  1503. length += 64;
  1504. // Eat the argument.
  1505. static_cast<void>(va_arg(ap, int));
  1506. } break;
  1507. }
  1508. }
  1509. // Move past the characters just tested.
  1510. ++cur;
  1511. }
  1512. }
  1513. return static_cast<int>(length);
  1514. }
  1515. kwsys_stl::string SystemTools::EscapeChars(
  1516. const char *str,
  1517. const char *chars_to_escape,
  1518. char escape_char)
  1519. {
  1520. kwsys_stl::string n;
  1521. if (str)
  1522. {
  1523. if (!chars_to_escape | !*chars_to_escape)
  1524. {
  1525. n.append(str);
  1526. }
  1527. else
  1528. {
  1529. n.reserve(strlen(str));
  1530. while (*str)
  1531. {
  1532. const char *ptr = chars_to_escape;
  1533. while (*ptr)
  1534. {
  1535. if (*str == *ptr)
  1536. {
  1537. n += escape_char;
  1538. break;
  1539. }
  1540. ++ptr;
  1541. }
  1542. n += *str;
  1543. ++str;
  1544. }
  1545. }
  1546. }
  1547. return n;
  1548. }
  1549. #ifdef __VMS
  1550. static void ConvertVMSToUnix(kwsys_stl::string& path)
  1551. {
  1552. kwsys_stl::string::size_type rootEnd = path.find(":[");
  1553. kwsys_stl::string::size_type pathEnd = path.find("]");
  1554. if(rootEnd != path.npos)
  1555. {
  1556. kwsys_stl::string root = path.substr(0, rootEnd);
  1557. kwsys_stl::string pathPart = path.substr(rootEnd+2, pathEnd - rootEnd-2);
  1558. const char* pathCString = pathPart.c_str();
  1559. const char* pos0 = pathCString;
  1560. for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
  1561. {
  1562. if ( *pos0 == '.' )
  1563. {
  1564. pathPart[pos] = '/';
  1565. }
  1566. pos0 ++;
  1567. }
  1568. path = "/"+ root + "/" + pathPart;
  1569. }
  1570. }
  1571. #endif
  1572. // convert windows slashes to unix slashes
  1573. void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
  1574. {
  1575. const char* pathCString = path.c_str();
  1576. bool hasDoubleSlash = false;
  1577. #ifdef __VMS
  1578. ConvertVMSToUnix(path);
  1579. #else
  1580. const char* pos0 = pathCString;
  1581. const char* pos1 = pathCString+1;
  1582. for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
  1583. {
  1584. // make sure we don't convert an escaped space to a unix slash
  1585. if ( *pos0 == '\\' && *pos1 != ' ' )
  1586. {
  1587. path[pos] = '/';
  1588. }
  1589. // Also, reuse the loop to check for slash followed by another slash
  1590. if (*pos1 == '/' && *(pos1+1) == '/' && !hasDoubleSlash)
  1591. {
  1592. #ifdef _WIN32
  1593. // However, on windows if the first characters are both slashes,
  1594. // then keep them that way, so that network paths can be handled.
  1595. if ( pos > 0)
  1596. {
  1597. hasDoubleSlash = true;
  1598. }
  1599. #else
  1600. hasDoubleSlash = true;
  1601. #endif
  1602. }
  1603. pos0 ++;
  1604. pos1 ++;
  1605. }
  1606. if ( hasDoubleSlash )
  1607. {
  1608. SystemTools::ReplaceString(path, "//", "/");
  1609. }
  1610. #endif
  1611. // remove any trailing slash
  1612. if(!path.empty())
  1613. {
  1614. // if there is a tilda ~ then replace it with HOME
  1615. pathCString = path.c_str();
  1616. if(pathCString[0] == '~' && (pathCString[1] == '/' || pathCString[1] == '\0'))
  1617. {
  1618. const char* homeEnv = SystemTools::GetEnv("HOME");
  1619. if (homeEnv)
  1620. {
  1621. path.replace(0,1,homeEnv);
  1622. }
  1623. }
  1624. #ifdef HAVE_GETPWNAM
  1625. else if(pathCString[0] == '~')
  1626. {
  1627. kwsys_stl::string::size_type idx = path.find_first_of("/\0");
  1628. kwsys_stl::string user = path.substr(1, idx-1);
  1629. passwd* pw = getpwnam(user.c_str());
  1630. if(pw)
  1631. {
  1632. path.replace(0, idx, pw->pw_dir);
  1633. }
  1634. }
  1635. #endif
  1636. // remove trailing slash if the path is more than
  1637. // a single /
  1638. pathCString = path.c_str();
  1639. if(path.size() > 1 && *(pathCString+(path.size()-1)) == '/')
  1640. {
  1641. // if it is c:/ then do not remove the trailing slash
  1642. if(!((path.size() == 3 && pathCString[1] == ':')))
  1643. {
  1644. path = path.substr(0, path.size()-1);
  1645. }
  1646. }
  1647. }
  1648. }
  1649. // change // to /, and escape any spaces in the path
  1650. kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
  1651. {
  1652. kwsys_stl::string ret = path;
  1653. // remove // except at the beginning might be a cygwin drive
  1654. kwsys_stl::string::size_type pos=1;
  1655. while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
  1656. {
  1657. ret.erase(pos, 1);
  1658. }
  1659. // escape spaces and () in the path
  1660. if(ret.find_first_of(" ") != kwsys_stl::string::npos)
  1661. {
  1662. kwsys_stl::string result = "";
  1663. char lastch = 1;
  1664. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  1665. {
  1666. // if it is already escaped then don't try to escape it again
  1667. if((*ch == ' ') && lastch != '\\')
  1668. {
  1669. result += '\\';
  1670. }
  1671. result += *ch;
  1672. lastch = *ch;
  1673. }
  1674. ret = result;
  1675. }
  1676. return ret;
  1677. }
  1678. kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
  1679. {
  1680. #if defined(_WIN32) && !defined(__CYGWIN__)
  1681. return SystemTools::ConvertToWindowsOutputPath(path);
  1682. #else
  1683. return SystemTools::ConvertToUnixOutputPath(path);
  1684. #endif
  1685. }
  1686. // remove double slashes not at the start
  1687. kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  1688. {
  1689. kwsys_stl::string ret;
  1690. // make it big enough for all of path and double quotes
  1691. ret.reserve(strlen(path)+3);
  1692. // put path into the string
  1693. ret.assign(path);
  1694. ret = path;
  1695. kwsys_stl::string::size_type pos = 0;
  1696. // first convert all of the slashes
  1697. while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
  1698. {
  1699. ret[pos] = '\\';
  1700. pos++;
  1701. }
  1702. // check for really small paths
  1703. if(ret.size() < 2)
  1704. {
  1705. return ret;
  1706. }
  1707. // now clean up a bit and remove double slashes
  1708. // Only if it is not the first position in the path which is a network
  1709. // path on windows
  1710. pos = 1; // start at position 1
  1711. if(ret[0] == '\"')
  1712. {
  1713. pos = 2; // if the string is already quoted then start at 2
  1714. if(ret.size() < 3)
  1715. {
  1716. return ret;
  1717. }
  1718. }
  1719. while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
  1720. {
  1721. ret.erase(pos, 1);
  1722. }
  1723. // now double quote the path if it has spaces in it
  1724. // and is not already double quoted
  1725. if(ret.find(' ') != kwsys_stl::string::npos
  1726. && ret[0] != '\"')
  1727. {
  1728. ret.insert(static_cast<kwsys_stl::string::size_type>(0),
  1729. static_cast<kwsys_stl::string::size_type>(1), '\"');
  1730. ret.append(1, '\"');
  1731. }
  1732. return ret;
  1733. }
  1734. bool SystemTools::CopyFileIfDifferent(const char* source,
  1735. const char* destination)
  1736. {
  1737. // special check for a destination that is a directory
  1738. // FilesDiffer does not handle file to directory compare
  1739. if(SystemTools::FileIsDirectory(destination))
  1740. {
  1741. kwsys_stl::string new_destination = destination;
  1742. SystemTools::ConvertToUnixSlashes(new_destination);
  1743. new_destination += '/';
  1744. kwsys_stl::string source_name = source;
  1745. new_destination += SystemTools::GetFilenameName(source_name);
  1746. if(SystemTools::FilesDiffer(source, new_destination.c_str()))
  1747. {
  1748. return SystemTools::CopyFileAlways(source, destination);
  1749. }
  1750. else
  1751. {
  1752. // the files are the same so the copy is done return
  1753. // true
  1754. return true;
  1755. }
  1756. }
  1757. // source and destination are files so do a copy if they
  1758. // are different
  1759. if(SystemTools::FilesDiffer(source, destination))
  1760. {
  1761. return SystemTools::CopyFileAlways(source, destination);
  1762. }
  1763. // at this point the files must be the same so return true
  1764. return true;
  1765. }
  1766. #define KWSYS_ST_BUFFER 4096
  1767. bool SystemTools::FilesDiffer(const char* source,
  1768. const char* destination)
  1769. {
  1770. struct stat statSource;
  1771. if (stat(source, &statSource) != 0)
  1772. {
  1773. return true;
  1774. }
  1775. struct stat statDestination;
  1776. if (stat(destination, &statDestination) != 0)
  1777. {
  1778. return true;
  1779. }
  1780. if(statSource.st_size != statDestination.st_size)
  1781. {
  1782. return true;
  1783. }
  1784. if(statSource.st_size == 0)
  1785. {
  1786. return false;
  1787. }
  1788. #if defined(_WIN32) || defined(__CYGWIN__)
  1789. kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
  1790. kwsys_ios::ios::in));
  1791. kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
  1792. kwsys_ios::ios::in));
  1793. #else
  1794. kwsys_ios::ifstream finSource(source);
  1795. kwsys_ios::ifstream finDestination(destination);
  1796. #endif
  1797. if(!finSource || !finDestination)
  1798. {
  1799. return true;
  1800. }
  1801. // Compare the files a block at a time.
  1802. char source_buf[KWSYS_ST_BUFFER];
  1803. char dest_buf[KWSYS_ST_BUFFER];
  1804. off_t nleft = statSource.st_size;
  1805. while(nleft > 0)
  1806. {
  1807. // Read a block from each file.
  1808. kwsys_ios::streamsize nnext = (nleft > KWSYS_ST_BUFFER)? KWSYS_ST_BUFFER : static_cast<kwsys_ios::streamsize>(nleft);
  1809. finSource.read(source_buf, nnext);
  1810. finDestination.read(dest_buf, nnext);
  1811. // If either failed to read assume they are different.
  1812. if(static_cast<kwsys_ios::streamsize>(finSource.gcount()) != nnext ||
  1813. static_cast<kwsys_ios::streamsize>(finDestination.gcount()) != nnext)
  1814. {
  1815. return true;
  1816. }
  1817. // If this block differs the file differs.
  1818. if(memcmp(static_cast<const void*>(source_buf),
  1819. static_cast<const void*>(dest_buf),
  1820. static_cast<size_t>(nnext)) != 0)
  1821. {
  1822. return true;
  1823. }
  1824. // Update the byte count remaining.
  1825. nleft -= nnext;
  1826. }
  1827. // No differences found.
  1828. return false;
  1829. }
  1830. //----------------------------------------------------------------------------
  1831. /**
  1832. * Copy a file named by "source" to the file named by "destination".
  1833. */
  1834. bool SystemTools::CopyFileAlways(const char* source, const char* destination)
  1835. {
  1836. // If files are the same do not copy
  1837. if ( SystemTools::SameFile(source, destination) )
  1838. {
  1839. return true;
  1840. }
  1841. mode_t perm = 0;
  1842. bool perms = SystemTools::GetPermissions(source, perm);
  1843. const int bufferSize = 4096;
  1844. char buffer[bufferSize];
  1845. // If destination is a directory, try to create a file with the same
  1846. // name as the source in that directory.
  1847. kwsys_stl::string new_destination;
  1848. if(SystemTools::FileExists(destination) &&
  1849. SystemTools::FileIsDirectory(destination))
  1850. {
  1851. new_destination = destination;
  1852. SystemTools::ConvertToUnixSlashes(new_destination);
  1853. new_destination += '/';
  1854. kwsys_stl::string source_name = source;
  1855. new_destination += SystemTools::GetFilenameName(source_name);
  1856. destination = new_destination.c_str();
  1857. }
  1858. // Create destination directory
  1859. kwsys_stl::string destination_dir = destination;
  1860. destination_dir = SystemTools::GetFilenamePath(destination_dir);
  1861. SystemTools::MakeDirectory(destination_dir.c_str());
  1862. // Open files
  1863. #if defined(_WIN32) || defined(__CYGWIN__)
  1864. kwsys_ios::ifstream fin(source,
  1865. kwsys_ios::ios::binary | kwsys_ios::ios::in);
  1866. #else
  1867. kwsys_ios::ifstream fin(source);
  1868. #endif
  1869. if(!fin)
  1870. {
  1871. return false;
  1872. }
  1873. // try and remove the destination file so that read only destination files
  1874. // can be written to.
  1875. // If the remove fails continue so that files in read only directories
  1876. // that do not allow file removal can be modified.
  1877. SystemTools::RemoveFile(destination);
  1878. #if defined(_WIN32) || defined(__CYGWIN__)
  1879. kwsys_ios::ofstream fout(destination,
  1880. kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1881. #else
  1882. kwsys_ios::ofstream fout(destination,
  1883. kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1884. #endif
  1885. if(!fout)
  1886. {
  1887. return false;
  1888. }
  1889. // This copy loop is very sensitive on certain platforms with
  1890. // slightly broken stream libraries (like HPUX). Normally, it is
  1891. // incorrect to not check the error condition on the fin.read()
  1892. // before using the data, but the fin.gcount() will be zero if an
  1893. // error occurred. Therefore, the loop should be safe everywhere.
  1894. while(fin)
  1895. {
  1896. fin.read(buffer, bufferSize);
  1897. if(fin.gcount())
  1898. {
  1899. fout.write(buffer, fin.gcount());
  1900. }
  1901. }
  1902. // Make sure the operating system has finished writing the file
  1903. // before closing it. This will ensure the file is finished before
  1904. // the check below.
  1905. fout.flush();
  1906. fin.close();
  1907. fout.close();
  1908. if(!fout)
  1909. {
  1910. return false;
  1911. }
  1912. if ( perms )
  1913. {
  1914. if ( !SystemTools::SetPermissions(destination, perm) )
  1915. {
  1916. return false;
  1917. }
  1918. }
  1919. return true;
  1920. }
  1921. //----------------------------------------------------------------------------
  1922. bool SystemTools::CopyAFile(const char* source, const char* destination,
  1923. bool always)
  1924. {
  1925. if(always)
  1926. {
  1927. return SystemTools::CopyFileAlways(source, destination);
  1928. }
  1929. else
  1930. {
  1931. return SystemTools::CopyFileIfDifferent(source, destination);
  1932. }
  1933. }
  1934. /**
  1935. * Copy a directory content from "source" directory to the directory named by
  1936. * "destination".
  1937. */
  1938. bool SystemTools::CopyADirectory(const char* source, const char* destination,
  1939. bool always)
  1940. {
  1941. Directory dir;
  1942. dir.Load(source);
  1943. size_t fileNum;
  1944. if ( !SystemTools::MakeDirectory(destination) )
  1945. {
  1946. return false;
  1947. }
  1948. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1949. {
  1950. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1951. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1952. {
  1953. kwsys_stl::string fullPath = source;
  1954. fullPath += "/";
  1955. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1956. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  1957. {
  1958. kwsys_stl::string fullDestPath = destination;
  1959. fullDestPath += "/";
  1960. fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1961. if (!SystemTools::CopyADirectory(fullPath.c_str(),
  1962. fullDestPath.c_str(),
  1963. always))
  1964. {
  1965. return false;
  1966. }
  1967. }
  1968. else
  1969. {
  1970. if(!SystemTools::CopyAFile(fullPath.c_str(), destination, always))
  1971. {
  1972. return false;
  1973. }
  1974. }
  1975. }
  1976. }
  1977. return true;
  1978. }
  1979. // return size of file; also returns zero if no file exists
  1980. unsigned long SystemTools::FileLength(const char* filename)
  1981. {
  1982. struct stat fs;
  1983. if (stat(filename, &fs) != 0)
  1984. {
  1985. return 0;
  1986. }
  1987. else
  1988. {
  1989. return static_cast<unsigned long>(fs.st_size);
  1990. }
  1991. }
  1992. int SystemTools::Strucmp(const char *s1, const char *s2)
  1993. {
  1994. // lifted from Graphvis http://www.graphviz.org
  1995. while ((*s1 != '\0')
  1996. && (tolower(*s1) == tolower(*s2)))
  1997. {
  1998. s1++;
  1999. s2++;
  2000. }
  2001. return tolower(*s1) - tolower(*s2);
  2002. }
  2003. // return file's modified time
  2004. long int SystemTools::ModifiedTime(const char* filename)
  2005. {
  2006. struct stat fs;
  2007. if (stat(filename, &fs) != 0)
  2008. {
  2009. return 0;
  2010. }
  2011. else
  2012. {
  2013. return static_cast<long int>(fs.st_mtime);
  2014. }
  2015. }
  2016. // return file's creation time
  2017. long int SystemTools::CreationTime(const char* filename)
  2018. {
  2019. struct stat fs;
  2020. if (stat(filename, &fs) != 0)
  2021. {
  2022. return 0;
  2023. }
  2024. else
  2025. {
  2026. return fs.st_ctime >= 0 ? static_cast<long int>(fs.st_ctime) : 0;
  2027. }
  2028. }
  2029. bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
  2030. {
  2031. if (!str || !tmt || strlen(str) > 11)
  2032. {
  2033. return false;
  2034. }
  2035. struct tm tmt2;
  2036. // __DATE__
  2037. // The compilation date of the current source file. The date is a string
  2038. // literal of the form Mmm dd yyyy. The month name Mmm is the same as for
  2039. // dates generated by the library function asctime declared in TIME.H.
  2040. // index: 012345678901
  2041. // format: Mmm dd yyyy
  2042. // example: Dec 19 2003
  2043. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  2044. char buffer[12];
  2045. strcpy(buffer, str);
  2046. buffer[3] = 0;
  2047. char *ptr = strstr(month_names, buffer);
  2048. if (!ptr)
  2049. {
  2050. return false;
  2051. }
  2052. int month = static_cast<int>((ptr - month_names) / 3);
  2053. int day = atoi(buffer + 4);
  2054. int year = atoi(buffer + 7);
  2055. tmt2.tm_isdst = -1;
  2056. tmt2.tm_hour = 0;
  2057. tmt2.tm_min = 0;
  2058. tmt2.tm_sec = 0;
  2059. tmt2.tm_wday = 0;
  2060. tmt2.tm_yday = 0;
  2061. tmt2.tm_mday = day;
  2062. tmt2.tm_mon = month;
  2063. tmt2.tm_year = year - 1900;
  2064. *tmt = mktime(&tmt2);
  2065. return true;
  2066. }
  2067. bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
  2068. {
  2069. if (!str || !tmt || strlen(str) > 26)
  2070. {
  2071. return false;
  2072. }
  2073. struct tm tmt2;
  2074. // __TIMESTAMP__
  2075. // The date and time of the last modification of the current source file,
  2076. // expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy,
  2077. /// where Ddd is the abbreviated day of the week and Date is an integer
  2078. // from 1 to 31.
  2079. // index: 0123456789
  2080. // 0123456789
  2081. // 0123456789
  2082. // format: Ddd Mmm Date hh:mm:ss yyyy
  2083. // example: Fri Dec 19 14:34:58 2003
  2084. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  2085. char buffer[27];
  2086. strcpy(buffer, str);
  2087. buffer[7] = 0;
  2088. char *ptr = strstr(month_names, buffer + 4);
  2089. if (!ptr)
  2090. {
  2091. return false;
  2092. }
  2093. int month = static_cast<int>((ptr - month_names) / 3);
  2094. int day = atoi(buffer + 8);
  2095. int hour = atoi(buffer + 11);
  2096. int min = atoi(buffer + 14);
  2097. int sec = atoi(buffer + 17);
  2098. int year = atoi(buffer + 20);
  2099. tmt2.tm_isdst = -1;
  2100. tmt2.tm_hour = hour;
  2101. tmt2.tm_min = min;
  2102. tmt2.tm_sec = sec;
  2103. tmt2.tm_wday = 0;
  2104. tmt2.tm_yday = 0;
  2105. tmt2.tm_mday = day;
  2106. tmt2.tm_mon = month;
  2107. tmt2.tm_year = year - 1900;
  2108. *tmt = mktime(&tmt2);
  2109. return true;
  2110. }
  2111. kwsys_stl::string SystemTools::GetLastSystemError()
  2112. {
  2113. int e = errno;
  2114. return strerror(e);
  2115. }
  2116. bool SystemTools::RemoveFile(const char* source)
  2117. {
  2118. #ifdef _WIN32
  2119. mode_t mode;
  2120. if ( !SystemTools::GetPermissions(source, mode) )
  2121. {
  2122. return false;
  2123. }
  2124. /* Win32 unlink is stupid --- it fails if the file is read-only */
  2125. SystemTools::SetPermissions(source, S_IWRITE);
  2126. #endif
  2127. bool res = unlink(source) != 0 ? false : true;
  2128. #ifdef _WIN32
  2129. if ( !res )
  2130. {
  2131. SystemTools::SetPermissions(source, mode);
  2132. }
  2133. #endif
  2134. return res;
  2135. }
  2136. bool SystemTools::RemoveADirectory(const char* source)
  2137. {
  2138. // Add write permission to the directory so we can modify its
  2139. // content to remove files and directories from it.
  2140. mode_t mode;
  2141. if(SystemTools::GetPermissions(source, mode))
  2142. {
  2143. #if defined(_WIN32) && !defined(__CYGWIN__)
  2144. mode |= S_IWRITE;
  2145. #else
  2146. mode |= S_IWUSR;
  2147. #endif
  2148. SystemTools::SetPermissions(source, mode);
  2149. }
  2150. Directory dir;
  2151. dir.Load(source);
  2152. size_t fileNum;
  2153. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  2154. {
  2155. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  2156. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  2157. {
  2158. kwsys_stl::string fullPath = source;
  2159. fullPath += "/";
  2160. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  2161. if(SystemTools::FileIsDirectory(fullPath.c_str()) &&
  2162. !SystemTools::FileIsSymlink(fullPath.c_str()))
  2163. {
  2164. if (!SystemTools::RemoveADirectory(fullPath.c_str()))
  2165. {
  2166. return false;
  2167. }
  2168. }
  2169. else
  2170. {
  2171. if(!SystemTools::RemoveFile(fullPath.c_str()))
  2172. {
  2173. return false;
  2174. }
  2175. }
  2176. }
  2177. }
  2178. return (Rmdir(source) == 0);
  2179. }
  2180. /**
  2181. */
  2182. size_t SystemTools::GetMaximumFilePathLength()
  2183. {
  2184. return KWSYS_SYSTEMTOOLS_MAXPATH;
  2185. }
  2186. /**
  2187. * Find the file the given name. Searches the given path and then
  2188. * the system search path. Returns the full path to the file if it is
  2189. * found. Otherwise, the empty string is returned.
  2190. */
  2191. kwsys_stl::string SystemTools
  2192. ::FindName(const char* name,
  2193. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  2194. bool no_system_path)
  2195. {
  2196. // Add the system search path to our path first
  2197. kwsys_stl::vector<kwsys_stl::string> path;
  2198. if (!no_system_path)
  2199. {
  2200. SystemTools::GetPath(path, "CMAKE_FILE_PATH");
  2201. SystemTools::GetPath(path);
  2202. }
  2203. // now add the additional paths
  2204. {
  2205. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
  2206. i != userPaths.end(); ++i)
  2207. {
  2208. path.push_back(*i);
  2209. }
  2210. }
  2211. // Add a trailing slash to all paths to aid the search process.
  2212. {
  2213. for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
  2214. i != path.end(); ++i)
  2215. {
  2216. kwsys_stl::string& p = *i;
  2217. if(p.empty() || p[p.size()-1] != '/')
  2218. {
  2219. p += "/";
  2220. }
  2221. }
  2222. }
  2223. // now look for the file
  2224. kwsys_stl::string tryPath;
  2225. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  2226. p != path.end(); ++p)
  2227. {
  2228. tryPath = *p;
  2229. tryPath += name;
  2230. if(SystemTools::FileExists(tryPath.c_str()))
  2231. {
  2232. return tryPath;
  2233. }
  2234. }
  2235. // Couldn't find the file.
  2236. return "";
  2237. }
  2238. /**
  2239. * Find the file the given name. Searches the given path and then
  2240. * the system search path. Returns the full path to the file if it is
  2241. * found. Otherwise, the empty string is returned.
  2242. */
  2243. kwsys_stl::string SystemTools
  2244. ::FindFile(const char* name,
  2245. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  2246. bool no_system_path)
  2247. {
  2248. kwsys_stl::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
  2249. if(tryPath != "" && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2250. {
  2251. return SystemTools::CollapseFullPath(tryPath.c_str());
  2252. }
  2253. // Couldn't find the file.
  2254. return "";
  2255. }
  2256. /**
  2257. * Find the directory the given name. Searches the given path and then
  2258. * the system search path. Returns the full path to the directory if it is
  2259. * found. Otherwise, the empty string is returned.
  2260. */
  2261. kwsys_stl::string SystemTools
  2262. ::FindDirectory(const char* name,
  2263. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  2264. bool no_system_path)
  2265. {
  2266. kwsys_stl::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
  2267. if(tryPath != "" && SystemTools::FileIsDirectory(tryPath.c_str()))
  2268. {
  2269. return SystemTools::CollapseFullPath(tryPath.c_str());
  2270. }
  2271. // Couldn't find the file.
  2272. return "";
  2273. }
  2274. /**
  2275. * Find the executable with the given name. Searches the given path and then
  2276. * the system search path. Returns the full path to the executable if it is
  2277. * found. Otherwise, the empty string is returned.
  2278. */
  2279. kwsys_stl::string SystemTools::FindProgram(
  2280. const char* nameIn,
  2281. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  2282. bool no_system_path)
  2283. {
  2284. if(!nameIn || !*nameIn)
  2285. {
  2286. return "";
  2287. }
  2288. kwsys_stl::string name = nameIn;
  2289. kwsys_stl::vector<kwsys_stl::string> extensions;
  2290. #if defined (_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
  2291. bool hasExtension = false;
  2292. // check to see if the name already has a .xxx at
  2293. // the end of it
  2294. if(name.size() > 3 && name[name.size()-4] == '.')
  2295. {
  2296. hasExtension = true;
  2297. }
  2298. // on windows try .com then .exe
  2299. if(!hasExtension)
  2300. {
  2301. extensions.push_back(".com");
  2302. extensions.push_back(".exe");
  2303. }
  2304. #endif
  2305. kwsys_stl::string tryPath;
  2306. // first try with extensions if the os supports them
  2307. if(extensions.size())
  2308. {
  2309. for(kwsys_stl::vector<kwsys_stl::string>::iterator i =
  2310. extensions.begin(); i != extensions.end(); ++i)
  2311. {
  2312. tryPath = name;
  2313. tryPath += *i;
  2314. if(SystemTools::FileExists(tryPath.c_str()) &&
  2315. !SystemTools::FileIsDirectory(tryPath.c_str()))
  2316. {
  2317. return SystemTools::CollapseFullPath(tryPath.c_str());
  2318. }
  2319. }
  2320. }
  2321. // now try just the name
  2322. tryPath = name;
  2323. if(SystemTools::FileExists(tryPath.c_str()) &&
  2324. !SystemTools::FileIsDirectory(tryPath.c_str()))
  2325. {
  2326. return SystemTools::CollapseFullPath(tryPath.c_str());
  2327. }
  2328. // now construct the path
  2329. kwsys_stl::vector<kwsys_stl::string> path;
  2330. // Add the system search path to our path.
  2331. if (!no_system_path)
  2332. {
  2333. SystemTools::GetPath(path);
  2334. }
  2335. // now add the additional paths
  2336. {
  2337. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i =
  2338. userPaths.begin(); i != userPaths.end(); ++i)
  2339. {
  2340. path.push_back(*i);
  2341. }
  2342. }
  2343. // Add a trailing slash to all paths to aid the search process.
  2344. {
  2345. for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
  2346. i != path.end(); ++i)
  2347. {
  2348. kwsys_stl::string& p = *i;
  2349. if(p.empty() || p[p.size()-1] != '/')
  2350. {
  2351. p += "/";
  2352. }
  2353. }
  2354. }
  2355. // Try each path
  2356. for(kwsys_stl::vector<kwsys_stl::string>::iterator p = path.begin();
  2357. p != path.end(); ++p)
  2358. {
  2359. #ifdef _WIN32
  2360. // Remove double quotes from the path on windows
  2361. SystemTools::ReplaceString(*p, "\"", "");
  2362. #endif
  2363. // first try with extensions
  2364. if(extensions.size())
  2365. {
  2366. for(kwsys_stl::vector<kwsys_stl::string>::iterator ext
  2367. = extensions.begin(); ext != extensions.end(); ++ext)
  2368. {
  2369. tryPath = *p;
  2370. tryPath += name;
  2371. tryPath += *ext;
  2372. if(SystemTools::FileExists(tryPath.c_str()) &&
  2373. !SystemTools::FileIsDirectory(tryPath.c_str()))
  2374. {
  2375. return SystemTools::CollapseFullPath(tryPath.c_str());
  2376. }
  2377. }
  2378. }
  2379. // now try it without them
  2380. tryPath = *p;
  2381. tryPath += name;
  2382. if(SystemTools::FileExists(tryPath.c_str()) &&
  2383. !SystemTools::FileIsDirectory(tryPath.c_str()))
  2384. {
  2385. return SystemTools::CollapseFullPath(tryPath.c_str());
  2386. }
  2387. }
  2388. // Couldn't find the program.
  2389. return "";
  2390. }
  2391. kwsys_stl::string SystemTools::FindProgram(
  2392. const kwsys_stl::vector<kwsys_stl::string>& names,
  2393. const kwsys_stl::vector<kwsys_stl::string>& path,
  2394. bool noSystemPath)
  2395. {
  2396. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator it = names.begin();
  2397. it != names.end() ; ++it)
  2398. {
  2399. // Try to find the program.
  2400. kwsys_stl::string result = SystemTools::FindProgram(it->c_str(),
  2401. path,
  2402. noSystemPath);
  2403. if ( !result.empty() )
  2404. {
  2405. return result;
  2406. }
  2407. }
  2408. return "";
  2409. }
  2410. /**
  2411. * Find the library with the given name. Searches the given path and then
  2412. * the system search path. Returns the full path to the library if it is
  2413. * found. Otherwise, the empty string is returned.
  2414. */
  2415. kwsys_stl::string SystemTools
  2416. ::FindLibrary(const char* name,
  2417. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  2418. {
  2419. // See if the executable exists as written.
  2420. if(SystemTools::FileExists(name) &&
  2421. !SystemTools::FileIsDirectory(name))
  2422. {
  2423. return SystemTools::CollapseFullPath(name);
  2424. }
  2425. // Add the system search path to our path.
  2426. kwsys_stl::vector<kwsys_stl::string> path;
  2427. SystemTools::GetPath(path);
  2428. // now add the additional paths
  2429. {
  2430. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
  2431. i != userPaths.end(); ++i)
  2432. {
  2433. path.push_back(*i);
  2434. }
  2435. }
  2436. // Add a trailing slash to all paths to aid the search process.
  2437. {
  2438. for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
  2439. i != path.end(); ++i)
  2440. {
  2441. kwsys_stl::string& p = *i;
  2442. if(p.empty() || p[p.size()-1] != '/')
  2443. {
  2444. p += "/";
  2445. }
  2446. }
  2447. }
  2448. kwsys_stl::string tryPath;
  2449. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  2450. p != path.end(); ++p)
  2451. {
  2452. #if defined(__APPLE__)
  2453. tryPath = *p;
  2454. tryPath += name;
  2455. tryPath += ".framework";
  2456. if(SystemTools::FileExists(tryPath.c_str())
  2457. && SystemTools::FileIsDirectory(tryPath.c_str()))
  2458. {
  2459. return SystemTools::CollapseFullPath(tryPath.c_str());
  2460. }
  2461. #endif
  2462. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
  2463. tryPath = *p;
  2464. tryPath += name;
  2465. tryPath += ".lib";
  2466. if(SystemTools::FileExists(tryPath.c_str())
  2467. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2468. {
  2469. return SystemTools::CollapseFullPath(tryPath.c_str());
  2470. }
  2471. #else
  2472. tryPath = *p;
  2473. tryPath += "lib";
  2474. tryPath += name;
  2475. tryPath += ".so";
  2476. if(SystemTools::FileExists(tryPath.c_str())
  2477. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2478. {
  2479. return SystemTools::CollapseFullPath(tryPath.c_str());
  2480. }
  2481. tryPath = *p;
  2482. tryPath += "lib";
  2483. tryPath += name;
  2484. tryPath += ".a";
  2485. if(SystemTools::FileExists(tryPath.c_str())
  2486. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2487. {
  2488. return SystemTools::CollapseFullPath(tryPath.c_str());
  2489. }
  2490. tryPath = *p;
  2491. tryPath += "lib";
  2492. tryPath += name;
  2493. tryPath += ".sl";
  2494. if(SystemTools::FileExists(tryPath.c_str())
  2495. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2496. {
  2497. return SystemTools::CollapseFullPath(tryPath.c_str());
  2498. }
  2499. tryPath = *p;
  2500. tryPath += "lib";
  2501. tryPath += name;
  2502. tryPath += ".dylib";
  2503. if(SystemTools::FileExists(tryPath.c_str())
  2504. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2505. {
  2506. return SystemTools::CollapseFullPath(tryPath.c_str());
  2507. }
  2508. tryPath = *p;
  2509. tryPath += "lib";
  2510. tryPath += name;
  2511. tryPath += ".dll";
  2512. if(SystemTools::FileExists(tryPath.c_str())
  2513. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2514. {
  2515. return SystemTools::CollapseFullPath(tryPath.c_str());
  2516. }
  2517. #endif
  2518. }
  2519. // Couldn't find the library.
  2520. return "";
  2521. }
  2522. kwsys_stl::string SystemTools::GetRealPath(const char* path)
  2523. {
  2524. kwsys_stl::string ret;
  2525. Realpath(path, ret);
  2526. return ret;
  2527. }
  2528. bool SystemTools::FileIsDirectory(const char* name)
  2529. {
  2530. // Remove any trailing slash from the name.
  2531. char buffer[KWSYS_SYSTEMTOOLS_MAXPATH];
  2532. size_t last = strlen(name)-1;
  2533. if(last > 0 && (name[last] == '/' || name[last] == '\\')
  2534. && strcmp(name, "/") !=0)
  2535. {
  2536. memcpy(buffer, name, last);
  2537. buffer[last] = 0;
  2538. name = buffer;
  2539. }
  2540. // Now check the file node type.
  2541. struct stat fs;
  2542. if(stat(name, &fs) == 0)
  2543. {
  2544. #if defined( _WIN32 ) && !defined(__CYGWIN__)
  2545. return ((fs.st_mode & _S_IFDIR) != 0);
  2546. #else
  2547. return S_ISDIR(fs.st_mode);
  2548. #endif
  2549. }
  2550. else
  2551. {
  2552. return false;
  2553. }
  2554. }
  2555. bool SystemTools::FileIsSymlink(const char* name)
  2556. {
  2557. #if defined( _WIN32 )
  2558. (void)name;
  2559. return false;
  2560. #else
  2561. struct stat fs;
  2562. if(lstat(name, &fs) == 0)
  2563. {
  2564. return S_ISLNK(fs.st_mode);
  2565. }
  2566. else
  2567. {
  2568. return false;
  2569. }
  2570. #endif
  2571. }
  2572. #if defined(_WIN32) && !defined(__CYGWIN__)
  2573. bool SystemTools::CreateSymlink(const char*, const char*)
  2574. {
  2575. return false;
  2576. }
  2577. #else
  2578. bool SystemTools::CreateSymlink(const char* origName, const char* newName)
  2579. {
  2580. return symlink(origName, newName) >= 0;
  2581. }
  2582. #endif
  2583. #if defined(_WIN32) && !defined(__CYGWIN__)
  2584. bool SystemTools::ReadSymlink(const char*, kwsys_stl::string&)
  2585. {
  2586. return false;
  2587. }
  2588. #else
  2589. bool SystemTools::ReadSymlink(const char* newName,
  2590. kwsys_stl::string& origName)
  2591. {
  2592. char buf[KWSYS_SYSTEMTOOLS_MAXPATH+1];
  2593. int count =
  2594. static_cast<int>(readlink(newName, buf, KWSYS_SYSTEMTOOLS_MAXPATH));
  2595. if(count >= 0)
  2596. {
  2597. // Add null-terminator.
  2598. buf[count] = 0;
  2599. origName = buf;
  2600. return true;
  2601. }
  2602. else
  2603. {
  2604. return false;
  2605. }
  2606. }
  2607. #endif
  2608. int SystemTools::ChangeDirectory(const char *dir)
  2609. {
  2610. return Chdir(dir);
  2611. }
  2612. kwsys_stl::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
  2613. {
  2614. char buf[2048];
  2615. const char* cwd = Getcwd(buf, 2048);
  2616. kwsys_stl::string path;
  2617. if ( cwd )
  2618. {
  2619. path = cwd;
  2620. }
  2621. if(collapse)
  2622. {
  2623. return SystemTools::CollapseFullPath(path.c_str());
  2624. }
  2625. return path;
  2626. }
  2627. kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
  2628. {
  2629. kwsys_stl::string dir, file;
  2630. SystemTools::SplitProgramPath(in_name, dir, file);
  2631. return dir;
  2632. }
  2633. bool SystemTools::SplitProgramPath(const char* in_name,
  2634. kwsys_stl::string& dir,
  2635. kwsys_stl::string& file,
  2636. bool)
  2637. {
  2638. dir = in_name;
  2639. file = "";
  2640. SystemTools::ConvertToUnixSlashes(dir);
  2641. if(!SystemTools::FileIsDirectory(dir.c_str()))
  2642. {
  2643. kwsys_stl::string::size_type slashPos = dir.rfind("/");
  2644. if(slashPos != kwsys_stl::string::npos)
  2645. {
  2646. file = dir.substr(slashPos+1);
  2647. dir = dir.substr(0, slashPos);
  2648. }
  2649. else
  2650. {
  2651. file = dir;
  2652. dir = "";
  2653. }
  2654. }
  2655. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  2656. {
  2657. kwsys_stl::string oldDir = in_name;
  2658. SystemTools::ConvertToUnixSlashes(oldDir);
  2659. dir = in_name;
  2660. return false;
  2661. }
  2662. return true;
  2663. }
  2664. bool SystemTools::FindProgramPath(const char* argv0,
  2665. kwsys_stl::string& pathOut,
  2666. kwsys_stl::string& errorMsg,
  2667. const char* exeName,
  2668. const char* buildDir,
  2669. const char* installPrefix )
  2670. {
  2671. kwsys_stl::vector<kwsys_stl::string> failures;
  2672. kwsys_stl::string self = argv0 ? argv0 : "";
  2673. failures.push_back(self);
  2674. SystemTools::ConvertToUnixSlashes(self);
  2675. self = SystemTools::FindProgram(self.c_str());
  2676. if(!SystemTools::FileExists(self.c_str()))
  2677. {
  2678. if(buildDir)
  2679. {
  2680. kwsys_stl::string intdir = ".";
  2681. #ifdef CMAKE_INTDIR
  2682. intdir = CMAKE_INTDIR;
  2683. #endif
  2684. self = buildDir;
  2685. self += "/bin/";
  2686. self += intdir;
  2687. self += "/";
  2688. self += exeName;
  2689. self += SystemTools::GetExecutableExtension();
  2690. }
  2691. }
  2692. if(installPrefix)
  2693. {
  2694. if(!SystemTools::FileExists(self.c_str()))
  2695. {
  2696. failures.push_back(self);
  2697. self = installPrefix;
  2698. self += "/bin/";
  2699. self += exeName;
  2700. }
  2701. }
  2702. if(!SystemTools::FileExists(self.c_str()))
  2703. {
  2704. failures.push_back(self);
  2705. kwsys_ios::ostringstream msg;
  2706. msg << "Can not find the command line program ";
  2707. if (exeName)
  2708. {
  2709. msg << exeName;
  2710. }
  2711. msg << "\n";
  2712. if (argv0)
  2713. {
  2714. msg << " argv[0] = \"" << argv0 << "\"\n";
  2715. }
  2716. msg << " Attempted paths:\n";
  2717. kwsys_stl::vector<kwsys_stl::string>::iterator i;
  2718. for(i=failures.begin(); i != failures.end(); ++i)
  2719. {
  2720. msg << " \"" << i->c_str() << "\"\n";
  2721. }
  2722. errorMsg = msg.str();
  2723. return false;
  2724. }
  2725. pathOut = self;
  2726. return true;
  2727. }
  2728. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
  2729. {
  2730. return SystemTools::CollapseFullPath(in_relative, 0);
  2731. }
  2732. void SystemTools::AddTranslationPath(const char * a, const char * b)
  2733. {
  2734. kwsys_stl::string path_a = a;
  2735. kwsys_stl::string path_b = b;
  2736. SystemTools::ConvertToUnixSlashes(path_a);
  2737. SystemTools::ConvertToUnixSlashes(path_b);
  2738. // First check this is a directory path, since we don't want the table to
  2739. // grow too fat
  2740. if( SystemTools::FileIsDirectory( path_a.c_str() ) )
  2741. {
  2742. // Make sure the path is a full path and does not contain no '..'
  2743. // Ken--the following code is incorrect. .. can be in a valid path
  2744. // for example /home/martink/MyHubba...Hubba/Src
  2745. if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
  2746. == kwsys_stl::string::npos )
  2747. {
  2748. // Before inserting make sure path ends with '/'
  2749. if(path_a.size() && path_a[path_a.size() -1] != '/')
  2750. {
  2751. path_a += '/';
  2752. }
  2753. if(path_b.size() && path_b[path_b.size() -1] != '/')
  2754. {
  2755. path_b += '/';
  2756. }
  2757. if( !(path_a == path_b) )
  2758. {
  2759. SystemTools::TranslationMap->insert(
  2760. SystemToolsTranslationMap::value_type(path_a, path_b));
  2761. }
  2762. }
  2763. }
  2764. }
  2765. void SystemTools::AddKeepPath(const char* dir)
  2766. {
  2767. kwsys_stl::string cdir;
  2768. Realpath(SystemTools::CollapseFullPath(dir).c_str(), cdir);
  2769. SystemTools::AddTranslationPath(cdir.c_str(), dir);
  2770. }
  2771. void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
  2772. {
  2773. // Do not translate paths that are too short to have meaningful
  2774. // translations.
  2775. if(path.size() < 2)
  2776. {
  2777. return;
  2778. }
  2779. // Always add a trailing slash before translation. It does not
  2780. // matter if this adds an extra slash, but we do not want to
  2781. // translate part of a directory (like the foo part of foo-dir).
  2782. path += "/";
  2783. // In case a file was specified we still have to go through this:
  2784. // Now convert any path found in the table back to the one desired:
  2785. kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
  2786. for(it = SystemTools::TranslationMap->begin();
  2787. it != SystemTools::TranslationMap->end();
  2788. ++it )
  2789. {
  2790. // We need to check of the path is a substring of the other path
  2791. if(path.find( it->first ) == 0)
  2792. {
  2793. path = path.replace( 0, it->first.size(), it->second);
  2794. }
  2795. }
  2796. // Remove the trailing slash we added before.
  2797. path.erase(path.end()-1, path.end());
  2798. }
  2799. void
  2800. SystemToolsAppendComponents(
  2801. kwsys_stl::vector<kwsys_stl::string>& out_components,
  2802. kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
  2803. kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
  2804. {
  2805. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = first;
  2806. i != last; ++i)
  2807. {
  2808. if(*i == "..")
  2809. {
  2810. if(out_components.begin() != out_components.end())
  2811. {
  2812. out_components.erase(out_components.end()-1, out_components.end());
  2813. }
  2814. }
  2815. else if(!(*i == ".") && !(*i == ""))
  2816. {
  2817. out_components.push_back(*i);
  2818. }
  2819. }
  2820. }
  2821. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_path,
  2822. const char* in_base)
  2823. {
  2824. // Collect the output path components.
  2825. kwsys_stl::vector<kwsys_stl::string> out_components;
  2826. // Split the input path components.
  2827. kwsys_stl::vector<kwsys_stl::string> path_components;
  2828. SystemTools::SplitPath(in_path, path_components);
  2829. // If the input path is relative, start with a base path.
  2830. if(path_components[0].length() == 0)
  2831. {
  2832. kwsys_stl::vector<kwsys_stl::string> base_components;
  2833. if(in_base)
  2834. {
  2835. // Use the given base path.
  2836. SystemTools::SplitPath(in_base, base_components);
  2837. }
  2838. else
  2839. {
  2840. // Use the current working directory as a base path.
  2841. char buf[2048];
  2842. if(const char* cwd = Getcwd(buf, 2048))
  2843. {
  2844. SystemTools::SplitPath(cwd, base_components);
  2845. }
  2846. else
  2847. {
  2848. // ??
  2849. }
  2850. }
  2851. // Append base path components to the output path.
  2852. out_components.push_back(base_components[0]);
  2853. SystemToolsAppendComponents(out_components,
  2854. base_components.begin()+1,
  2855. base_components.end());
  2856. }
  2857. // Append input path components to the output path.
  2858. SystemToolsAppendComponents(out_components,
  2859. path_components.begin(),
  2860. path_components.end());
  2861. // Transform the path back to a string.
  2862. kwsys_stl::string newPath = SystemTools::JoinPath(out_components);
  2863. // Update the translation table with this potentially new path. I am not
  2864. // sure why this line is here, it seems really questionable, but yet I
  2865. // would put good money that if I remove it something will break, basically
  2866. // from what I can see it created a mapping from the collapsed path, to be
  2867. // replaced by the input path, which almost completely does the opposite of
  2868. // this function, the only thing preventing this from happening a lot is
  2869. // that if the in_path has a .. in it, then it is not added to the
  2870. // translation table. So for most calls this either does nothing due to the
  2871. // .. or it adds a translation between identical paths as nothing was
  2872. // collapsed, so I am going to try to comment it out, and see what hits the
  2873. // fan, hopefully quickly.
  2874. // Commented out line below:
  2875. //SystemTools::AddTranslationPath(newPath.c_str(), in_path);
  2876. SystemTools::CheckTranslationPath(newPath);
  2877. #ifdef _WIN32
  2878. newPath = SystemTools::GetActualCaseForPath(newPath.c_str());
  2879. SystemTools::ConvertToUnixSlashes(newPath);
  2880. #endif
  2881. // Return the reconstructed path.
  2882. return newPath;
  2883. }
  2884. // compute the relative path from here to there
  2885. kwsys_stl::string SystemTools::RelativePath(const char* local, const char* remote)
  2886. {
  2887. if(!SystemTools::FileIsFullPath(local))
  2888. {
  2889. return "";
  2890. }
  2891. if(!SystemTools::FileIsFullPath(remote))
  2892. {
  2893. return "";
  2894. }
  2895. // split up both paths into arrays of strings using / as a separator
  2896. kwsys_stl::vector<kwsys::String> localSplit = SystemTools::SplitString(local, '/', true);
  2897. kwsys_stl::vector<kwsys::String> remoteSplit = SystemTools::SplitString(remote, '/', true);
  2898. kwsys_stl::vector<kwsys::String> commonPath; // store shared parts of path in this array
  2899. kwsys_stl::vector<kwsys::String> finalPath; // store the final relative path here
  2900. // count up how many matching directory names there are from the start
  2901. unsigned int sameCount = 0;
  2902. while(
  2903. ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1)))
  2904. &&
  2905. // for windows and apple do a case insensitive string compare
  2906. #if defined(_WIN32) || defined(__APPLE__)
  2907. SystemTools::Strucmp(localSplit[sameCount].c_str(),
  2908. remoteSplit[sameCount].c_str()) == 0
  2909. #else
  2910. localSplit[sameCount] == remoteSplit[sameCount]
  2911. #endif
  2912. )
  2913. {
  2914. // put the common parts of the path into the commonPath array
  2915. commonPath.push_back(localSplit[sameCount]);
  2916. // erase the common parts of the path from the original path arrays
  2917. localSplit[sameCount] = "";
  2918. remoteSplit[sameCount] = "";
  2919. sameCount++;
  2920. }
  2921. // If there is nothing in common at all then just return the full
  2922. // path. This is the case only on windows when the paths have
  2923. // different drive letters. On unix two full paths always at least
  2924. // have the root "/" in common so we will return a relative path
  2925. // that passes through the root directory.
  2926. if(sameCount == 0)
  2927. {
  2928. return remote;
  2929. }
  2930. // for each entry that is not common in the local path
  2931. // add a ../ to the finalpath array, this gets us out of the local
  2932. // path into the remote dir
  2933. for(unsigned int i = 0; i < localSplit.size(); ++i)
  2934. {
  2935. if(localSplit[i].size())
  2936. {
  2937. finalPath.push_back("../");
  2938. }
  2939. }
  2940. // for each entry that is not common in the remote path add it
  2941. // to the final path.
  2942. for(kwsys_stl::vector<String>::iterator vit = remoteSplit.begin();
  2943. vit != remoteSplit.end(); ++vit)
  2944. {
  2945. if(vit->size())
  2946. {
  2947. finalPath.push_back(*vit);
  2948. }
  2949. }
  2950. kwsys_stl::string relativePath; // result string
  2951. // now turn the array of directories into a unix path by puttint /
  2952. // between each entry that does not already have one
  2953. for(kwsys_stl::vector<String>::iterator vit1 = finalPath.begin();
  2954. vit1 != finalPath.end(); ++vit1)
  2955. {
  2956. if(relativePath.size() && relativePath[relativePath.size()-1] != '/')
  2957. {
  2958. relativePath += "/";
  2959. }
  2960. relativePath += *vit1;
  2961. }
  2962. return relativePath;
  2963. }
  2964. #ifdef _WIN32
  2965. static int GetCasePathName(const kwsys_stl::string & pathIn,
  2966. kwsys_stl::string & casePath)
  2967. {
  2968. kwsys_stl::vector<kwsys_stl::string> path_components;
  2969. SystemTools::SplitPath(pathIn.c_str(), path_components);
  2970. if(path_components[0].empty()) // First component always exists.
  2971. {
  2972. // Relative paths cannot be converted.
  2973. casePath = "";
  2974. return 0;
  2975. }
  2976. // Start with root component.
  2977. kwsys_stl::vector<kwsys_stl::string>::size_type idx = 0;
  2978. casePath = path_components[idx++];
  2979. const char* sep = "";
  2980. // If network path, fill casePath with server/share so FindFirstFile
  2981. // will work after that. Maybe someday call other APIs to get
  2982. // actual case of servers and shares.
  2983. if(path_components.size() > 2 && path_components[0] == "//")
  2984. {
  2985. casePath += path_components[idx++];
  2986. casePath += "/";
  2987. casePath += path_components[idx++];
  2988. sep = "/";
  2989. }
  2990. for(; idx < path_components.size(); idx++)
  2991. {
  2992. casePath += sep;
  2993. sep = "/";
  2994. kwsys_stl::string test_str = casePath;
  2995. test_str += path_components[idx];
  2996. WIN32_FIND_DATA findData;
  2997. HANDLE hFind = ::FindFirstFile(test_str.c_str(), &findData);
  2998. if (INVALID_HANDLE_VALUE != hFind)
  2999. {
  3000. casePath += findData.cFileName;
  3001. ::FindClose(hFind);
  3002. }
  3003. else
  3004. {
  3005. casePath = "";
  3006. return 0;
  3007. }
  3008. }
  3009. return (int)casePath.size();
  3010. }
  3011. #endif
  3012. //----------------------------------------------------------------------------
  3013. kwsys_stl::string SystemTools::GetActualCaseForPath(const char* p)
  3014. {
  3015. #ifndef _WIN32
  3016. return p;
  3017. #else
  3018. kwsys_stl::string casePath = p;
  3019. // make sure drive letter is always upper case
  3020. if(casePath.size() > 1 && casePath[1] == ':')
  3021. {
  3022. casePath[0] = toupper(casePath[0]);
  3023. }
  3024. // Check to see if actual case has already been called
  3025. // for this path, and the result is stored in the LongPathMap
  3026. SystemToolsTranslationMap::iterator i =
  3027. SystemTools::LongPathMap->find(casePath);
  3028. if(i != SystemTools::LongPathMap->end())
  3029. {
  3030. return i->second;
  3031. }
  3032. int len = GetCasePathName(p, casePath);
  3033. if(len == 0 || len > MAX_PATH+1)
  3034. {
  3035. return p;
  3036. }
  3037. (*SystemTools::LongPathMap)[p] = casePath;
  3038. return casePath;
  3039. #endif
  3040. }
  3041. //----------------------------------------------------------------------------
  3042. const char* SystemTools::SplitPathRootComponent(const char* p,
  3043. kwsys_stl::string* root)
  3044. {
  3045. // Identify the root component.
  3046. const char* c = p;
  3047. if((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\'))
  3048. {
  3049. // Network path.
  3050. if(root)
  3051. {
  3052. *root = "//";
  3053. }
  3054. c += 2;
  3055. }
  3056. else if(c[0] == '/' || c[0] == '\\')
  3057. {
  3058. // Unix path (or Windows path w/out drive letter).
  3059. if(root)
  3060. {
  3061. *root = "/";
  3062. }
  3063. c += 1;
  3064. }
  3065. else if(c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\'))
  3066. {
  3067. // Windows path.
  3068. if(root)
  3069. {
  3070. (*root) = "_:/";
  3071. (*root)[0] = c[0];
  3072. }
  3073. c += 3;
  3074. }
  3075. else if(c[0] && c[1] == ':')
  3076. {
  3077. // Path relative to a windows drive working directory.
  3078. if(root)
  3079. {
  3080. (*root) = "_:";
  3081. (*root)[0] = c[0];
  3082. }
  3083. c += 2;
  3084. }
  3085. else if(c[0] == '~')
  3086. {
  3087. // Home directory. The returned root should always have a
  3088. // trailing slash so that appending components as
  3089. // c[0]c[1]/c[2]/... works. The remaining path returned should
  3090. // skip the first slash if it exists:
  3091. //
  3092. // "~" : root = "~/" , return ""
  3093. // "~/ : root = "~/" , return ""
  3094. // "~/x : root = "~/" , return "x"
  3095. // "~u" : root = "~u/", return ""
  3096. // "~u/" : root = "~u/", return ""
  3097. // "~u/x" : root = "~u/", return "x"
  3098. size_t n = 1;
  3099. while(c[n] && c[n] != '/')
  3100. {
  3101. ++n;
  3102. }
  3103. if(root)
  3104. {
  3105. root->assign(c, n);
  3106. *root += '/';
  3107. }
  3108. if(c[n] == '/')
  3109. {
  3110. ++n;
  3111. }
  3112. c += n;
  3113. }
  3114. else
  3115. {
  3116. // Relative path.
  3117. if(root)
  3118. {
  3119. *root = "";
  3120. }
  3121. }
  3122. // Return the remaining path.
  3123. return c;
  3124. }
  3125. //----------------------------------------------------------------------------
  3126. void SystemTools::SplitPath(const char* p,
  3127. kwsys_stl::vector<kwsys_stl::string>& components,
  3128. bool expand_home_dir)
  3129. {
  3130. const char* c = p;
  3131. components.clear();
  3132. // Identify the root component.
  3133. {
  3134. kwsys_stl::string root;
  3135. c = SystemTools::SplitPathRootComponent(c, &root);
  3136. // Expand home directory references if requested.
  3137. if(expand_home_dir && !root.empty() && root[0] == '~')
  3138. {
  3139. kwsys_stl::string homedir;
  3140. root = root.substr(0, root.size()-1);
  3141. if(root.size() == 1)
  3142. {
  3143. #if defined(_WIN32) && !defined(__CYGWIN__)
  3144. if(const char* userp = getenv("USERPROFILE"))
  3145. {
  3146. homedir = userp;
  3147. }
  3148. else
  3149. #endif
  3150. if(const char* h = getenv("HOME"))
  3151. {
  3152. homedir = h;
  3153. }
  3154. }
  3155. #ifdef HAVE_GETPWNAM
  3156. else if(passwd* pw = getpwnam(root.c_str()+1))
  3157. {
  3158. if(pw->pw_dir)
  3159. {
  3160. homedir = pw->pw_dir;
  3161. }
  3162. }
  3163. #endif
  3164. if(!homedir.empty() && (homedir[homedir.size()-1] == '/' ||
  3165. homedir[homedir.size()-1] == '\\'))
  3166. {
  3167. homedir = homedir.substr(0, homedir.size()-1);
  3168. }
  3169. SystemTools::SplitPath(homedir.c_str(), components);
  3170. }
  3171. else
  3172. {
  3173. components.push_back(root);
  3174. }
  3175. }
  3176. // Parse the remaining components.
  3177. const char* first = c;
  3178. const char* last = first;
  3179. for(;*last; ++last)
  3180. {
  3181. if(*last == '/' || *last == '\\')
  3182. {
  3183. // End of a component. Save it.
  3184. components.push_back(
  3185. kwsys_stl::string(first,static_cast<kwsys_stl::string::size_type>(
  3186. last-first)));
  3187. first = last+1;
  3188. }
  3189. }
  3190. // Save the last component unless there were no components.
  3191. if(last != c)
  3192. {
  3193. components.push_back(
  3194. kwsys_stl::string(first,static_cast<kwsys_stl::string::size_type>(
  3195. last-first)));
  3196. }
  3197. }
  3198. //----------------------------------------------------------------------------
  3199. kwsys_stl::string
  3200. SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components)
  3201. {
  3202. return SystemTools::JoinPath(components.begin(), components.end());
  3203. }
  3204. //----------------------------------------------------------------------------
  3205. kwsys_stl::string
  3206. SystemTools
  3207. ::JoinPath(kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
  3208. kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
  3209. {
  3210. // Construct result in a single string.
  3211. kwsys_stl::string result;
  3212. // The first two components do not add a slash.
  3213. if(first != last)
  3214. {
  3215. result.append(*first++);
  3216. }
  3217. if(first != last)
  3218. {
  3219. result.append(*first++);
  3220. }
  3221. // All remaining components are always separated with a slash.
  3222. while(first != last)
  3223. {
  3224. result.append("/");
  3225. result.append((*first++));
  3226. }
  3227. // Return the concatenated result.
  3228. return result;
  3229. }
  3230. //----------------------------------------------------------------------------
  3231. bool SystemTools::ComparePath(const char* c1, const char* c2)
  3232. {
  3233. #if defined(_WIN32) || defined(__APPLE__)
  3234. # ifdef _MSC_VER
  3235. return _stricmp(c1, c2) == 0;
  3236. # elif defined(__APPLE__) || defined(__GNUC__)
  3237. return strcasecmp(c1, c2) == 0;
  3238. #else
  3239. return SystemTools::Strucmp(c1, c2) == 0;
  3240. # endif
  3241. #else
  3242. return strcmp(c1, c2) == 0;
  3243. #endif
  3244. }
  3245. //----------------------------------------------------------------------------
  3246. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines, char separator)
  3247. {
  3248. kwsys_stl::string data(str);
  3249. kwsys_stl::string::size_type lpos = 0;
  3250. while(lpos < data.length())
  3251. {
  3252. kwsys_stl::string::size_type rpos = data.find_first_of(separator, lpos);
  3253. if(rpos == kwsys_stl::string::npos)
  3254. {
  3255. // Line ends at end of string without a newline.
  3256. lines.push_back(data.substr(lpos));
  3257. return false;
  3258. }
  3259. else
  3260. {
  3261. // Line ends in a "\n", remove the character.
  3262. lines.push_back(data.substr(lpos, rpos-lpos));
  3263. }
  3264. lpos = rpos+1;
  3265. }
  3266. return true;
  3267. }
  3268. //----------------------------------------------------------------------------
  3269. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
  3270. {
  3271. kwsys_stl::string data(str);
  3272. kwsys_stl::string::size_type lpos = 0;
  3273. while(lpos < data.length())
  3274. {
  3275. kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
  3276. if(rpos == kwsys_stl::string::npos)
  3277. {
  3278. // Line ends at end of string without a newline.
  3279. lines.push_back(data.substr(lpos));
  3280. return false;
  3281. }
  3282. if((rpos > lpos) && (data[rpos-1] == '\r'))
  3283. {
  3284. // Line ends in a "\r\n" pair, remove both characters.
  3285. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  3286. }
  3287. else
  3288. {
  3289. // Line ends in a "\n", remove the character.
  3290. lines.push_back(data.substr(lpos, rpos-lpos));
  3291. }
  3292. lpos = rpos+1;
  3293. }
  3294. return true;
  3295. }
  3296. /**
  3297. * Return path of a full filename (no trailing slashes).
  3298. * Warning: returned path is converted to Unix slashes format.
  3299. */
  3300. kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
  3301. {
  3302. kwsys_stl::string fn = filename;
  3303. SystemTools::ConvertToUnixSlashes(fn);
  3304. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  3305. if(slash_pos != kwsys_stl::string::npos)
  3306. {
  3307. kwsys_stl::string ret = fn.substr(0, slash_pos);
  3308. if(ret.size() == 2 && ret[1] == ':')
  3309. {
  3310. return ret + '/';
  3311. }
  3312. if(ret.size() == 0)
  3313. {
  3314. return "/";
  3315. }
  3316. return ret;
  3317. }
  3318. else
  3319. {
  3320. return "";
  3321. }
  3322. }
  3323. /**
  3324. * Return file name of a full filename (i.e. file name without path).
  3325. */
  3326. kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
  3327. {
  3328. #if defined(_WIN32)
  3329. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/\\");
  3330. #else
  3331. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/");
  3332. #endif
  3333. if(slash_pos != kwsys_stl::string::npos)
  3334. {
  3335. return filename.substr(slash_pos + 1);
  3336. }
  3337. else
  3338. {
  3339. return filename;
  3340. }
  3341. }
  3342. /**
  3343. * Return file extension of a full filename (dot included).
  3344. * Warning: this is the longest extension (for example: .tar.gz)
  3345. */
  3346. kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
  3347. {
  3348. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  3349. kwsys_stl::string::size_type dot_pos = name.find(".");
  3350. if(dot_pos != kwsys_stl::string::npos)
  3351. {
  3352. return name.substr(dot_pos);
  3353. }
  3354. else
  3355. {
  3356. return "";
  3357. }
  3358. }
  3359. /**
  3360. * Return file extension of a full filename (dot included).
  3361. * Warning: this is the shortest extension (for example: .gz of .tar.gz)
  3362. */
  3363. kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
  3364. {
  3365. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  3366. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  3367. if(dot_pos != kwsys_stl::string::npos)
  3368. {
  3369. return name.substr(dot_pos);
  3370. }
  3371. else
  3372. {
  3373. return "";
  3374. }
  3375. }
  3376. /**
  3377. * Return file name without extension of a full filename (i.e. without path).
  3378. * Warning: it considers the longest extension (for example: .tar.gz)
  3379. */
  3380. kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
  3381. {
  3382. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  3383. kwsys_stl::string::size_type dot_pos = name.find(".");
  3384. if(dot_pos != kwsys_stl::string::npos)
  3385. {
  3386. return name.substr(0, dot_pos);
  3387. }
  3388. else
  3389. {
  3390. return name;
  3391. }
  3392. }
  3393. /**
  3394. * Return file name without extension of a full filename (i.e. without path).
  3395. * Warning: it considers the last extension (for example: removes .gz
  3396. * from .tar.gz)
  3397. */
  3398. kwsys_stl::string
  3399. SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
  3400. {
  3401. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  3402. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  3403. if(dot_pos != kwsys_stl::string::npos)
  3404. {
  3405. return name.substr(0, dot_pos);
  3406. }
  3407. else
  3408. {
  3409. return name;
  3410. }
  3411. }
  3412. bool SystemTools::FileHasSignature(const char *filename,
  3413. const char *signature,
  3414. long offset)
  3415. {
  3416. if (!filename || !signature)
  3417. {
  3418. return false;
  3419. }
  3420. FILE *fp;
  3421. fp = fopen(filename, "rb");
  3422. if (!fp)
  3423. {
  3424. return false;
  3425. }
  3426. fseek(fp, offset, SEEK_SET);
  3427. bool res = false;
  3428. size_t signature_len = strlen(signature);
  3429. char *buffer = new char [signature_len];
  3430. if (fread(buffer, 1, signature_len, fp) == signature_len)
  3431. {
  3432. res = (!strncmp(buffer, signature, signature_len) ? true : false);
  3433. }
  3434. delete [] buffer;
  3435. fclose(fp);
  3436. return res;
  3437. }
  3438. SystemTools::FileTypeEnum
  3439. SystemTools::DetectFileType(const char *filename,
  3440. unsigned long length,
  3441. double percent_bin)
  3442. {
  3443. if (!filename || percent_bin < 0)
  3444. {
  3445. return SystemTools::FileTypeUnknown;
  3446. }
  3447. FILE *fp;
  3448. fp = fopen(filename, "rb");
  3449. if (!fp)
  3450. {
  3451. return SystemTools::FileTypeUnknown;
  3452. }
  3453. // Allocate buffer and read bytes
  3454. unsigned char *buffer = new unsigned char [length];
  3455. size_t read_length = fread(buffer, 1, length, fp);
  3456. fclose(fp);
  3457. if (read_length == 0)
  3458. {
  3459. return SystemTools::FileTypeUnknown;
  3460. }
  3461. // Loop over contents and count
  3462. size_t text_count = 0;
  3463. const unsigned char *ptr = buffer;
  3464. const unsigned char *buffer_end = buffer + read_length;
  3465. while (ptr != buffer_end)
  3466. {
  3467. if ((*ptr >= 0x20 && *ptr <= 0x7F) ||
  3468. *ptr == '\n' ||
  3469. *ptr == '\r' ||
  3470. *ptr == '\t')
  3471. {
  3472. text_count++;
  3473. }
  3474. ptr++;
  3475. }
  3476. delete [] buffer;
  3477. double current_percent_bin =
  3478. (static_cast<double>(read_length - text_count) /
  3479. static_cast<double>(read_length));
  3480. if (current_percent_bin >= percent_bin)
  3481. {
  3482. return SystemTools::FileTypeBinary;
  3483. }
  3484. return SystemTools::FileTypeText;
  3485. }
  3486. bool SystemTools::LocateFileInDir(const char *filename,
  3487. const char *dir,
  3488. kwsys_stl::string& filename_found,
  3489. int try_filename_dirs)
  3490. {
  3491. if (!filename || !dir)
  3492. {
  3493. return false;
  3494. }
  3495. // Get the basename of 'filename'
  3496. kwsys_stl::string filename_base = SystemTools::GetFilenameName(filename);
  3497. // Check if 'dir' is really a directory
  3498. // If win32 and matches something like C:, accept it as a dir
  3499. kwsys_stl::string real_dir;
  3500. if (!SystemTools::FileIsDirectory(dir))
  3501. {
  3502. #if defined( _WIN32 )
  3503. size_t dir_len = strlen(dir);
  3504. if (dir_len < 2 || dir[dir_len - 1] != ':')
  3505. {
  3506. #endif
  3507. real_dir = SystemTools::GetFilenamePath(dir);
  3508. dir = real_dir.c_str();
  3509. #if defined( _WIN32 )
  3510. }
  3511. #endif
  3512. }
  3513. // Try to find the file in 'dir'
  3514. bool res = false;
  3515. if (filename_base.size() && dir)
  3516. {
  3517. size_t dir_len = strlen(dir);
  3518. int need_slash =
  3519. (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
  3520. kwsys_stl::string temp = dir;
  3521. if (need_slash)
  3522. {
  3523. temp += "/";
  3524. }
  3525. temp += filename_base;
  3526. if (SystemTools::FileExists(temp.c_str()))
  3527. {
  3528. res = true;
  3529. filename_found = temp;
  3530. }
  3531. // If not found, we can try harder by appending part of the file to
  3532. // to the directory to look inside.
  3533. // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
  3534. // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
  3535. else if (try_filename_dirs)
  3536. {
  3537. kwsys_stl::string filename_dir(filename);
  3538. kwsys_stl::string filename_dir_base;
  3539. kwsys_stl::string filename_dir_bases;
  3540. do
  3541. {
  3542. filename_dir = SystemTools::GetFilenamePath(filename_dir);
  3543. filename_dir_base = SystemTools::GetFilenameName(filename_dir);
  3544. #if defined( _WIN32 )
  3545. if (!filename_dir_base.size() ||
  3546. filename_dir_base[filename_dir_base.size() - 1] == ':')
  3547. #else
  3548. if (!filename_dir_base.size())
  3549. #endif
  3550. {
  3551. break;
  3552. }
  3553. filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
  3554. temp = dir;
  3555. if (need_slash)
  3556. {
  3557. temp += "/";
  3558. }
  3559. temp += filename_dir_bases;
  3560. res = SystemTools::LocateFileInDir(
  3561. filename_base.c_str(), temp.c_str(), filename_found, 0);
  3562. } while (!res && filename_dir_base.size());
  3563. }
  3564. }
  3565. return res;
  3566. }
  3567. bool SystemTools::FileIsFullPath(const char* in_name)
  3568. {
  3569. kwsys_stl::string name = in_name;
  3570. #if defined(_WIN32) || defined(__CYGWIN__)
  3571. // On Windows, the name must be at least two characters long.
  3572. if(name.length() < 2)
  3573. {
  3574. return false;
  3575. }
  3576. if(name[1] == ':')
  3577. {
  3578. return true;
  3579. }
  3580. if(name[0] == '\\')
  3581. {
  3582. return true;
  3583. }
  3584. #else
  3585. // On UNIX, the name must be at least one character long.
  3586. if(name.length() < 1)
  3587. {
  3588. return false;
  3589. }
  3590. #endif
  3591. #if !defined(_WIN32)
  3592. if(name[0] == '~')
  3593. {
  3594. return true;
  3595. }
  3596. #endif
  3597. // On UNIX, the name must begin in a '/'.
  3598. // On Windows, if the name begins in a '/', then it is a full
  3599. // network path.
  3600. if(name[0] == '/')
  3601. {
  3602. return true;
  3603. }
  3604. return false;
  3605. }
  3606. bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
  3607. {
  3608. #if defined(WIN32) && !defined(__CYGWIN__)
  3609. const int size = int(strlen(path)) +1; // size of return
  3610. char *buffer = new char[size]; // create a buffer
  3611. char *tempPath = new char[size]; // create a buffer
  3612. int ret;
  3613. // if the path passed in has quotes around it, first remove the quotes
  3614. if (path[0] == '"' && path[strlen(path)-1] == '"')
  3615. {
  3616. strcpy(tempPath,path+1);
  3617. tempPath[strlen(tempPath)-1] = '\0';
  3618. }
  3619. else
  3620. {
  3621. strcpy(tempPath,path);
  3622. }
  3623. buffer[0] = 0;
  3624. ret = GetShortPathName(tempPath, buffer, size);
  3625. if(buffer[0] == 0 || ret > size)
  3626. {
  3627. delete [] buffer;
  3628. delete [] tempPath;
  3629. return false;
  3630. }
  3631. else
  3632. {
  3633. shortPath = buffer;
  3634. delete [] buffer;
  3635. delete [] tempPath;
  3636. return true;
  3637. }
  3638. #else
  3639. shortPath = path;
  3640. return true;
  3641. #endif
  3642. }
  3643. void SystemTools::SplitProgramFromArgs(const char* path,
  3644. kwsys_stl::string& program, kwsys_stl::string& args)
  3645. {
  3646. // see if this is a full path to a program
  3647. // if so then set program to path and args to nothing
  3648. if(SystemTools::FileExists(path))
  3649. {
  3650. program = path;
  3651. args = "";
  3652. return;
  3653. }
  3654. // Try to find the program in the path, note the program
  3655. // may have spaces in its name so we have to look for it
  3656. kwsys_stl::vector<kwsys_stl::string> e;
  3657. kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
  3658. if(findProg.size())
  3659. {
  3660. program = findProg;
  3661. args = "";
  3662. return;
  3663. }
  3664. // Now try and peel off space separated chunks from the end of the string
  3665. // so the largest path possible is found allowing for spaces in the path
  3666. kwsys_stl::string dir = path;
  3667. kwsys_stl::string::size_type spacePos = dir.rfind(' ');
  3668. while(spacePos != kwsys_stl::string::npos)
  3669. {
  3670. kwsys_stl::string tryProg = dir.substr(0, spacePos);
  3671. // See if the file exists
  3672. if(SystemTools::FileExists(tryProg.c_str()))
  3673. {
  3674. program = tryProg;
  3675. // remove trailing spaces from program
  3676. kwsys_stl::string::size_type pos = program.size()-1;
  3677. while(program[pos] == ' ')
  3678. {
  3679. program.erase(pos);
  3680. pos--;
  3681. }
  3682. args = dir.substr(spacePos, dir.size()-spacePos);
  3683. return;
  3684. }
  3685. // Now try and find the the program in the path
  3686. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  3687. if(findProg.size())
  3688. {
  3689. program = findProg;
  3690. // remove trailing spaces from program
  3691. kwsys_stl::string::size_type pos = program.size()-1;
  3692. while(program[pos] == ' ')
  3693. {
  3694. program.erase(pos);
  3695. pos--;
  3696. }
  3697. args = dir.substr(spacePos, dir.size()-spacePos);
  3698. return;
  3699. }
  3700. // move past the space for the next search
  3701. spacePos--;
  3702. spacePos = dir.rfind(' ', spacePos);
  3703. }
  3704. program = "";
  3705. args = "";
  3706. }
  3707. kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
  3708. {
  3709. char buf[1024];
  3710. time_t t;
  3711. time(&t);
  3712. strftime(buf, sizeof(buf), format, localtime(&t));
  3713. return kwsys_stl::string(buf);
  3714. }
  3715. kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
  3716. {
  3717. kwsys_stl::string str(s);
  3718. if (str.find_first_of("0123456789") == 0)
  3719. {
  3720. str = "_" + str;
  3721. }
  3722. kwsys_stl::string permited_chars("_"
  3723. "abcdefghijklmnopqrstuvwxyz"
  3724. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3725. "0123456789");
  3726. kwsys_stl::string::size_type pos = 0;
  3727. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
  3728. {
  3729. str[pos] = '_';
  3730. }
  3731. return str;
  3732. }
  3733. // Due to a buggy stream library on the HP and another on Mac OS X, we
  3734. // need this very carefully written version of getline. Returns true
  3735. // if any data were read before the end-of-file was reached.
  3736. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is,
  3737. kwsys_stl::string& line,
  3738. bool* has_newline /* = 0 */,
  3739. long sizeLimit /* = -1 */)
  3740. {
  3741. const int bufferSize = 1024;
  3742. char buffer[bufferSize];
  3743. bool haveData = false;
  3744. bool haveNewline = false;
  3745. // Start with an empty line.
  3746. line = "";
  3747. long leftToRead = sizeLimit;
  3748. // Early short circuit return if stream is no good. Just return
  3749. // false and the empty line. (Probably means caller tried to
  3750. // create a file stream with a non-existent file name...)
  3751. //
  3752. if(!is)
  3753. {
  3754. if(has_newline)
  3755. {
  3756. *has_newline = false;
  3757. }
  3758. return false;
  3759. }
  3760. // If no characters are read from the stream, the end of file has
  3761. // been reached. Clear the fail bit just before reading.
  3762. while(!haveNewline &&
  3763. leftToRead != 0 &&
  3764. (is.clear(is.rdstate() & ~kwsys_ios::ios::failbit),
  3765. is.getline(buffer, bufferSize), is.gcount() > 0))
  3766. {
  3767. // We have read at least one byte.
  3768. haveData = true;
  3769. // If newline character was read the gcount includes the character
  3770. // but the buffer does not: the end of line has been reached.
  3771. size_t length = strlen(buffer);
  3772. if(length < static_cast<size_t>(is.gcount()))
  3773. {
  3774. haveNewline = true;
  3775. }
  3776. // Avoid storing a carriage return character.
  3777. if(length > 0 && buffer[length-1] == '\r')
  3778. {
  3779. buffer[length-1] = 0;
  3780. }
  3781. // if we read too much then truncate the buffer
  3782. if (leftToRead > 0)
  3783. {
  3784. if (static_cast<long>(length) > leftToRead)
  3785. {
  3786. buffer[leftToRead-1] = 0;
  3787. leftToRead = 0;
  3788. }
  3789. else
  3790. {
  3791. leftToRead -= static_cast<long>(length);
  3792. }
  3793. }
  3794. // Append the data read to the line.
  3795. line.append(buffer);
  3796. }
  3797. // Return the results.
  3798. if(has_newline)
  3799. {
  3800. *has_newline = haveNewline;
  3801. }
  3802. return haveData;
  3803. }
  3804. int SystemTools::GetTerminalWidth()
  3805. {
  3806. int width = -1;
  3807. #ifdef HAVE_TTY_INFO
  3808. struct winsize ws;
  3809. char *columns; /* Unix98 environment variable */
  3810. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  3811. {
  3812. width = ws.ws_col;
  3813. }
  3814. if(!isatty(STDOUT_FILENO))
  3815. {
  3816. width = -1;
  3817. }
  3818. columns = getenv("COLUMNS");
  3819. if(columns && *columns)
  3820. {
  3821. long t;
  3822. char *endptr;
  3823. t = strtol(columns, &endptr, 0);
  3824. if(endptr && !*endptr && (t>0) && (t<1000))
  3825. {
  3826. width = static_cast<int>(t);
  3827. }
  3828. }
  3829. if ( width < 9 )
  3830. {
  3831. width = -1;
  3832. }
  3833. #endif
  3834. return width;
  3835. }
  3836. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  3837. {
  3838. if ( !file )
  3839. {
  3840. return false;
  3841. }
  3842. struct stat st;
  3843. if ( stat(file, &st) < 0 )
  3844. {
  3845. return false;
  3846. }
  3847. mode = st.st_mode;
  3848. return true;
  3849. }
  3850. bool SystemTools::SetPermissions(const char* file, mode_t mode)
  3851. {
  3852. if ( !file )
  3853. {
  3854. return false;
  3855. }
  3856. if ( !SystemTools::FileExists(file) )
  3857. {
  3858. return false;
  3859. }
  3860. if ( chmod(file, mode) < 0 )
  3861. {
  3862. return false;
  3863. }
  3864. return true;
  3865. }
  3866. kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
  3867. {
  3868. return SystemTools::GetFilenamePath(fileOrDir);
  3869. }
  3870. bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
  3871. {
  3872. if(!*cDir)
  3873. {
  3874. return false;
  3875. }
  3876. kwsys_stl::string subdir = cSubdir;
  3877. kwsys_stl::string dir = cDir;
  3878. SystemTools::ConvertToUnixSlashes(dir);
  3879. kwsys_stl::string path = subdir;
  3880. do
  3881. {
  3882. path = SystemTools::GetParentDirectory(path.c_str());
  3883. if(SystemTools::ComparePath(dir.c_str(), path.c_str()))
  3884. {
  3885. return true;
  3886. }
  3887. }
  3888. while ( path.size() > dir.size() );
  3889. return false;
  3890. }
  3891. void SystemTools::Delay(unsigned int msec)
  3892. {
  3893. #ifdef _WIN32
  3894. Sleep(msec);
  3895. #else
  3896. // The sleep function gives 1 second resolution and the usleep
  3897. // function gives 1e-6 second resolution but on some platforms has a
  3898. // maximum sleep time of 1 second. This could be re-implemented to
  3899. // use select with masked signals or pselect to mask signals
  3900. // atomically. If select is given empty sets and zero as the max
  3901. // file descriptor but a non-zero timeout it can be used to block
  3902. // for a precise amount of time.
  3903. if(msec >= 1000)
  3904. {
  3905. sleep(msec / 1000);
  3906. usleep((msec % 1000) * 1000);
  3907. }
  3908. else
  3909. {
  3910. usleep(msec * 1000);
  3911. }
  3912. #endif
  3913. }
  3914. void SystemTools::ConvertWindowsCommandLineToUnixArguments(
  3915. const char *cmd_line, int *argc, char ***argv)
  3916. {
  3917. if (!cmd_line || !argc || !argv)
  3918. {
  3919. return;
  3920. }
  3921. // A space delimites an argument except when it is inside a quote
  3922. (*argc) = 1;
  3923. size_t cmd_line_len = strlen(cmd_line);
  3924. size_t i;
  3925. for (i = 0; i < cmd_line_len; i++)
  3926. {
  3927. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3928. {
  3929. i++;
  3930. }
  3931. if (i < cmd_line_len)
  3932. {
  3933. if (cmd_line[i] == '\"')
  3934. {
  3935. i++;
  3936. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3937. {
  3938. i++;
  3939. }
  3940. (*argc)++;
  3941. }
  3942. else
  3943. {
  3944. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3945. {
  3946. i++;
  3947. }
  3948. (*argc)++;
  3949. }
  3950. }
  3951. }
  3952. (*argv) = new char* [(*argc) + 1];
  3953. (*argv)[(*argc)] = NULL;
  3954. // Set the first arg to be the exec name
  3955. (*argv)[0] = new char [1024];
  3956. #ifdef _WIN32
  3957. ::GetModuleFileName(0, (*argv)[0], 1024);
  3958. #else
  3959. (*argv)[0][0] = '\0';
  3960. #endif
  3961. // Allocate the others
  3962. int j;
  3963. for (j = 1; j < (*argc); j++)
  3964. {
  3965. (*argv)[j] = new char [cmd_line_len + 10];
  3966. }
  3967. // Grab the args
  3968. size_t pos;
  3969. int argc_idx = 1;
  3970. for (i = 0; i < cmd_line_len; i++)
  3971. {
  3972. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3973. {
  3974. i++;
  3975. }
  3976. if (i < cmd_line_len)
  3977. {
  3978. if (cmd_line[i] == '\"')
  3979. {
  3980. i++;
  3981. pos = i;
  3982. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3983. {
  3984. i++;
  3985. }
  3986. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3987. (*argv)[argc_idx][i - pos] = '\0';
  3988. argc_idx++;
  3989. }
  3990. else
  3991. {
  3992. pos = i;
  3993. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3994. {
  3995. i++;
  3996. }
  3997. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3998. (*argv)[argc_idx][i - pos] = '\0';
  3999. argc_idx++;
  4000. }
  4001. }
  4002. }
  4003. }
  4004. kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
  4005. {
  4006. kwsys_stl::string res;
  4007. #ifdef _WIN32
  4008. char buffer[256];
  4009. OSVERSIONINFOEX osvi;
  4010. BOOL bOsVersionInfoEx;
  4011. // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
  4012. // If that fails, try using the OSVERSIONINFO structure.
  4013. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  4014. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  4015. bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi);
  4016. if (!bOsVersionInfoEx)
  4017. {
  4018. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  4019. if (!GetVersionEx((OSVERSIONINFO *)&osvi))
  4020. {
  4021. return 0;
  4022. }
  4023. }
  4024. switch (osvi.dwPlatformId)
  4025. {
  4026. // Test for the Windows NT product family.
  4027. case VER_PLATFORM_WIN32_NT:
  4028. // Test for the specific product family.
  4029. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
  4030. {
  4031. #if (_MSC_VER >= 1300)
  4032. if (osvi.wProductType == VER_NT_WORKSTATION)
  4033. {
  4034. res += "Microsoft Windows Vista";
  4035. }
  4036. else
  4037. {
  4038. res += "Microsoft Windows Server 2008 family";
  4039. }
  4040. #else
  4041. res += "Microsoft Windows Vista or Windows Server 2008";
  4042. #endif
  4043. }
  4044. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  4045. {
  4046. res += "Microsoft Windows Server 2003 family";
  4047. }
  4048. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  4049. {
  4050. res += "Microsoft Windows XP";
  4051. }
  4052. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  4053. {
  4054. res += "Microsoft Windows 2000";
  4055. }
  4056. if (osvi.dwMajorVersion <= 4)
  4057. {
  4058. res += "Microsoft Windows NT";
  4059. }
  4060. // Test for specific product on Windows NT 4.0 SP6 and later.
  4061. if (bOsVersionInfoEx)
  4062. {
  4063. // Test for the workstation type.
  4064. #if (_MSC_VER >= 1300)
  4065. if (osvi.wProductType == VER_NT_WORKSTATION)
  4066. {
  4067. if (osvi.dwMajorVersion == 4)
  4068. {
  4069. res += " Workstation 4.0";
  4070. }
  4071. else if (osvi.dwMajorVersion == 5)
  4072. {
  4073. if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
  4074. {
  4075. res += " Home Edition";
  4076. }
  4077. else
  4078. {
  4079. res += " Professional";
  4080. }
  4081. }
  4082. }
  4083. // Test for the server type.
  4084. else if (osvi.wProductType == VER_NT_SERVER)
  4085. {
  4086. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  4087. {
  4088. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  4089. {
  4090. res += " Datacenter Edition";
  4091. }
  4092. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  4093. {
  4094. res += " Enterprise Edition";
  4095. }
  4096. else if (osvi.wSuiteMask == VER_SUITE_BLADE)
  4097. {
  4098. res += " Web Edition";
  4099. }
  4100. else
  4101. {
  4102. res += " Standard Edition";
  4103. }
  4104. }
  4105. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  4106. {
  4107. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  4108. {
  4109. res += " Datacenter Server";
  4110. }
  4111. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  4112. {
  4113. res += " Advanced Server";
  4114. }
  4115. else
  4116. {
  4117. res += " Server";
  4118. }
  4119. }
  4120. else if (osvi.dwMajorVersion <= 4) // Windows NT 4.0
  4121. {
  4122. if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  4123. {
  4124. res += " Server 4.0, Enterprise Edition";
  4125. }
  4126. else
  4127. {
  4128. res += " Server 4.0";
  4129. }
  4130. }
  4131. }
  4132. #endif // Visual Studio 7 and up
  4133. }
  4134. // Test for specific product on Windows NT 4.0 SP5 and earlier
  4135. else
  4136. {
  4137. HKEY hKey;
  4138. #define BUFSIZE 80
  4139. char szProductType[BUFSIZE];
  4140. DWORD dwBufLen=BUFSIZE;
  4141. LONG lRet;
  4142. lRet = RegOpenKeyEx(
  4143. HKEY_LOCAL_MACHINE,
  4144. "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
  4145. 0, KEY_QUERY_VALUE, &hKey);
  4146. if (lRet != ERROR_SUCCESS)
  4147. {
  4148. return 0;
  4149. }
  4150. lRet = RegQueryValueEx(hKey, "ProductType", NULL, NULL,
  4151. (LPBYTE) szProductType, &dwBufLen);
  4152. if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))
  4153. {
  4154. return 0;
  4155. }
  4156. RegCloseKey(hKey);
  4157. if (lstrcmpi("WINNT", szProductType) == 0)
  4158. {
  4159. res += " Workstation";
  4160. }
  4161. if (lstrcmpi("LANMANNT", szProductType) == 0)
  4162. {
  4163. res += " Server";
  4164. }
  4165. if (lstrcmpi("SERVERNT", szProductType) == 0)
  4166. {
  4167. res += " Advanced Server";
  4168. }
  4169. res += " ";
  4170. sprintf(buffer, "%ld", osvi.dwMajorVersion);
  4171. res += buffer;
  4172. res += ".";
  4173. sprintf(buffer, "%ld", osvi.dwMinorVersion);
  4174. res += buffer;
  4175. }
  4176. // Display service pack (if any) and build number.
  4177. if (osvi.dwMajorVersion == 4 &&
  4178. lstrcmpi(osvi.szCSDVersion, "Service Pack 6") == 0)
  4179. {
  4180. HKEY hKey;
  4181. LONG lRet;
  4182. // Test for SP6 versus SP6a.
  4183. lRet = RegOpenKeyEx(
  4184. HKEY_LOCAL_MACHINE,
  4185. "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
  4186. 0, KEY_QUERY_VALUE, &hKey);
  4187. if (lRet == ERROR_SUCCESS)
  4188. {
  4189. res += " Service Pack 6a (Build ";
  4190. sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
  4191. res += buffer;
  4192. res += ")";
  4193. }
  4194. else // Windows NT 4.0 prior to SP6a
  4195. {
  4196. res += " ";
  4197. res += osvi.szCSDVersion;
  4198. res += " (Build ";
  4199. sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
  4200. res += buffer;
  4201. res += ")";
  4202. }
  4203. RegCloseKey(hKey);
  4204. }
  4205. else // Windows NT 3.51 and earlier or Windows 2000 and later
  4206. {
  4207. res += " ";
  4208. res += osvi.szCSDVersion;
  4209. res += " (Build ";
  4210. sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
  4211. res += buffer;
  4212. res += ")";
  4213. }
  4214. break;
  4215. // Test for the Windows 95 product family.
  4216. case VER_PLATFORM_WIN32_WINDOWS:
  4217. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
  4218. {
  4219. res += "Microsoft Windows 95";
  4220. if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
  4221. {
  4222. res += " OSR2";
  4223. }
  4224. }
  4225. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
  4226. {
  4227. res += "Microsoft Windows 98";
  4228. if (osvi.szCSDVersion[1] == 'A')
  4229. {
  4230. res += " SE";
  4231. }
  4232. }
  4233. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
  4234. {
  4235. res += "Microsoft Windows Millennium Edition";
  4236. }
  4237. break;
  4238. case VER_PLATFORM_WIN32s:
  4239. res += "Microsoft Win32s";
  4240. break;
  4241. }
  4242. #endif
  4243. return res;
  4244. }
  4245. // ----------------------------------------------------------------------
  4246. bool SystemTools::ParseURLProtocol( const kwsys_stl::string& URL,
  4247. kwsys_stl::string& protocol,
  4248. kwsys_stl::string& dataglom )
  4249. {
  4250. // match 0 entire url
  4251. // match 1 protocol
  4252. // match 2 dataglom following protocol://
  4253. kwsys::RegularExpression urlRe( VTK_URL_PROTOCOL_REGEX );
  4254. if ( ! urlRe.find( URL ) ) return false;
  4255. protocol = urlRe.match( 1 );
  4256. dataglom = urlRe.match( 2 );
  4257. return true;
  4258. }
  4259. // ----------------------------------------------------------------------
  4260. bool SystemTools::ParseURL( const kwsys_stl::string& URL,
  4261. kwsys_stl::string& protocol,
  4262. kwsys_stl::string& username,
  4263. kwsys_stl::string& password,
  4264. kwsys_stl::string& hostname,
  4265. kwsys_stl::string& dataport,
  4266. kwsys_stl::string& database )
  4267. {
  4268. kwsys::RegularExpression urlRe( VTK_URL_REGEX );
  4269. if ( ! urlRe.find( URL ) ) return false;
  4270. // match 0 URL
  4271. // match 1 protocol
  4272. // match 2 mangled user
  4273. // match 3 username
  4274. // match 4 mangled password
  4275. // match 5 password
  4276. // match 6 hostname
  4277. // match 7 mangled port
  4278. // match 8 dataport
  4279. // match 9 database name
  4280. protocol = urlRe.match( 1 );
  4281. username = urlRe.match( 3 );
  4282. password = urlRe.match( 5 );
  4283. hostname = urlRe.match( 6 );
  4284. dataport = urlRe.match( 8 );
  4285. database = urlRe.match( 9 );
  4286. return true;
  4287. }
  4288. // ----------------------------------------------------------------------
  4289. // These must NOT be initialized. Default initialization to zero is
  4290. // necessary.
  4291. unsigned int SystemToolsManagerCount;
  4292. SystemToolsTranslationMap *SystemTools::TranslationMap;
  4293. SystemToolsTranslationMap *SystemTools::LongPathMap;
  4294. #ifdef __CYGWIN__
  4295. SystemToolsTranslationMap *SystemTools::Cyg2Win32Map;
  4296. #endif
  4297. // SystemToolsManager manages the SystemTools singleton.
  4298. // SystemToolsManager should be included in any translation unit
  4299. // that will use SystemTools or that implements the singleton
  4300. // pattern. It makes sure that the SystemTools singleton is created
  4301. // before and destroyed after all other singletons in CMake.
  4302. SystemToolsManager::SystemToolsManager()
  4303. {
  4304. if(++SystemToolsManagerCount == 1)
  4305. {
  4306. SystemTools::ClassInitialize();
  4307. }
  4308. }
  4309. SystemToolsManager::~SystemToolsManager()
  4310. {
  4311. if(--SystemToolsManagerCount == 0)
  4312. {
  4313. SystemTools::ClassFinalize();
  4314. }
  4315. }
  4316. #if defined(__VMS)
  4317. // On VMS we configure the run time C library to be more UNIX like.
  4318. // http://h71000.www7.hp.com/doc/732final/5763/5763pro_004.html
  4319. extern "C" int decc$feature_get_index(char *name);
  4320. extern "C" int decc$feature_set_value(int index, int mode, int value);
  4321. static int SetVMSFeature(char* name, int value)
  4322. {
  4323. int i;
  4324. errno = 0;
  4325. i = decc$feature_get_index(name);
  4326. return i >= 0 && (decc$feature_set_value(i, 1, value) >= 0 || errno == 0);
  4327. }
  4328. #endif
  4329. void SystemTools::ClassInitialize()
  4330. {
  4331. #ifdef __VMS
  4332. SetVMSFeature("DECC$FILENAME_UNIX_ONLY", 1);
  4333. #endif
  4334. // Allocate the translation map first.
  4335. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  4336. SystemTools::LongPathMap = new SystemToolsTranslationMap;
  4337. #ifdef __CYGWIN__
  4338. SystemTools::Cyg2Win32Map = new SystemToolsTranslationMap;
  4339. #endif
  4340. // Add some special translation paths for unix. These are not added
  4341. // for windows because drive letters need to be maintained. Also,
  4342. // there are not sym-links and mount points on windows anyway.
  4343. #if !defined(_WIN32) || defined(__CYGWIN__)
  4344. // The tmp path is frequently a logical path so always keep it:
  4345. SystemTools::AddKeepPath("/tmp/");
  4346. // If the current working directory is a logical path then keep the
  4347. // logical name.
  4348. if(const char* pwd = getenv("PWD"))
  4349. {
  4350. char buf[2048];
  4351. if(const char* cwd = Getcwd(buf, 2048))
  4352. {
  4353. // The current working directory may be a logical path. Find
  4354. // the shortest logical path that still produces the correct
  4355. // physical path.
  4356. kwsys_stl::string cwd_changed;
  4357. kwsys_stl::string pwd_changed;
  4358. // Test progressively shorter logical-to-physical mappings.
  4359. kwsys_stl::string pwd_str = pwd;
  4360. kwsys_stl::string cwd_str = cwd;
  4361. kwsys_stl::string pwd_path;
  4362. Realpath(pwd, pwd_path);
  4363. while(cwd_str == pwd_path && cwd_str != pwd_str)
  4364. {
  4365. // The current pair of paths is a working logical mapping.
  4366. cwd_changed = cwd_str;
  4367. pwd_changed = pwd_str;
  4368. // Strip off one directory level and see if the logical
  4369. // mapping still works.
  4370. pwd_str = SystemTools::GetFilenamePath(pwd_str.c_str());
  4371. cwd_str = SystemTools::GetFilenamePath(cwd_str.c_str());
  4372. Realpath(pwd_str.c_str(), pwd_path);
  4373. }
  4374. // Add the translation to keep the logical path name.
  4375. if(!cwd_changed.empty() && !pwd_changed.empty())
  4376. {
  4377. SystemTools::AddTranslationPath(cwd_changed.c_str(),
  4378. pwd_changed.c_str());
  4379. }
  4380. }
  4381. }
  4382. #endif
  4383. }
  4384. void SystemTools::ClassFinalize()
  4385. {
  4386. delete SystemTools::TranslationMap;
  4387. delete SystemTools::LongPathMap;
  4388. #ifdef __CYGWIN__
  4389. delete SystemTools::Cyg2Win32Map;
  4390. #endif
  4391. }
  4392. } // namespace KWSYS_NAMESPACE
  4393. #if defined(_MSC_VER) && defined(_DEBUG)
  4394. # include <crtdbg.h>
  4395. # include <stdio.h>
  4396. # include <stdlib.h>
  4397. namespace KWSYS_NAMESPACE
  4398. {
  4399. static int SystemToolsDebugReport(int, char* message, int*)
  4400. {
  4401. fprintf(stderr, "%s", message);
  4402. fflush(stderr);
  4403. return 1; // no further reporting required
  4404. }
  4405. void SystemTools::EnableMSVCDebugHook()
  4406. {
  4407. if (getenv("DART_TEST_FROM_DART"))
  4408. {
  4409. _CrtSetReportHook(SystemToolsDebugReport);
  4410. }
  4411. }
  4412. } // namespace KWSYS_NAMESPACE
  4413. #else
  4414. namespace KWSYS_NAMESPACE
  4415. {
  4416. void SystemTools::EnableMSVCDebugHook() {}
  4417. } // namespace KWSYS_NAMESPACE
  4418. #endif