SystemTools.cxx 41 KB

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