SystemTools.cxx 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692
  1. /*=========================================================================
  2. Program: KWSys - Kitware System Library
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
  8. See http://www.cmake.org/HTML/Copyright.html for details.
  9. This software is distributed WITHOUT ANY WARRANTY; without even
  10. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  11. PURPOSE. See the above copyright notices for more information.
  12. =========================================================================*/
  13. #include "kwsysPrivate.h"
  14. #include KWSYS_HEADER(SystemTools.hxx)
  15. #include KWSYS_HEADER(std/iostream)
  16. #include KWSYS_HEADER(std/fstream)
  17. #ifdef _MSC_VER
  18. # pragma warning (disable: 4786)
  19. #endif
  20. #include <stdio.h>
  21. #include <sys/stat.h>
  22. #include <ctype.h>
  23. #include <errno.h>
  24. #include <time.h>
  25. // support for realpath call
  26. #ifndef _WIN32
  27. #include <limits.h>
  28. #include <stdlib.h>
  29. #include <sys/param.h>
  30. #include <sys/wait.h>
  31. #endif
  32. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__))
  33. #include <string.h>
  34. #include <windows.h>
  35. #include <direct.h>
  36. #define _unlink unlink
  37. inline int Mkdir(const char* dir)
  38. {
  39. return _mkdir(dir);
  40. }
  41. inline const char* Getcwd(char* buf, unsigned int len)
  42. {
  43. return _getcwd(buf, len);
  44. }
  45. inline int Chdir(const char* dir)
  46. {
  47. #if defined(__BORLANDC__)
  48. return chdir(dir);
  49. #else
  50. return _chdir(dir);
  51. #endif
  52. }
  53. #else
  54. #include <sys/types.h>
  55. #include <fcntl.h>
  56. #include <unistd.h>
  57. inline int Mkdir(const char* dir)
  58. {
  59. return mkdir(dir, 00777);
  60. }
  61. inline const char* Getcwd(char* buf, unsigned int len)
  62. {
  63. return getcwd(buf, len);
  64. }
  65. inline int Chdir(const char* dir)
  66. {
  67. return chdir(dir);
  68. }
  69. #endif
  70. #if !defined(_WIN32) && defined(__COMO__)
  71. // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
  72. extern "C"
  73. {
  74. extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
  75. extern int pclose (FILE *__stream) __THROW;
  76. extern char *realpath (__const char *__restrict __name,
  77. char *__restrict __resolved) __THROW;
  78. extern char *strdup (__const char *__s) __THROW;
  79. extern int putenv (char *__string) __THROW;
  80. }
  81. #endif
  82. /* Implement floattime() for various platforms */
  83. // Taken from Python 2.1.3
  84. #if defined( _WIN32 ) && !defined( __CYGWIN__ )
  85. # include <sys/timeb.h>
  86. # define HAVE_FTIME
  87. # if defined( __BORLANDC__)
  88. # define FTIME ftime
  89. # define TIMEB timeb
  90. # else // Visual studio?
  91. # define FTIME _ftime
  92. # define TIMEB _timeb
  93. # endif
  94. #elif defined( __CYGWIN__ ) || defined( __linux__ )
  95. # include <sys/time.h>
  96. # include <time.h>
  97. # define HAVE_GETTIMEOFDAY
  98. #endif
  99. namespace KWSYS_NAMESPACE
  100. {
  101. double
  102. SystemTools::GetTime(void)
  103. {
  104. /* There are three ways to get the time:
  105. (1) gettimeofday() -- resolution in microseconds
  106. (2) ftime() -- resolution in milliseconds
  107. (3) time() -- resolution in seconds
  108. In all cases the return value is a float in seconds.
  109. Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
  110. fail, so we fall back on ftime() or time().
  111. Note: clock resolution does not imply clock accuracy! */
  112. #ifdef HAVE_GETTIMEOFDAY
  113. {
  114. struct timeval t;
  115. #ifdef GETTIMEOFDAY_NO_TZ
  116. if (gettimeofday(&t) == 0)
  117. return (double)t.tv_sec + t.tv_usec*0.000001;
  118. #else /* !GETTIMEOFDAY_NO_TZ */
  119. if (gettimeofday(&t, (struct timezone *)NULL) == 0)
  120. return (double)t.tv_sec + t.tv_usec*0.000001;
  121. #endif /* !GETTIMEOFDAY_NO_TZ */
  122. }
  123. #endif /* !HAVE_GETTIMEOFDAY */
  124. {
  125. #if defined(HAVE_FTIME)
  126. struct TIMEB t;
  127. FTIME(&t);
  128. return (double)t.time + (double)t.millitm * (double)0.001;
  129. #else /* !HAVE_FTIME */
  130. time_t secs;
  131. time(&secs);
  132. return (double)secs;
  133. #endif /* !HAVE_FTIME */
  134. }
  135. }
  136. // adds the elements of the env variable path to the arg passed in
  137. void SystemTools::GetPath(kwsys_std::vector<kwsys_std::string>& path)
  138. {
  139. #if defined(_WIN32) && !defined(__CYGWIN__)
  140. const char* pathSep = ";";
  141. #else
  142. const char* pathSep = ":";
  143. #endif
  144. kwsys_std::string pathEnv = getenv("PATH");
  145. // A hack to make the below algorithm work.
  146. if(pathEnv[pathEnv.length()-1] != ':')
  147. {
  148. pathEnv += pathSep;
  149. }
  150. kwsys_std::string::size_type start =0;
  151. bool done = false;
  152. while(!done)
  153. {
  154. kwsys_std::string::size_type endpos = pathEnv.find(pathSep, start);
  155. if(endpos != kwsys_std::string::npos)
  156. {
  157. path.push_back(pathEnv.substr(start, endpos-start));
  158. start = endpos+1;
  159. }
  160. else
  161. {
  162. done = true;
  163. }
  164. }
  165. for(kwsys_std::vector<kwsys_std::string>::iterator i = path.begin();
  166. i != path.end(); ++i)
  167. {
  168. SystemTools::ConvertToUnixSlashes(*i);
  169. }
  170. }
  171. const char* SystemTools::GetExecutableExtension()
  172. {
  173. #if defined(_WIN32) || defined(__CYGWIN__)
  174. return ".exe";
  175. #else
  176. return "";
  177. #endif
  178. }
  179. bool SystemTools::MakeDirectory(const char* path)
  180. {
  181. if(SystemTools::FileExists(path))
  182. {
  183. return true;
  184. }
  185. kwsys_std::string dir = path;
  186. if(dir.size() == 0)
  187. {
  188. return false;
  189. }
  190. SystemTools::ConvertToUnixSlashes(dir);
  191. kwsys_std::string::size_type pos = dir.find(':');
  192. if(pos == kwsys_std::string::npos)
  193. {
  194. pos = 0;
  195. }
  196. kwsys_std::string topdir;
  197. while((pos = dir.find('/', pos)) != kwsys_std::string::npos)
  198. {
  199. topdir = dir.substr(0, pos);
  200. Mkdir(topdir.c_str());
  201. pos++;
  202. }
  203. if(dir[dir.size()-1] == '/')
  204. {
  205. topdir = dir.substr(0, dir.size());
  206. }
  207. else
  208. {
  209. topdir = dir;
  210. }
  211. if(Mkdir(topdir.c_str()) != 0)
  212. {
  213. // There is a bug in the Borland Run time library which makes MKDIR
  214. // return EACCES when it should return EEXISTS
  215. // if it is some other error besides directory exists
  216. // then return false
  217. if( (errno != EEXIST)
  218. #ifdef __BORLANDC__
  219. && (errno != EACCES)
  220. #endif
  221. )
  222. {
  223. return false;
  224. }
  225. }
  226. return true;
  227. }
  228. // replace replace with with as many times as it shows up in source.
  229. // write the result into source.
  230. void SystemTools::ReplaceString(kwsys_std::string& source,
  231. const char* replace,
  232. const char* with)
  233. {
  234. const char *src = source.c_str();
  235. char *searchPos = const_cast<char *>(strstr(src,replace));
  236. // get out quick if string is not found
  237. if (!searchPos)
  238. {
  239. return;
  240. }
  241. // perform replacements until done
  242. size_t replaceSize = strlen(replace);
  243. char *orig = strdup(src);
  244. char *currentPos = orig;
  245. searchPos = searchPos - src + orig;
  246. // initialize the result
  247. source.erase(source.begin(),source.end());
  248. do
  249. {
  250. *searchPos = '\0';
  251. source += currentPos;
  252. currentPos = searchPos + replaceSize;
  253. // replace
  254. source += with;
  255. searchPos = strstr(currentPos,replace);
  256. }
  257. while (searchPos);
  258. // copy any trailing text
  259. source += currentPos;
  260. free(orig);
  261. }
  262. // Read a registry value.
  263. // Example :
  264. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  265. // => will return the data of the "default" value of the key
  266. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  267. // => will return the data of the "Root" value of the key
  268. #if defined(_WIN32) && !defined(__CYGWIN__)
  269. bool SystemTools::ReadRegistryValue(const char *key, kwsys_std::string &value)
  270. {
  271. kwsys_std::string primary = key;
  272. kwsys_std::string second;
  273. kwsys_std::string valuename;
  274. size_t start = primary.find("\\");
  275. if (start == kwsys_std::string::npos)
  276. {
  277. return false;
  278. }
  279. size_t valuenamepos = primary.find(";");
  280. if (valuenamepos != kwsys_std::string::npos)
  281. {
  282. valuename = primary.substr(valuenamepos+1);
  283. }
  284. second = primary.substr(start+1, valuenamepos-start-1);
  285. primary = primary.substr(0, start);
  286. HKEY primaryKey;
  287. if (primary == "HKEY_CURRENT_USER")
  288. {
  289. primaryKey = HKEY_CURRENT_USER;
  290. }
  291. if (primary == "HKEY_CURRENT_CONFIG")
  292. {
  293. primaryKey = HKEY_CURRENT_CONFIG;
  294. }
  295. if (primary == "HKEY_CLASSES_ROOT")
  296. {
  297. primaryKey = HKEY_CLASSES_ROOT;
  298. }
  299. if (primary == "HKEY_LOCAL_MACHINE")
  300. {
  301. primaryKey = HKEY_LOCAL_MACHINE;
  302. }
  303. if (primary == "HKEY_USERS")
  304. {
  305. primaryKey = HKEY_USERS;
  306. }
  307. HKEY hKey;
  308. if(RegOpenKeyEx(primaryKey,
  309. second.c_str(),
  310. 0,
  311. KEY_READ,
  312. &hKey) != ERROR_SUCCESS)
  313. {
  314. return false;
  315. }
  316. else
  317. {
  318. DWORD dwType, dwSize;
  319. dwSize = 1023;
  320. char data[1024];
  321. if(RegQueryValueEx(hKey,
  322. (LPTSTR)valuename.c_str(),
  323. NULL,
  324. &dwType,
  325. (BYTE *)data,
  326. &dwSize) == ERROR_SUCCESS)
  327. {
  328. if (dwType == REG_SZ)
  329. {
  330. value = data;
  331. return true;
  332. }
  333. }
  334. }
  335. return false;
  336. }
  337. #else
  338. bool SystemTools::ReadRegistryValue(const char *, kwsys_std::string &)
  339. {
  340. return false;
  341. }
  342. #endif
  343. // Write a registry value.
  344. // Example :
  345. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  346. // => will set the data of the "default" value of the key
  347. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  348. // => will set the data of the "Root" value of the key
  349. #if defined(_WIN32) && !defined(__CYGWIN__)
  350. bool SystemTools::WriteRegistryValue(const char *key, const char *value)
  351. {
  352. kwsys_std::string primary = key;
  353. kwsys_std::string second;
  354. kwsys_std::string valuename;
  355. size_t start = primary.find("\\");
  356. if (start == kwsys_std::string::npos)
  357. {
  358. return false;
  359. }
  360. size_t valuenamepos = primary.find(";");
  361. if (valuenamepos != kwsys_std::string::npos)
  362. {
  363. valuename = primary.substr(valuenamepos+1);
  364. }
  365. second = primary.substr(start+1, valuenamepos-start-1);
  366. primary = primary.substr(0, start);
  367. HKEY primaryKey;
  368. if (primary == "HKEY_CURRENT_USER")
  369. {
  370. primaryKey = HKEY_CURRENT_USER;
  371. }
  372. if (primary == "HKEY_CURRENT_CONFIG")
  373. {
  374. primaryKey = HKEY_CURRENT_CONFIG;
  375. }
  376. if (primary == "HKEY_CLASSES_ROOT")
  377. {
  378. primaryKey = HKEY_CLASSES_ROOT;
  379. }
  380. if (primary == "HKEY_LOCAL_MACHINE")
  381. {
  382. primaryKey = HKEY_LOCAL_MACHINE;
  383. }
  384. if (primary == "HKEY_USERS")
  385. {
  386. primaryKey = HKEY_USERS;
  387. }
  388. HKEY hKey;
  389. DWORD dwDummy;
  390. if(RegCreateKeyEx(primaryKey,
  391. second.c_str(),
  392. 0,
  393. "",
  394. REG_OPTION_NON_VOLATILE,
  395. KEY_WRITE,
  396. NULL,
  397. &hKey,
  398. &dwDummy) != ERROR_SUCCESS)
  399. {
  400. return false;
  401. }
  402. if(RegSetValueEx(hKey,
  403. (LPTSTR)valuename.c_str(),
  404. 0,
  405. REG_SZ,
  406. (CONST BYTE *)value,
  407. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  408. {
  409. return true;
  410. }
  411. return false;
  412. }
  413. #else
  414. bool SystemTools::WriteRegistryValue(const char *, const char *)
  415. {
  416. return false;
  417. }
  418. #endif
  419. // Delete a registry value.
  420. // Example :
  421. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  422. // => will delete the data of the "default" value of the key
  423. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  424. // => will delete the data of the "Root" value of the key
  425. #if defined(_WIN32) && !defined(__CYGWIN__)
  426. bool SystemTools::DeleteRegistryValue(const char *key)
  427. {
  428. kwsys_std::string primary = key;
  429. kwsys_std::string second;
  430. kwsys_std::string valuename;
  431. size_t start = primary.find("\\");
  432. if (start == kwsys_std::string::npos)
  433. {
  434. return false;
  435. }
  436. size_t valuenamepos = primary.find(";");
  437. if (valuenamepos != kwsys_std::string::npos)
  438. {
  439. valuename = primary.substr(valuenamepos+1);
  440. }
  441. second = primary.substr(start+1, valuenamepos-start-1);
  442. primary = primary.substr(0, start);
  443. HKEY primaryKey;
  444. if (primary == "HKEY_CURRENT_USER")
  445. {
  446. primaryKey = HKEY_CURRENT_USER;
  447. }
  448. if (primary == "HKEY_CURRENT_CONFIG")
  449. {
  450. primaryKey = HKEY_CURRENT_CONFIG;
  451. }
  452. if (primary == "HKEY_CLASSES_ROOT")
  453. {
  454. primaryKey = HKEY_CLASSES_ROOT;
  455. }
  456. if (primary == "HKEY_LOCAL_MACHINE")
  457. {
  458. primaryKey = HKEY_LOCAL_MACHINE;
  459. }
  460. if (primary == "HKEY_USERS")
  461. {
  462. primaryKey = HKEY_USERS;
  463. }
  464. HKEY hKey;
  465. if(RegOpenKeyEx(primaryKey,
  466. second.c_str(),
  467. 0,
  468. KEY_WRITE,
  469. &hKey) != ERROR_SUCCESS)
  470. {
  471. return false;
  472. }
  473. else
  474. {
  475. if(RegDeleteValue(hKey,
  476. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  477. {
  478. return true;
  479. }
  480. }
  481. return false;
  482. }
  483. #else
  484. bool SystemTools::DeleteRegistryValue(const char *)
  485. {
  486. return false;
  487. }
  488. #endif
  489. bool SystemTools::SameFile(const char* file1, const char* file2)
  490. {
  491. #ifdef _WIN32
  492. HANDLE hFile1, hFile2;
  493. hFile1 = CreateFile( file1,
  494. GENERIC_READ,
  495. FILE_SHARE_READ ,
  496. NULL,
  497. OPEN_EXISTING,
  498. FILE_FLAG_BACKUP_SEMANTICS,
  499. NULL
  500. );
  501. hFile2 = CreateFile( file2,
  502. GENERIC_READ,
  503. FILE_SHARE_READ,
  504. NULL,
  505. OPEN_EXISTING,
  506. FILE_FLAG_BACKUP_SEMANTICS,
  507. NULL
  508. );
  509. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  510. {
  511. if(hFile1 != INVALID_HANDLE_VALUE)
  512. {
  513. CloseHandle(hFile1);
  514. }
  515. if(hFile2 != INVALID_HANDLE_VALUE)
  516. {
  517. CloseHandle(hFile2);
  518. }
  519. return false;
  520. }
  521. BY_HANDLE_FILE_INFORMATION fiBuf1;
  522. BY_HANDLE_FILE_INFORMATION fiBuf2;
  523. GetFileInformationByHandle( hFile1, &fiBuf1 );
  524. GetFileInformationByHandle( hFile2, &fiBuf2 );
  525. CloseHandle(hFile1);
  526. CloseHandle(hFile2);
  527. return (fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  528. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  529. #else
  530. struct stat fileStat1, fileStat2;
  531. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  532. {
  533. // see if the files are the same file
  534. // check the device inode and size
  535. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  536. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  537. fileStat2.st_size == fileStat1.st_size
  538. )
  539. {
  540. return true;
  541. }
  542. }
  543. return false;
  544. #endif
  545. }
  546. // return true if the file exists
  547. bool SystemTools::FileExists(const char* filename)
  548. {
  549. struct stat fs;
  550. if (stat(filename, &fs) != 0)
  551. {
  552. return false;
  553. }
  554. else
  555. {
  556. return true;
  557. }
  558. }
  559. // Return a capitalized string (i.e the first letter is uppercased, all other
  560. // are lowercased)
  561. kwsys_std::string SystemTools::Capitalized(const kwsys_std::string& s)
  562. {
  563. kwsys_std::string n;
  564. n.resize(s.size());
  565. n[0] = toupper(s[0]);
  566. for (size_t i = 1; i < s.size(); i++)
  567. {
  568. n[i] = tolower(s[i]);
  569. }
  570. return n;
  571. }
  572. // Return a lower case string
  573. kwsys_std::string SystemTools::LowerCase(const kwsys_std::string& s)
  574. {
  575. kwsys_std::string n;
  576. n.resize(s.size());
  577. for (size_t i = 0; i < s.size(); i++)
  578. {
  579. n[i] = tolower(s[i]);
  580. }
  581. return n;
  582. }
  583. // Return a lower case string
  584. kwsys_std::string SystemTools::UpperCase(const kwsys_std::string& s)
  585. {
  586. kwsys_std::string n;
  587. n.resize(s.size());
  588. for (size_t i = 0; i < s.size(); i++)
  589. {
  590. n[i] = toupper(s[i]);
  591. }
  592. return n;
  593. }
  594. // convert windows slashes to unix slashes
  595. void SystemTools::ConvertToUnixSlashes(kwsys_std::string& path)
  596. {
  597. kwsys_std::string::size_type pos = 0;
  598. while((pos = path.find('\\', pos)) != kwsys_std::string::npos)
  599. {
  600. path[pos] = '/';
  601. pos++;
  602. }
  603. // Remove all // from the path just like most unix shells
  604. int start_find = 0;
  605. #ifdef _WIN32
  606. // However, on windows if the first characters are both slashes,
  607. // then keep them that way, so that network paths can be handled.
  608. start_find = 1;
  609. #endif
  610. while((pos = path.find("//", start_find)) != kwsys_std::string::npos)
  611. {
  612. SystemTools::ReplaceString(path, "//", "/");
  613. }
  614. // remove any trailing slash
  615. if(path.size() && path[path.size()-1] == '/')
  616. {
  617. path = path.substr(0, path.size()-1);
  618. }
  619. // if there is a tilda ~ then replace it with HOME
  620. if(path.find("~") == 0)
  621. {
  622. if (getenv("HOME"))
  623. {
  624. path = kwsys_std::string(getenv("HOME")) + path.substr(1);
  625. }
  626. }
  627. // if there is a /tmp_mnt in a path get rid of it!
  628. if(path.find("/tmp_mnt") == 0)
  629. {
  630. path = path.substr(8);
  631. }
  632. }
  633. // change // to /, and escape any spaces in the path
  634. kwsys_std::string SystemTools::ConvertToUnixOutputPath(const char* path)
  635. {
  636. kwsys_std::string ret = path;
  637. // remove // except at the beginning might be a cygwin drive
  638. kwsys_std::string::size_type pos = 1;
  639. while((pos = ret.find("//", pos)) != kwsys_std::string::npos)
  640. {
  641. ret.erase(pos, 1);
  642. }
  643. // now escape spaces if there is a space in the path
  644. if(ret.find(" ") != kwsys_std::string::npos)
  645. {
  646. kwsys_std::string result = "";
  647. char lastch = 1;
  648. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  649. {
  650. // if it is already escaped then don't try to escape it again
  651. if(*ch == ' ' && lastch != '\\')
  652. {
  653. result += '\\';
  654. }
  655. result += *ch;
  656. lastch = *ch;
  657. }
  658. ret = result;
  659. }
  660. return ret;
  661. }
  662. kwsys_std::string SystemTools::ConvertToOutputPath(const char* path)
  663. {
  664. #if defined(_WIN32) && !defined(__CYGWIN__)
  665. return SystemTools::ConvertToWindowsOutputPath(path);
  666. #else
  667. return SystemTools::ConvertToUnixOutputPath(path);
  668. #endif
  669. }
  670. // remove double slashes not at the start
  671. kwsys_std::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  672. {
  673. kwsys_std::string ret = path;
  674. kwsys_std::string::size_type pos = 0;
  675. // first convert all of the slashes
  676. while((pos = ret.find('/', pos)) != kwsys_std::string::npos)
  677. {
  678. ret[pos] = '\\';
  679. pos++;
  680. }
  681. // check for really small paths
  682. if(ret.size() < 2)
  683. {
  684. return ret;
  685. }
  686. // now clean up a bit and remove double slashes
  687. // Only if it is not the first position in the path which is a network
  688. // path on windows
  689. pos = 1; // start at position 1
  690. if(ret[0] == '\"')
  691. {
  692. pos = 2; // if the string is already quoted then start at 2
  693. if(ret.size() < 3)
  694. {
  695. return ret;
  696. }
  697. }
  698. while((pos = ret.find("\\\\", pos)) != kwsys_std::string::npos)
  699. {
  700. ret.erase(pos, 1);
  701. }
  702. // now double quote the path if it has spaces in it
  703. // and is not already double quoted
  704. if(ret.find(" ") != kwsys_std::string::npos
  705. && ret[0] != '\"')
  706. {
  707. kwsys_std::string result;
  708. result = "\"" + ret + "\"";
  709. ret = result;
  710. }
  711. return ret;
  712. }
  713. bool SystemTools::CopyFileIfDifferent(const char* source,
  714. const char* destination)
  715. {
  716. if(SystemTools::FilesDiffer(source, destination))
  717. {
  718. SystemTools::CopyFileAlways(source, destination);
  719. return true;
  720. }
  721. return false;
  722. }
  723. bool SystemTools::FilesDiffer(const char* source,
  724. const char* destination)
  725. {
  726. struct stat statSource;
  727. if (stat(source, &statSource) != 0)
  728. {
  729. return true;
  730. }
  731. struct stat statDestination;
  732. if (stat(destination, &statDestination) != 0)
  733. {
  734. return true;
  735. }
  736. if(statSource.st_size != statDestination.st_size)
  737. {
  738. return true;
  739. }
  740. if(statSource.st_size == 0)
  741. {
  742. return false;
  743. }
  744. #if defined(_WIN32) || defined(__CYGWIN__)
  745. kwsys_std::ifstream finSource(source, (kwsys_std::ios::binary |
  746. kwsys_std::ios::in));
  747. kwsys_std::ifstream finDestination(destination, (kwsys_std::ios::binary |
  748. kwsys_std::ios::in));
  749. #else
  750. kwsys_std::ifstream finSource(source);
  751. kwsys_std::ifstream finDestination(destination);
  752. #endif
  753. if(!finSource || !finDestination)
  754. {
  755. return true;
  756. }
  757. char* source_buf = new char[statSource.st_size];
  758. char* dest_buf = new char[statSource.st_size];
  759. finSource.read(source_buf, statSource.st_size);
  760. finDestination.read(dest_buf, statSource.st_size);
  761. if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
  762. statSource.st_size != static_cast<long>(finDestination.gcount()))
  763. {
  764. // Failed to read files.
  765. delete [] source_buf;
  766. delete [] dest_buf;
  767. return true;
  768. }
  769. int ret = memcmp((const void*)source_buf,
  770. (const void*)dest_buf,
  771. statSource.st_size);
  772. delete [] dest_buf;
  773. delete [] source_buf;
  774. return ret != 0;
  775. }
  776. /**
  777. * Copy a file named by "source" to the file named by "destination".
  778. */
  779. bool SystemTools::CopyFileAlways(const char* source, const char* destination)
  780. {
  781. const int bufferSize = 4096;
  782. char buffer[bufferSize];
  783. // If destination is a directory, try to create a file with the same
  784. // name as the source in that directory.
  785. kwsys_std::string new_destination;
  786. if(SystemTools::FileExists(destination) &&
  787. SystemTools::FileIsDirectory(destination))
  788. {
  789. new_destination = destination;
  790. SystemTools::ConvertToUnixSlashes(new_destination);
  791. new_destination += '/';
  792. kwsys_std::string source_name = source;
  793. new_destination += SystemTools::GetFilenameName(source_name);
  794. destination = new_destination.c_str();
  795. }
  796. // Create destination directory
  797. kwsys_std::string destination_dir = destination;
  798. destination_dir = SystemTools::GetFilenamePath(destination_dir);
  799. SystemTools::MakeDirectory(destination_dir.c_str());
  800. // Open files
  801. #if defined(_WIN32) || defined(__CYGWIN__)
  802. kwsys_std::ifstream fin(source,
  803. kwsys_std::ios::binary | kwsys_std::ios::in);
  804. #else
  805. kwsys_std::ifstream fin(source);
  806. #endif
  807. if(!fin)
  808. {
  809. return false;
  810. }
  811. #if defined(_WIN32) || defined(__CYGWIN__)
  812. kwsys_std::ofstream fout(destination,
  813. kwsys_std::ios::binary | kwsys_std::ios::out | kwsys_std::ios::trunc);
  814. #else
  815. kwsys_std::ofstream fout(destination,
  816. kwsys_std::ios::out | kwsys_std::ios::trunc);
  817. #endif
  818. if(!fout)
  819. {
  820. return false;
  821. }
  822. // This copy loop is very sensitive on certain platforms with
  823. // slightly broken stream libraries (like HPUX). Normally, it is
  824. // incorrect to not check the error condition on the fin.read()
  825. // before using the data, but the fin.gcount() will be zero if an
  826. // error occurred. Therefore, the loop should be safe everywhere.
  827. while(fin)
  828. {
  829. fin.read(buffer, bufferSize);
  830. if(fin.gcount())
  831. {
  832. fout.write(buffer, fin.gcount());
  833. }
  834. }
  835. // Make sure the operating system has finished writing the file
  836. // before closing it. This will ensure the file is finished before
  837. // the check below.
  838. fout.flush();
  839. fin.close();
  840. fout.close();
  841. // More checks.
  842. struct stat statSource, statDestination;
  843. statSource.st_size = 12345;
  844. statDestination.st_size = 12345;
  845. if(stat(source, &statSource) != 0)
  846. {
  847. return false;
  848. }
  849. else if(stat(destination, &statDestination) != 0)
  850. {
  851. return false;
  852. }
  853. else if(statSource.st_size != statDestination.st_size)
  854. {
  855. return false;
  856. }
  857. return true;
  858. }
  859. // return size of file; also returns zero if no file exists
  860. unsigned long SystemTools::FileLength(const char* filename)
  861. {
  862. struct stat fs;
  863. if (stat(filename, &fs) != 0)
  864. {
  865. return 0;
  866. }
  867. else
  868. {
  869. return fs.st_size;
  870. }
  871. }
  872. int SystemTools::Strucmp(const char *s1, const char *s2)
  873. {
  874. // lifted from Graphvis http://www.graphviz.org
  875. while ((*s1 != '\0')
  876. && (tolower(*s1) == tolower(*s2)))
  877. {
  878. s1++;
  879. s2++;
  880. }
  881. return tolower(*s1) - tolower(*s2);
  882. }
  883. // return true if the file exists
  884. long int SystemTools::ModifiedTime(const char* filename)
  885. {
  886. struct stat fs;
  887. if (stat(filename, &fs) != 0)
  888. {
  889. return 0;
  890. }
  891. else
  892. {
  893. return (long int)fs.st_mtime;
  894. }
  895. }
  896. kwsys_std::string SystemTools::GetLastSystemError()
  897. {
  898. int e = errno;
  899. return strerror(e);
  900. }
  901. bool SystemTools::RemoveFile(const char* source)
  902. {
  903. return unlink(source) != 0 ? false : true;
  904. }
  905. /**
  906. * Find the file the given name. Searches the given path and then
  907. * the system search path. Returns the full path to the file if it is
  908. * found. Otherwise, the empty string is returned.
  909. */
  910. kwsys_std::string SystemTools::FindFile(const char* name,
  911. const kwsys_std::vector<kwsys_std::string>& userPaths)
  912. {
  913. // Add the system search path to our path first
  914. kwsys_std::vector<kwsys_std::string> path;
  915. SystemTools::GetPath(path);
  916. // now add the additional paths
  917. path.insert(path.end(), userPaths.begin(), userPaths.end());
  918. // now look for the file
  919. kwsys_std::string tryPath;
  920. for(kwsys_std::vector<kwsys_std::string>::const_iterator p = path.begin();
  921. p != path.end(); ++p)
  922. {
  923. tryPath = *p;
  924. tryPath += "/";
  925. tryPath += name;
  926. if(SystemTools::FileExists(tryPath.c_str()) &&
  927. !SystemTools::FileIsDirectory(tryPath.c_str()))
  928. {
  929. return SystemTools::CollapseFullPath(tryPath.c_str());
  930. }
  931. }
  932. // Couldn't find the file.
  933. return "";
  934. }
  935. /**
  936. * Find the executable with the given name. Searches the given path and then
  937. * the system search path. Returns the full path to the executable if it is
  938. * found. Otherwise, the empty string is returned.
  939. */
  940. kwsys_std::string SystemTools::FindProgram(const char* name,
  941. const kwsys_std::vector<kwsys_std::string>& userPaths,
  942. bool no_system_path)
  943. {
  944. if(!name)
  945. {
  946. return "";
  947. }
  948. // See if the executable exists as written.
  949. if(SystemTools::FileExists(name) &&
  950. !SystemTools::FileIsDirectory(name))
  951. {
  952. return SystemTools::CollapseFullPath(name);
  953. }
  954. kwsys_std::string tryPath = name;
  955. tryPath += SystemTools::GetExecutableExtension();
  956. if(SystemTools::FileExists(tryPath.c_str()) &&
  957. !SystemTools::FileIsDirectory(tryPath.c_str()))
  958. {
  959. return SystemTools::CollapseFullPath(tryPath.c_str());
  960. }
  961. // Add the system search path to our path.
  962. kwsys_std::vector<kwsys_std::string> path;
  963. if (!no_system_path)
  964. {
  965. SystemTools::GetPath(path);
  966. }
  967. // now add the additional paths
  968. path.insert(path.end(), userPaths.begin(), userPaths.end());
  969. for(kwsys_std::vector<kwsys_std::string>::const_iterator p = path.begin();
  970. p != path.end(); ++p)
  971. {
  972. tryPath = *p;
  973. tryPath += "/";
  974. tryPath += name;
  975. if(SystemTools::FileExists(tryPath.c_str()) &&
  976. !SystemTools::FileIsDirectory(tryPath.c_str()))
  977. {
  978. return SystemTools::CollapseFullPath(tryPath.c_str());
  979. }
  980. #ifdef _WIN32
  981. tryPath += ".com";
  982. if(SystemTools::FileExists(tryPath.c_str()) &&
  983. !SystemTools::FileIsDirectory(tryPath.c_str()))
  984. {
  985. return SystemTools::CollapseFullPath(tryPath.c_str());
  986. }
  987. tryPath = *p;
  988. tryPath += "/";
  989. tryPath += name;
  990. #endif
  991. tryPath += SystemTools::GetExecutableExtension();
  992. if(SystemTools::FileExists(tryPath.c_str()) &&
  993. !SystemTools::FileIsDirectory(tryPath.c_str()))
  994. {
  995. return SystemTools::CollapseFullPath(tryPath.c_str());
  996. }
  997. }
  998. // Couldn't find the program.
  999. return "";
  1000. }
  1001. /**
  1002. * Find the library with the given name. Searches the given path and then
  1003. * the system search path. Returns the full path to the library if it is
  1004. * found. Otherwise, the empty string is returned.
  1005. */
  1006. kwsys_std::string SystemTools::FindLibrary(const char* name,
  1007. const kwsys_std::vector<kwsys_std::string>& userPaths)
  1008. {
  1009. // See if the executable exists as written.
  1010. if(SystemTools::FileExists(name) &&
  1011. !SystemTools::FileIsDirectory(name))
  1012. {
  1013. return SystemTools::CollapseFullPath(name);
  1014. }
  1015. // Add the system search path to our path.
  1016. kwsys_std::vector<kwsys_std::string> path;
  1017. SystemTools::GetPath(path);
  1018. // now add the additional paths
  1019. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1020. kwsys_std::string tryPath;
  1021. for(kwsys_std::vector<kwsys_std::string>::const_iterator p = path.begin();
  1022. p != path.end(); ++p)
  1023. {
  1024. #if defined(_WIN32) && !defined(__CYGWIN__)
  1025. tryPath = *p;
  1026. tryPath += "/";
  1027. tryPath += name;
  1028. tryPath += ".lib";
  1029. if(SystemTools::FileExists(tryPath.c_str()))
  1030. {
  1031. return SystemTools::CollapseFullPath(tryPath.c_str());
  1032. }
  1033. #else
  1034. tryPath = *p;
  1035. tryPath += "/lib";
  1036. tryPath += name;
  1037. tryPath += ".so";
  1038. if(SystemTools::FileExists(tryPath.c_str()))
  1039. {
  1040. return SystemTools::CollapseFullPath(tryPath.c_str());
  1041. }
  1042. tryPath = *p;
  1043. tryPath += "/lib";
  1044. tryPath += name;
  1045. tryPath += ".a";
  1046. if(SystemTools::FileExists(tryPath.c_str()))
  1047. {
  1048. return SystemTools::CollapseFullPath(tryPath.c_str());
  1049. }
  1050. tryPath = *p;
  1051. tryPath += "/lib";
  1052. tryPath += name;
  1053. tryPath += ".sl";
  1054. if(SystemTools::FileExists(tryPath.c_str()))
  1055. {
  1056. return SystemTools::CollapseFullPath(tryPath.c_str());
  1057. }
  1058. tryPath = *p;
  1059. tryPath += "/lib";
  1060. tryPath += name;
  1061. tryPath += ".dylib";
  1062. if(SystemTools::FileExists(tryPath.c_str()))
  1063. {
  1064. return SystemTools::CollapseFullPath(tryPath.c_str());
  1065. }
  1066. #endif
  1067. }
  1068. // Couldn't find the library.
  1069. return "";
  1070. }
  1071. bool SystemTools::FileIsDirectory(const char* name)
  1072. {
  1073. struct stat fs;
  1074. if(stat(name, &fs) == 0)
  1075. {
  1076. #if _WIN32
  1077. return ((fs.st_mode & _S_IFDIR) != 0);
  1078. #else
  1079. return S_ISDIR(fs.st_mode);
  1080. #endif
  1081. }
  1082. else
  1083. {
  1084. return false;
  1085. }
  1086. }
  1087. int SystemTools::ChangeDirectory(const char *dir)
  1088. {
  1089. return Chdir(dir);
  1090. }
  1091. kwsys_std::string SystemTools::GetCurrentWorkingDirectory()
  1092. {
  1093. char buf[2048];
  1094. kwsys_std::string path = Getcwd(buf, 2048);
  1095. return path;
  1096. }
  1097. kwsys_std::string SystemTools::GetProgramPath(const char* in_name)
  1098. {
  1099. kwsys_std::string dir, file;
  1100. SystemTools::SplitProgramPath(in_name, dir, file);
  1101. return dir;
  1102. }
  1103. bool SystemTools::SplitProgramPath(const char* in_name,
  1104. kwsys_std::string& dir,
  1105. kwsys_std::string& file,
  1106. bool)
  1107. {
  1108. dir = in_name;
  1109. file = "";
  1110. SystemTools::ConvertToUnixSlashes(dir);
  1111. if(!SystemTools::FileIsDirectory(dir.c_str()))
  1112. {
  1113. kwsys_std::string::size_type slashPos = dir.rfind("/");
  1114. if(slashPos != kwsys_std::string::npos)
  1115. {
  1116. file = dir.substr(slashPos+1);
  1117. dir = dir.substr(0, slashPos);
  1118. }
  1119. else
  1120. {
  1121. file = dir;
  1122. dir = "";
  1123. }
  1124. }
  1125. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  1126. {
  1127. kwsys_std::string oldDir = in_name;
  1128. SystemTools::ConvertToUnixSlashes(oldDir);
  1129. dir = in_name;
  1130. return false;
  1131. }
  1132. return true;
  1133. }
  1134. kwsys_std::string SystemTools::CollapseFullPath(const char* in_relative)
  1135. {
  1136. return SystemTools::CollapseFullPath(in_relative, 0);
  1137. }
  1138. kwsys_std::string SystemTools::CollapseFullPath(const char* in_relative,
  1139. const char* in_base)
  1140. {
  1141. kwsys_std::string dir, file;
  1142. SystemTools::SplitProgramPath(in_relative, dir, file, false);
  1143. // Save original working directory.
  1144. kwsys_std::string orig = SystemTools::GetCurrentWorkingDirectory();
  1145. // Change to base of relative path.
  1146. if(in_base)
  1147. {
  1148. Chdir(in_base);
  1149. }
  1150. #ifdef _WIN32
  1151. // Follow relative path.
  1152. if(!(dir == ""))
  1153. {
  1154. Chdir(dir.c_str());
  1155. }
  1156. // Get the resulting directory.
  1157. kwsys_std::string newDir = SystemTools::GetCurrentWorkingDirectory();
  1158. // Add the file back on to the directory.
  1159. SystemTools::ConvertToUnixSlashes(newDir);
  1160. #else
  1161. # ifdef MAXPATHLEN
  1162. char resolved_name[MAXPATHLEN];
  1163. # else
  1164. # ifdef PATH_MAX
  1165. char resolved_name[PATH_MAX];
  1166. # else
  1167. char resolved_name[5024];
  1168. # endif
  1169. # endif
  1170. // Resolve relative path.
  1171. kwsys_std::string newDir;
  1172. if(!(dir == ""))
  1173. {
  1174. realpath(dir.c_str(), resolved_name);
  1175. newDir = resolved_name;
  1176. }
  1177. else
  1178. {
  1179. newDir = SystemTools::GetCurrentWorkingDirectory();
  1180. }
  1181. // if there is a /tmp_mnt in a path get rid of it!
  1182. if(newDir.find("/tmp_mnt") == 0)
  1183. {
  1184. newDir = newDir.substr(8);
  1185. }
  1186. #endif
  1187. // Restore original working directory.
  1188. Chdir(orig.c_str());
  1189. // Construct and return the full path.
  1190. kwsys_std::string newPath = newDir;
  1191. if(!(file == ""))
  1192. {
  1193. newPath += "/";
  1194. newPath += file;
  1195. }
  1196. return newPath;
  1197. }
  1198. bool SystemTools::Split(const char* str, kwsys_std::vector<kwsys_std::string>& lines)
  1199. {
  1200. kwsys_std::string data(str);
  1201. kwsys_std::string::size_type lpos = 0;
  1202. while(lpos < data.length())
  1203. {
  1204. kwsys_std::string::size_type rpos = data.find_first_of("\n", lpos);
  1205. if(rpos == kwsys_std::string::npos)
  1206. {
  1207. // Line ends at end of string without a newline.
  1208. lines.push_back(data.substr(lpos));
  1209. return false;
  1210. }
  1211. if((rpos > lpos) && (data[rpos-1] == '\r'))
  1212. {
  1213. // Line ends in a "\r\n" pair, remove both characters.
  1214. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  1215. }
  1216. else
  1217. {
  1218. // Line ends in a "\n", remove the character.
  1219. lines.push_back(data.substr(lpos, rpos-lpos));
  1220. }
  1221. lpos = rpos+1;
  1222. }
  1223. return true;
  1224. }
  1225. /**
  1226. * Return path of a full filename (no trailing slashes).
  1227. * Warning: returned path is converted to Unix slashes format.
  1228. */
  1229. kwsys_std::string SystemTools::GetFilenamePath(const kwsys_std::string& filename)
  1230. {
  1231. kwsys_std::string fn = filename;
  1232. SystemTools::ConvertToUnixSlashes(fn);
  1233. kwsys_std::string::size_type slash_pos = fn.rfind("/");
  1234. if(slash_pos != kwsys_std::string::npos)
  1235. {
  1236. return fn.substr(0, slash_pos);
  1237. }
  1238. else
  1239. {
  1240. return "";
  1241. }
  1242. }
  1243. /**
  1244. * Return file name of a full filename (i.e. file name without path).
  1245. */
  1246. kwsys_std::string SystemTools::GetFilenameName(const kwsys_std::string& filename)
  1247. {
  1248. kwsys_std::string fn = filename;
  1249. SystemTools::ConvertToUnixSlashes(fn);
  1250. kwsys_std::string::size_type slash_pos = fn.rfind("/");
  1251. if(slash_pos != kwsys_std::string::npos)
  1252. {
  1253. return fn.substr(slash_pos + 1);
  1254. }
  1255. else
  1256. {
  1257. return filename;
  1258. }
  1259. }
  1260. /**
  1261. * Return file extension of a full filename (dot included).
  1262. * Warning: this is the longest extension (for example: .tar.gz)
  1263. */
  1264. kwsys_std::string SystemTools::GetFilenameExtension(const kwsys_std::string& filename)
  1265. {
  1266. kwsys_std::string name = SystemTools::GetFilenameName(filename);
  1267. kwsys_std::string::size_type dot_pos = name.find(".");
  1268. if(dot_pos != kwsys_std::string::npos)
  1269. {
  1270. return name.substr(dot_pos);
  1271. }
  1272. else
  1273. {
  1274. return "";
  1275. }
  1276. }
  1277. /**
  1278. * Return file extension of a full filename (dot included).
  1279. * Warning: this is the shortest extension (for example: .tar.gz)
  1280. */
  1281. kwsys_std::string SystemTools::GetFilenameLastExtension(const kwsys_std::string& filename)
  1282. {
  1283. kwsys_std::string name = SystemTools::GetFilenameName(filename);
  1284. kwsys_std::string::size_type dot_pos = name.rfind(".");
  1285. if(dot_pos != kwsys_std::string::npos)
  1286. {
  1287. return name.substr(dot_pos);
  1288. }
  1289. else
  1290. {
  1291. return "";
  1292. }
  1293. }
  1294. /**
  1295. * Return file name without extension of a full filename (i.e. without path).
  1296. * Warning: it considers the longest extension (for example: .tar.gz)
  1297. */
  1298. kwsys_std::string SystemTools::GetFilenameWithoutExtension(const kwsys_std::string& filename)
  1299. {
  1300. kwsys_std::string name = SystemTools::GetFilenameName(filename);
  1301. kwsys_std::string::size_type dot_pos = name.find(".");
  1302. if(dot_pos != kwsys_std::string::npos)
  1303. {
  1304. return name.substr(0, dot_pos);
  1305. }
  1306. else
  1307. {
  1308. return name;
  1309. }
  1310. }
  1311. /**
  1312. * Return file name without extension of a full filename (i.e. without path).
  1313. * Warning: it considers the last extension (for example: removes .gz
  1314. * from .tar.gz)
  1315. */
  1316. kwsys_std::string
  1317. SystemTools::GetFilenameWithoutLastExtension(const kwsys_std::string& filename)
  1318. {
  1319. kwsys_std::string name = SystemTools::GetFilenameName(filename);
  1320. kwsys_std::string::size_type dot_pos = name.rfind(".");
  1321. if(dot_pos != kwsys_std::string::npos)
  1322. {
  1323. return name.substr(0, dot_pos);
  1324. }
  1325. else
  1326. {
  1327. return name;
  1328. }
  1329. }
  1330. bool SystemTools::FileIsFullPath(const char* in_name)
  1331. {
  1332. kwsys_std::string name = in_name;
  1333. #if defined(_WIN32)
  1334. // On Windows, the name must be at least two characters long.
  1335. if(name.length() < 2)
  1336. {
  1337. return false;
  1338. }
  1339. if(name[1] == ':')
  1340. {
  1341. return true;
  1342. }
  1343. if(name[0] == '\\')
  1344. {
  1345. return true;
  1346. }
  1347. #else
  1348. // On UNIX, the name must be at least one character long.
  1349. if(name.length() < 1)
  1350. {
  1351. return false;
  1352. }
  1353. #endif
  1354. // On UNIX, the name must begin in a '/'.
  1355. // On Windows, if the name begins in a '/', then it is a full
  1356. // network path.
  1357. if(name[0] == '/')
  1358. {
  1359. return true;
  1360. }
  1361. return false;
  1362. }
  1363. bool SystemTools::GetShortPath(const char* path, kwsys_std::string& shortPath)
  1364. {
  1365. #if defined(WIN32) && !defined(__CYGWIN__)
  1366. const int size = int(strlen(path)) +1; // size of return
  1367. char *buffer = new char[size]; // create a buffer
  1368. char *tempPath = new char[size]; // create a buffer
  1369. int ret;
  1370. // if the path passed in has quotes around it, first remove the quotes
  1371. if (path[0] == '"' && path[strlen(path)-1] == '"')
  1372. {
  1373. strcpy(tempPath,path+1);
  1374. tempPath[strlen(tempPath)-1] = '\0';
  1375. }
  1376. else
  1377. {
  1378. strcpy(tempPath,path);
  1379. }
  1380. buffer[0] = 0;
  1381. ret = GetShortPathName(tempPath, buffer, size);
  1382. if(buffer[0] == 0 || ret > size)
  1383. {
  1384. delete [] buffer;
  1385. delete [] tempPath;
  1386. return false;
  1387. }
  1388. else
  1389. {
  1390. shortPath = buffer;
  1391. delete [] buffer;
  1392. delete [] tempPath;
  1393. return true;
  1394. }
  1395. #else
  1396. shortPath = path;
  1397. return true;
  1398. #endif
  1399. }
  1400. void SystemTools::SplitProgramFromArgs(const char* path,
  1401. kwsys_std::string& program, kwsys_std::string& args)
  1402. {
  1403. if(SystemTools::FileExists(path))
  1404. {
  1405. program = path;
  1406. args = "";
  1407. return;
  1408. }
  1409. kwsys_std::vector<kwsys_std::string> e;
  1410. kwsys_std::string findProg = SystemTools::FindProgram(path, e);
  1411. if(findProg.size())
  1412. {
  1413. program = findProg;
  1414. args = "";
  1415. return;
  1416. }
  1417. kwsys_std::string dir = path;
  1418. kwsys_std::string::size_type spacePos = dir.rfind(' ');
  1419. if(spacePos == kwsys_std::string::npos)
  1420. {
  1421. program = "";
  1422. args = "";
  1423. return;
  1424. }
  1425. while(spacePos != kwsys_std::string::npos)
  1426. {
  1427. kwsys_std::string tryProg = dir.substr(0, spacePos);
  1428. if(SystemTools::FileExists(tryProg.c_str()))
  1429. {
  1430. program = tryProg;
  1431. args = dir.substr(spacePos, dir.size()-spacePos);
  1432. return;
  1433. }
  1434. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  1435. if(findProg.size())
  1436. {
  1437. program = findProg;
  1438. args = dir.substr(spacePos, dir.size()-spacePos);
  1439. return;
  1440. }
  1441. spacePos = dir.rfind(' ', spacePos--);
  1442. }
  1443. program = "";
  1444. args = "";
  1445. }
  1446. kwsys_std::string SystemTools::GetCurrentDateTime(const char* format)
  1447. {
  1448. char buf[1024];
  1449. time_t t;
  1450. time(&t);
  1451. strftime(buf, sizeof(buf), format, localtime(&t));
  1452. return buf;
  1453. }
  1454. kwsys_std::string SystemTools::MakeCindentifier(const char* s)
  1455. {
  1456. kwsys_std::string str(s);
  1457. if (str.find_first_of("0123456789") == 0)
  1458. {
  1459. str = "_" + str;
  1460. }
  1461. kwsys_std::string permited_chars("_"
  1462. "abcdefghijklmnopqrstuvwxyz"
  1463. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1464. "0123456789");
  1465. kwsys_std::string::size_type pos = 0;
  1466. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_std::string::npos)
  1467. {
  1468. str[pos] = '_';
  1469. }
  1470. return str;
  1471. }
  1472. // Due to a buggy stream library on the HP and another on Mac OSX, we
  1473. // need this very carefully written version of getline. Returns true
  1474. // if any data were read before the end-of-file was reached.
  1475. bool SystemTools::GetLineFromStream(kwsys_std::istream& is, kwsys_std::string& line,
  1476. bool *has_newline /* = 0 */)
  1477. {
  1478. const int bufferSize = 1024;
  1479. char buffer[bufferSize];
  1480. line = "";
  1481. bool haveData = false;
  1482. if ( has_newline )
  1483. {
  1484. *has_newline = false;
  1485. }
  1486. // If no characters are read from the stream, the end of file has
  1487. // been reached.
  1488. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  1489. {
  1490. haveData = true;
  1491. line.append(buffer);
  1492. // If newline character was read, the gcount includes the
  1493. // character, but the buffer does not. The end of line has been
  1494. // reached.
  1495. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  1496. {
  1497. if ( has_newline )
  1498. {
  1499. *has_newline = true;
  1500. }
  1501. break;
  1502. }
  1503. // The fail bit may be set. Clear it.
  1504. is.clear(is.rdstate() & ~kwsys_std::ios::failbit);
  1505. }
  1506. return haveData;
  1507. }
  1508. } // namespace KWSYS_NAMESPACE
  1509. #if defined(_MSC_VER) && defined(_DEBUG)
  1510. # include <crtdbg.h>
  1511. # include <stdio.h>
  1512. # include <stdlib.h>
  1513. namespace KWSYS_NAMESPACE
  1514. {
  1515. static int SystemToolsDebugReport(int, char* message, int*)
  1516. {
  1517. fprintf(stderr, message);
  1518. exit(1);
  1519. }
  1520. void SystemTools::EnableMSVCDebugHook()
  1521. {
  1522. if(getenv("DART_TEST_FROM_DART"))
  1523. {
  1524. _CrtSetReportHook(SystemToolsDebugReport);
  1525. }
  1526. }
  1527. } // namespace KWSYS_NAMESPACE
  1528. #else
  1529. namespace KWSYS_NAMESPACE
  1530. {
  1531. void SystemTools::EnableMSVCDebugHook() {}
  1532. } // namespace KWSYS_NAMESPACE
  1533. #endif