SystemTools.cxx 40 KB

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