SystemTools.cxx 42 KB

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