SystemTools.cxx 42 KB

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