SystemTools.cxx 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  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. // stupid sgi's
  629. if(path.find("/tmp_mnt") == 0)
  630. {
  631. path = path.substr(8);
  632. }
  633. }
  634. // change // to /, and escape any spaces in the path
  635. kwsys_std::string SystemTools::ConvertToUnixOutputPath(const char* path)
  636. {
  637. kwsys_std::string ret = path;
  638. // remove // except at the beginning might be a cygwin drive
  639. kwsys_std::string::size_type pos = 1;
  640. while((pos = ret.find("//", pos)) != kwsys_std::string::npos)
  641. {
  642. ret.erase(pos, 1);
  643. }
  644. // now escape spaces if there is a space in the path
  645. if(ret.find(" ") != kwsys_std::string::npos)
  646. {
  647. kwsys_std::string result = "";
  648. char lastch = 1;
  649. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  650. {
  651. // if it is already escaped then don't try to escape it again
  652. if(*ch == ' ' && lastch != '\\')
  653. {
  654. result += '\\';
  655. }
  656. result += *ch;
  657. lastch = *ch;
  658. }
  659. ret = result;
  660. }
  661. return ret;
  662. }
  663. kwsys_std::string SystemTools::ConvertToOutputPath(const char* path)
  664. {
  665. #if defined(_WIN32) && !defined(__CYGWIN__)
  666. return SystemTools::ConvertToWindowsOutputPath(path);
  667. #else
  668. return SystemTools::ConvertToUnixOutputPath(path);
  669. #endif
  670. }
  671. // remove double slashes not at the start
  672. kwsys_std::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  673. {
  674. kwsys_std::string ret = path;
  675. kwsys_std::string::size_type pos = 0;
  676. // first convert all of the slashes
  677. while((pos = ret.find('/', pos)) != kwsys_std::string::npos)
  678. {
  679. ret[pos] = '\\';
  680. pos++;
  681. }
  682. // check for really small paths
  683. if(ret.size() < 2)
  684. {
  685. return ret;
  686. }
  687. // now clean up a bit and remove double slashes
  688. // Only if it is not the first position in the path which is a network
  689. // path on windows
  690. pos = 1; // start at position 1
  691. if(ret[0] == '\"')
  692. {
  693. pos = 2; // if the string is already quoted then start at 2
  694. if(ret.size() < 3)
  695. {
  696. return ret;
  697. }
  698. }
  699. while((pos = ret.find("\\\\", pos)) != kwsys_std::string::npos)
  700. {
  701. ret.erase(pos, 1);
  702. }
  703. // now double quote the path if it has spaces in it
  704. // and is not already double quoted
  705. if(ret.find(" ") != kwsys_std::string::npos
  706. && ret[0] != '\"')
  707. {
  708. kwsys_std::string result;
  709. result = "\"" + ret + "\"";
  710. ret = result;
  711. }
  712. return ret;
  713. }
  714. bool SystemTools::CopyFileIfDifferent(const char* source,
  715. const char* destination)
  716. {
  717. if(SystemTools::FilesDiffer(source, destination))
  718. {
  719. SystemTools::CopyFileAlways(source, destination);
  720. return true;
  721. }
  722. return false;
  723. }
  724. bool SystemTools::FilesDiffer(const char* source,
  725. const char* destination)
  726. {
  727. struct stat statSource;
  728. if (stat(source, &statSource) != 0)
  729. {
  730. return true;
  731. }
  732. struct stat statDestination;
  733. if (stat(destination, &statDestination) != 0)
  734. {
  735. return true;
  736. }
  737. if(statSource.st_size != statDestination.st_size)
  738. {
  739. return true;
  740. }
  741. if(statSource.st_size == 0)
  742. {
  743. return false;
  744. }
  745. #if defined(_WIN32) || defined(__CYGWIN__)
  746. kwsys_std::ifstream finSource(source, (kwsys_std::ios::binary |
  747. kwsys_std::ios::in));
  748. kwsys_std::ifstream finDestination(destination, (kwsys_std::ios::binary |
  749. kwsys_std::ios::in));
  750. #else
  751. kwsys_std::ifstream finSource(source);
  752. kwsys_std::ifstream finDestination(destination);
  753. #endif
  754. if(!finSource || !finDestination)
  755. {
  756. return true;
  757. }
  758. char* source_buf = new char[statSource.st_size];
  759. char* dest_buf = new char[statSource.st_size];
  760. finSource.read(source_buf, statSource.st_size);
  761. finDestination.read(dest_buf, statSource.st_size);
  762. if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
  763. statSource.st_size != static_cast<long>(finDestination.gcount()))
  764. {
  765. // Failed to read files.
  766. delete [] source_buf;
  767. delete [] dest_buf;
  768. return true;
  769. }
  770. int ret = memcmp((const void*)source_buf,
  771. (const void*)dest_buf,
  772. statSource.st_size);
  773. delete [] dest_buf;
  774. delete [] source_buf;
  775. return ret != 0;
  776. }
  777. /**
  778. * Copy a file named by "source" to the file named by "destination".
  779. */
  780. bool SystemTools::CopyFileAlways(const char* source, const char* destination)
  781. {
  782. const int bufferSize = 4096;
  783. char buffer[bufferSize];
  784. // If destination is a directory, try to create a file with the same
  785. // name as the source in that directory.
  786. kwsys_std::string new_destination;
  787. if(SystemTools::FileExists(destination) &&
  788. SystemTools::FileIsDirectory(destination))
  789. {
  790. new_destination = destination;
  791. SystemTools::ConvertToUnixSlashes(new_destination);
  792. new_destination += '/';
  793. kwsys_std::string source_name = source;
  794. new_destination += SystemTools::GetFilenameName(source_name);
  795. destination = new_destination.c_str();
  796. }
  797. // Create destination directory
  798. kwsys_std::string destination_dir = destination;
  799. destination_dir = SystemTools::GetFilenamePath(destination_dir);
  800. SystemTools::MakeDirectory(destination_dir.c_str());
  801. // Open files
  802. #if defined(_WIN32) || defined(__CYGWIN__)
  803. kwsys_std::ifstream fin(source,
  804. kwsys_std::ios::binary | kwsys_std::ios::in);
  805. #else
  806. kwsys_std::ifstream fin(source);
  807. #endif
  808. if(!fin)
  809. {
  810. return false;
  811. }
  812. #if defined(_WIN32) || defined(__CYGWIN__)
  813. kwsys_std::ofstream fout(destination,
  814. kwsys_std::ios::binary | kwsys_std::ios::out | kwsys_std::ios::trunc);
  815. #else
  816. kwsys_std::ofstream fout(destination,
  817. kwsys_std::ios::out | kwsys_std::ios::trunc);
  818. #endif
  819. if(!fout)
  820. {
  821. return false;
  822. }
  823. // This copy loop is very sensitive on certain platforms with
  824. // slightly broken stream libraries (like HPUX). Normally, it is
  825. // incorrect to not check the error condition on the fin.read()
  826. // before using the data, but the fin.gcount() will be zero if an
  827. // error occurred. Therefore, the loop should be safe everywhere.
  828. while(fin)
  829. {
  830. fin.read(buffer, bufferSize);
  831. if(fin.gcount())
  832. {
  833. fout.write(buffer, fin.gcount());
  834. }
  835. }
  836. // Make sure the operating system has finished writing the file
  837. // before closing it. This will ensure the file is finished before
  838. // the check below.
  839. fout.flush();
  840. fin.close();
  841. fout.close();
  842. // More checks.
  843. struct stat statSource, statDestination;
  844. statSource.st_size = 12345;
  845. statDestination.st_size = 12345;
  846. if(stat(source, &statSource) != 0)
  847. {
  848. return false;
  849. }
  850. else if(stat(destination, &statDestination) != 0)
  851. {
  852. return false;
  853. }
  854. else if(statSource.st_size != statDestination.st_size)
  855. {
  856. return false;
  857. }
  858. return true;
  859. }
  860. // return size of file; also returns zero if no file exists
  861. unsigned long SystemTools::FileLength(const char* filename)
  862. {
  863. struct stat fs;
  864. if (stat(filename, &fs) != 0)
  865. {
  866. return 0;
  867. }
  868. else
  869. {
  870. return fs.st_size;
  871. }
  872. }
  873. int SystemTools::Strucmp(const char *s1, const char *s2)
  874. {
  875. // lifted from Graphvis http://www.graphviz.org
  876. while ((*s1 != '\0')
  877. && (tolower(*s1) == tolower(*s2)))
  878. {
  879. s1++;
  880. s2++;
  881. }
  882. return tolower(*s1) - tolower(*s2);
  883. }
  884. // return true if the file exists
  885. long int SystemTools::ModifiedTime(const char* filename)
  886. {
  887. struct stat fs;
  888. if (stat(filename, &fs) != 0)
  889. {
  890. return 0;
  891. }
  892. else
  893. {
  894. return (long int)fs.st_mtime;
  895. }
  896. }
  897. kwsys_std::string SystemTools::GetLastSystemError()
  898. {
  899. int e = errno;
  900. return strerror(e);
  901. }
  902. bool SystemTools::RemoveFile(const char* source)
  903. {
  904. return unlink(source) != 0 ? false : true;
  905. }
  906. /**
  907. * Find the file the given name. Searches the given path and then
  908. * the system search path. Returns the full path to the file if it is
  909. * found. Otherwise, the empty string is returned.
  910. */
  911. kwsys_std::string SystemTools::FindFile(const char* name,
  912. const kwsys_std::vector<kwsys_std::string>& userPaths)
  913. {
  914. // Add the system search path to our path.
  915. kwsys_std::vector<kwsys_std::string> path = userPaths;
  916. SystemTools::GetPath(path);
  917. kwsys_std::string tryPath;
  918. for(kwsys_std::vector<kwsys_std::string>::const_iterator p = path.begin();
  919. p != path.end(); ++p)
  920. {
  921. tryPath = *p;
  922. tryPath += "/";
  923. tryPath += name;
  924. if(SystemTools::FileExists(tryPath.c_str()) &&
  925. !SystemTools::FileIsDirectory(tryPath.c_str()))
  926. {
  927. return SystemTools::CollapseFullPath(tryPath.c_str());
  928. }
  929. }
  930. // Couldn't find the file.
  931. return "";
  932. }
  933. /**
  934. * Find the executable with the given name. Searches the given path and then
  935. * the system search path. Returns the full path to the executable if it is
  936. * found. Otherwise, the empty string is returned.
  937. */
  938. kwsys_std::string SystemTools::FindProgram(const char* name,
  939. const kwsys_std::vector<kwsys_std::string>& userPaths,
  940. bool no_system_path)
  941. {
  942. if(!name)
  943. {
  944. return "";
  945. }
  946. // See if the executable exists as written.
  947. if(SystemTools::FileExists(name) &&
  948. !SystemTools::FileIsDirectory(name))
  949. {
  950. return SystemTools::CollapseFullPath(name);
  951. }
  952. kwsys_std::string tryPath = name;
  953. tryPath += SystemTools::GetExecutableExtension();
  954. if(SystemTools::FileExists(tryPath.c_str()) &&
  955. !SystemTools::FileIsDirectory(tryPath.c_str()))
  956. {
  957. return SystemTools::CollapseFullPath(tryPath.c_str());
  958. }
  959. // Add the system search path to our path.
  960. kwsys_std::vector<kwsys_std::string> path = userPaths;
  961. if (!no_system_path)
  962. {
  963. SystemTools::GetPath(path);
  964. }
  965. for(kwsys_std::vector<kwsys_std::string>::const_iterator p = path.begin();
  966. p != path.end(); ++p)
  967. {
  968. tryPath = *p;
  969. tryPath += "/";
  970. tryPath += name;
  971. if(SystemTools::FileExists(tryPath.c_str()) &&
  972. !SystemTools::FileIsDirectory(tryPath.c_str()))
  973. {
  974. return SystemTools::CollapseFullPath(tryPath.c_str());
  975. }
  976. #ifdef _WIN32
  977. tryPath += ".com";
  978. if(SystemTools::FileExists(tryPath.c_str()) &&
  979. !SystemTools::FileIsDirectory(tryPath.c_str()))
  980. {
  981. return SystemTools::CollapseFullPath(tryPath.c_str());
  982. }
  983. tryPath = *p;
  984. tryPath += "/";
  985. tryPath += name;
  986. #endif
  987. tryPath += SystemTools::GetExecutableExtension();
  988. if(SystemTools::FileExists(tryPath.c_str()) &&
  989. !SystemTools::FileIsDirectory(tryPath.c_str()))
  990. {
  991. return SystemTools::CollapseFullPath(tryPath.c_str());
  992. }
  993. }
  994. // Couldn't find the program.
  995. return "";
  996. }
  997. /**
  998. * Find the library with the given name. Searches the given path and then
  999. * the system search path. Returns the full path to the library if it is
  1000. * found. Otherwise, the empty string is returned.
  1001. */
  1002. kwsys_std::string SystemTools::FindLibrary(const char* name,
  1003. const kwsys_std::vector<kwsys_std::string>& userPaths)
  1004. {
  1005. // See if the executable exists as written.
  1006. if(SystemTools::FileExists(name) &&
  1007. !SystemTools::FileIsDirectory(name))
  1008. {
  1009. return SystemTools::CollapseFullPath(name);
  1010. }
  1011. // Add the system search path to our path.
  1012. kwsys_std::vector<kwsys_std::string> path = userPaths;
  1013. SystemTools::GetPath(path);
  1014. kwsys_std::string tryPath;
  1015. for(kwsys_std::vector<kwsys_std::string>::const_iterator p = path.begin();
  1016. p != path.end(); ++p)
  1017. {
  1018. #if defined(_WIN32) && !defined(__CYGWIN__)
  1019. tryPath = *p;
  1020. tryPath += "/";
  1021. tryPath += name;
  1022. tryPath += ".lib";
  1023. if(SystemTools::FileExists(tryPath.c_str()))
  1024. {
  1025. return SystemTools::CollapseFullPath(tryPath.c_str());
  1026. }
  1027. #else
  1028. tryPath = *p;
  1029. tryPath += "/lib";
  1030. tryPath += name;
  1031. tryPath += ".so";
  1032. if(SystemTools::FileExists(tryPath.c_str()))
  1033. {
  1034. return SystemTools::CollapseFullPath(tryPath.c_str());
  1035. }
  1036. tryPath = *p;
  1037. tryPath += "/lib";
  1038. tryPath += name;
  1039. tryPath += ".a";
  1040. if(SystemTools::FileExists(tryPath.c_str()))
  1041. {
  1042. return SystemTools::CollapseFullPath(tryPath.c_str());
  1043. }
  1044. tryPath = *p;
  1045. tryPath += "/lib";
  1046. tryPath += name;
  1047. tryPath += ".sl";
  1048. if(SystemTools::FileExists(tryPath.c_str()))
  1049. {
  1050. return SystemTools::CollapseFullPath(tryPath.c_str());
  1051. }
  1052. tryPath = *p;
  1053. tryPath += "/lib";
  1054. tryPath += name;
  1055. tryPath += ".dylib";
  1056. if(SystemTools::FileExists(tryPath.c_str()))
  1057. {
  1058. return SystemTools::CollapseFullPath(tryPath.c_str());
  1059. }
  1060. #endif
  1061. }
  1062. // Couldn't find the library.
  1063. return "";
  1064. }
  1065. bool SystemTools::FileIsDirectory(const char* name)
  1066. {
  1067. struct stat fs;
  1068. if(stat(name, &fs) == 0)
  1069. {
  1070. #if _WIN32
  1071. return ((fs.st_mode & _S_IFDIR) != 0);
  1072. #else
  1073. return S_ISDIR(fs.st_mode);
  1074. #endif
  1075. }
  1076. else
  1077. {
  1078. return false;
  1079. }
  1080. }
  1081. int SystemTools::ChangeDirectory(const char *dir)
  1082. {
  1083. return Chdir(dir);
  1084. }
  1085. kwsys_std::string SystemTools::GetCurrentWorkingDirectory()
  1086. {
  1087. char buf[2048];
  1088. kwsys_std::string path = Getcwd(buf, 2048);
  1089. return path;
  1090. }
  1091. kwsys_std::string SystemTools::GetProgramPath(const char* in_name)
  1092. {
  1093. kwsys_std::string dir, file;
  1094. SystemTools::SplitProgramPath(in_name, dir, file);
  1095. return dir;
  1096. }
  1097. bool SystemTools::SplitProgramPath(const char* in_name,
  1098. kwsys_std::string& dir,
  1099. kwsys_std::string& file,
  1100. bool)
  1101. {
  1102. dir = in_name;
  1103. file = "";
  1104. SystemTools::ConvertToUnixSlashes(dir);
  1105. if(!SystemTools::FileIsDirectory(dir.c_str()))
  1106. {
  1107. kwsys_std::string::size_type slashPos = dir.rfind("/");
  1108. if(slashPos != kwsys_std::string::npos)
  1109. {
  1110. file = dir.substr(slashPos+1);
  1111. dir = dir.substr(0, slashPos);
  1112. }
  1113. else
  1114. {
  1115. file = dir;
  1116. dir = "";
  1117. }
  1118. }
  1119. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  1120. {
  1121. kwsys_std::string oldDir = in_name;
  1122. SystemTools::ConvertToUnixSlashes(oldDir);
  1123. dir = in_name;
  1124. return false;
  1125. }
  1126. return true;
  1127. }
  1128. kwsys_std::string SystemTools::CollapseFullPath(const char* in_relative)
  1129. {
  1130. return SystemTools::CollapseFullPath(in_relative, 0);
  1131. }
  1132. kwsys_std::string SystemTools::CollapseFullPath(const char* in_relative,
  1133. const char* in_base)
  1134. {
  1135. kwsys_std::string dir, file;
  1136. SystemTools::SplitProgramPath(in_relative, dir, file, false);
  1137. // Save original working directory.
  1138. kwsys_std::string orig = SystemTools::GetCurrentWorkingDirectory();
  1139. // Change to base of relative path.
  1140. if(in_base)
  1141. {
  1142. Chdir(in_base);
  1143. }
  1144. #ifdef _WIN32
  1145. // Follow relative path.
  1146. if(!(dir == ""))
  1147. {
  1148. Chdir(dir.c_str());
  1149. }
  1150. // Get the resulting directory.
  1151. kwsys_std::string newDir = SystemTools::GetCurrentWorkingDirectory();
  1152. // Add the file back on to the directory.
  1153. SystemTools::ConvertToUnixSlashes(newDir);
  1154. #else
  1155. # ifdef MAXPATHLEN
  1156. char resolved_name[MAXPATHLEN];
  1157. # else
  1158. # ifdef PATH_MAX
  1159. char resolved_name[PATH_MAX];
  1160. # else
  1161. char resolved_name[5024];
  1162. # endif
  1163. # endif
  1164. // Resolve relative path.
  1165. kwsys_std::string newDir;
  1166. if(!(dir == ""))
  1167. {
  1168. realpath(dir.c_str(), resolved_name);
  1169. newDir = resolved_name;
  1170. }
  1171. else
  1172. {
  1173. newDir = SystemTools::GetCurrentWorkingDirectory();
  1174. }
  1175. #endif
  1176. // Restore original working directory.
  1177. Chdir(orig.c_str());
  1178. // Construct and return the full path.
  1179. kwsys_std::string newPath = newDir;
  1180. if(!(file == ""))
  1181. {
  1182. newPath += "/";
  1183. newPath += file;
  1184. }
  1185. return newPath;
  1186. }
  1187. bool SystemTools::Split(const char* str, kwsys_std::vector<kwsys_std::string>& lines)
  1188. {
  1189. kwsys_std::string data(str);
  1190. kwsys_std::string::size_type lpos = 0;
  1191. while(lpos < data.length())
  1192. {
  1193. kwsys_std::string::size_type rpos = data.find_first_of("\n", lpos);
  1194. if(rpos == kwsys_std::string::npos)
  1195. {
  1196. // Line ends at end of string without a newline.
  1197. lines.push_back(data.substr(lpos));
  1198. return false;
  1199. }
  1200. if((rpos > lpos) && (data[rpos-1] == '\r'))
  1201. {
  1202. // Line ends in a "\r\n" pair, remove both characters.
  1203. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  1204. }
  1205. else
  1206. {
  1207. // Line ends in a "\n", remove the character.
  1208. lines.push_back(data.substr(lpos, rpos-lpos));
  1209. }
  1210. lpos = rpos+1;
  1211. }
  1212. return true;
  1213. }
  1214. /**
  1215. * Return path of a full filename (no trailing slashes).
  1216. * Warning: returned path is converted to Unix slashes format.
  1217. */
  1218. kwsys_std::string SystemTools::GetFilenamePath(const kwsys_std::string& filename)
  1219. {
  1220. kwsys_std::string fn = filename;
  1221. SystemTools::ConvertToUnixSlashes(fn);
  1222. kwsys_std::string::size_type slash_pos = fn.rfind("/");
  1223. if(slash_pos != kwsys_std::string::npos)
  1224. {
  1225. return fn.substr(0, slash_pos);
  1226. }
  1227. else
  1228. {
  1229. return "";
  1230. }
  1231. }
  1232. /**
  1233. * Return file name of a full filename (i.e. file name without path).
  1234. */
  1235. kwsys_std::string SystemTools::GetFilenameName(const kwsys_std::string& filename)
  1236. {
  1237. kwsys_std::string fn = filename;
  1238. SystemTools::ConvertToUnixSlashes(fn);
  1239. kwsys_std::string::size_type slash_pos = fn.rfind("/");
  1240. if(slash_pos != kwsys_std::string::npos)
  1241. {
  1242. return fn.substr(slash_pos + 1);
  1243. }
  1244. else
  1245. {
  1246. return filename;
  1247. }
  1248. }
  1249. /**
  1250. * Return file extension of a full filename (dot included).
  1251. * Warning: this is the longest extension (for example: .tar.gz)
  1252. */
  1253. kwsys_std::string SystemTools::GetFilenameExtension(const kwsys_std::string& filename)
  1254. {
  1255. kwsys_std::string name = SystemTools::GetFilenameName(filename);
  1256. kwsys_std::string::size_type dot_pos = name.find(".");
  1257. if(dot_pos != kwsys_std::string::npos)
  1258. {
  1259. return name.substr(dot_pos);
  1260. }
  1261. else
  1262. {
  1263. return "";
  1264. }
  1265. }
  1266. /**
  1267. * Return file extension of a full filename (dot included).
  1268. * Warning: this is the shortest extension (for example: .tar.gz)
  1269. */
  1270. kwsys_std::string SystemTools::GetFilenameLastExtension(const kwsys_std::string& filename)
  1271. {
  1272. kwsys_std::string name = SystemTools::GetFilenameName(filename);
  1273. kwsys_std::string::size_type dot_pos = name.rfind(".");
  1274. if(dot_pos != kwsys_std::string::npos)
  1275. {
  1276. return name.substr(dot_pos);
  1277. }
  1278. else
  1279. {
  1280. return "";
  1281. }
  1282. }
  1283. /**
  1284. * Return file name without extension of a full filename (i.e. without path).
  1285. * Warning: it considers the longest extension (for example: .tar.gz)
  1286. */
  1287. kwsys_std::string SystemTools::GetFilenameWithoutExtension(const kwsys_std::string& filename)
  1288. {
  1289. kwsys_std::string name = SystemTools::GetFilenameName(filename);
  1290. kwsys_std::string::size_type dot_pos = name.find(".");
  1291. if(dot_pos != kwsys_std::string::npos)
  1292. {
  1293. return name.substr(0, dot_pos);
  1294. }
  1295. else
  1296. {
  1297. return name;
  1298. }
  1299. }
  1300. /**
  1301. * Return file name without extension of a full filename (i.e. without path).
  1302. * Warning: it considers the last extension (for example: removes .gz
  1303. * from .tar.gz)
  1304. */
  1305. kwsys_std::string
  1306. SystemTools::GetFilenameWithoutLastExtension(const kwsys_std::string& filename)
  1307. {
  1308. kwsys_std::string name = SystemTools::GetFilenameName(filename);
  1309. kwsys_std::string::size_type dot_pos = name.rfind(".");
  1310. if(dot_pos != kwsys_std::string::npos)
  1311. {
  1312. return name.substr(0, dot_pos);
  1313. }
  1314. else
  1315. {
  1316. return name;
  1317. }
  1318. }
  1319. bool SystemTools::FileIsFullPath(const char* in_name)
  1320. {
  1321. kwsys_std::string name = in_name;
  1322. #if defined(_WIN32)
  1323. // On Windows, the name must be at least two characters long.
  1324. if(name.length() < 2)
  1325. {
  1326. return false;
  1327. }
  1328. if(name[1] == ':')
  1329. {
  1330. return true;
  1331. }
  1332. if(name[0] == '\\')
  1333. {
  1334. return true;
  1335. }
  1336. #else
  1337. // On UNIX, the name must be at least one character long.
  1338. if(name.length() < 1)
  1339. {
  1340. return false;
  1341. }
  1342. #endif
  1343. // On UNIX, the name must begin in a '/'.
  1344. // On Windows, if the name begins in a '/', then it is a full
  1345. // network path.
  1346. if(name[0] == '/')
  1347. {
  1348. return true;
  1349. }
  1350. return false;
  1351. }
  1352. bool SystemTools::GetShortPath(const char* path, kwsys_std::string& shortPath)
  1353. {
  1354. #if defined(WIN32) && !defined(__CYGWIN__)
  1355. const int size = int(strlen(path)) +1; // size of return
  1356. char *buffer = new char[size]; // create a buffer
  1357. char *tempPath = new char[size]; // create a buffer
  1358. int ret;
  1359. // if the path passed in has quotes around it, first remove the quotes
  1360. if (path[0] == '"' && path[strlen(path)-1] == '"')
  1361. {
  1362. strcpy(tempPath,path+1);
  1363. tempPath[strlen(tempPath)-1] = '\0';
  1364. }
  1365. else
  1366. {
  1367. strcpy(tempPath,path);
  1368. }
  1369. buffer[0] = 0;
  1370. ret = GetShortPathName(tempPath, buffer, size);
  1371. if(buffer[0] == 0 || ret > size)
  1372. {
  1373. delete [] buffer;
  1374. delete [] tempPath;
  1375. return false;
  1376. }
  1377. else
  1378. {
  1379. shortPath = buffer;
  1380. delete [] buffer;
  1381. delete [] tempPath;
  1382. return true;
  1383. }
  1384. #else
  1385. shortPath = path;
  1386. return true;
  1387. #endif
  1388. }
  1389. void SystemTools::SplitProgramFromArgs(const char* path,
  1390. kwsys_std::string& program, kwsys_std::string& args)
  1391. {
  1392. if(SystemTools::FileExists(path))
  1393. {
  1394. program = path;
  1395. args = "";
  1396. return;
  1397. }
  1398. kwsys_std::vector<kwsys_std::string> e;
  1399. kwsys_std::string findProg = SystemTools::FindProgram(path, e);
  1400. if(findProg.size())
  1401. {
  1402. program = findProg;
  1403. args = "";
  1404. return;
  1405. }
  1406. kwsys_std::string dir = path;
  1407. kwsys_std::string::size_type spacePos = dir.rfind(' ');
  1408. if(spacePos == kwsys_std::string::npos)
  1409. {
  1410. program = "";
  1411. args = "";
  1412. return;
  1413. }
  1414. while(spacePos != kwsys_std::string::npos)
  1415. {
  1416. kwsys_std::string tryProg = dir.substr(0, spacePos);
  1417. if(SystemTools::FileExists(tryProg.c_str()))
  1418. {
  1419. program = tryProg;
  1420. args = dir.substr(spacePos, dir.size()-spacePos);
  1421. return;
  1422. }
  1423. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  1424. if(findProg.size())
  1425. {
  1426. program = findProg;
  1427. args = dir.substr(spacePos, dir.size()-spacePos);
  1428. return;
  1429. }
  1430. spacePos = dir.rfind(' ', spacePos--);
  1431. }
  1432. program = "";
  1433. args = "";
  1434. }
  1435. kwsys_std::string SystemTools::GetCurrentDateTime(const char* format)
  1436. {
  1437. char buf[1024];
  1438. time_t t;
  1439. time(&t);
  1440. strftime(buf, sizeof(buf), format, localtime(&t));
  1441. return buf;
  1442. }
  1443. kwsys_std::string SystemTools::MakeCindentifier(const char* s)
  1444. {
  1445. kwsys_std::string str(s);
  1446. if (str.find_first_of("0123456789") == 0)
  1447. {
  1448. str = "_" + str;
  1449. }
  1450. kwsys_std::string permited_chars("_"
  1451. "abcdefghijklmnopqrstuvwxyz"
  1452. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1453. "0123456789");
  1454. kwsys_std::string::size_type pos = 0;
  1455. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_std::string::npos)
  1456. {
  1457. str[pos] = '_';
  1458. }
  1459. return str;
  1460. }
  1461. // Due to a buggy stream library on the HP and another on Mac OSX, we
  1462. // need this very carefully written version of getline. Returns true
  1463. // if any data were read before the end-of-file was reached.
  1464. bool SystemTools::GetLineFromStream(kwsys_std::istream& is, kwsys_std::string& line,
  1465. bool *has_newline /* = 0 */)
  1466. {
  1467. const int bufferSize = 1024;
  1468. char buffer[bufferSize];
  1469. line = "";
  1470. bool haveData = false;
  1471. if ( has_newline )
  1472. {
  1473. *has_newline = false;
  1474. }
  1475. // If no characters are read from the stream, the end of file has
  1476. // been reached.
  1477. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  1478. {
  1479. haveData = true;
  1480. line.append(buffer);
  1481. // If newline character was read, the gcount includes the
  1482. // character, but the buffer does not. The end of line has been
  1483. // reached.
  1484. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  1485. {
  1486. if ( has_newline )
  1487. {
  1488. *has_newline = true;
  1489. }
  1490. break;
  1491. }
  1492. // The fail bit may be set. Clear it.
  1493. is.clear(is.rdstate() & ~kwsys_std::ios::failbit);
  1494. }
  1495. return haveData;
  1496. }
  1497. } // namespace KWSYS_NAMESPACE
  1498. #if defined(_MSC_VER) && defined(_DEBUG)
  1499. # include <crtdbg.h>
  1500. # include <stdio.h>
  1501. # include <stdlib.h>
  1502. namespace KWSYS_NAMESPACE
  1503. {
  1504. static int SystemToolsDebugReport(int, char* message, int*)
  1505. {
  1506. fprintf(stderr, message);
  1507. exit(1);
  1508. }
  1509. void SystemTools::EnableMSVCDebugHook()
  1510. {
  1511. if(getenv("DART_TEST_FROM_DART"))
  1512. {
  1513. _CrtSetReportHook(SystemToolsDebugReport);
  1514. }
  1515. }
  1516. } // namespace KWSYS_NAMESPACE
  1517. #else
  1518. namespace KWSYS_NAMESPACE
  1519. {
  1520. void SystemTools::EnableMSVCDebugHook() {}
  1521. } // namespace KWSYS_NAMESPACE
  1522. #endif