SystemTools.cxx 40 KB

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