SystemTools.cxx 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676
  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 = 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. {
  1467. const int bufferSize = 1024;
  1468. char buffer[bufferSize];
  1469. line = "";
  1470. bool haveData = false;
  1471. // If no characters are read from the stream, the end of file has
  1472. // been reached.
  1473. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  1474. {
  1475. haveData = true;
  1476. line.append(buffer);
  1477. // If newline character was read, the gcount includes the
  1478. // character, but the buffer does not. The end of line has been
  1479. // reached.
  1480. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  1481. {
  1482. break;
  1483. }
  1484. // The fail bit may be set. Clear it.
  1485. is.clear(is.rdstate() & ~kwsys_std::ios::failbit);
  1486. }
  1487. return haveData;
  1488. }
  1489. } // namespace KWSYS_NAMESPACE
  1490. #if defined(_MSC_VER) && defined(_DEBUG)
  1491. # include <crtdbg.h>
  1492. # include <stdio.h>
  1493. # include <stdlib.h>
  1494. namespace KWSYS_NAMESPACE
  1495. {
  1496. static int SystemToolsDebugReport(int, char* message, int*)
  1497. {
  1498. fprintf(stderr, message);
  1499. exit(1);
  1500. return 0;
  1501. }
  1502. void SystemTools::EnableMSVCDebugHook()
  1503. {
  1504. if(getenv("DART_TEST_FROM_DART"))
  1505. {
  1506. _CrtSetReportHook(SystemToolsDebugReport);
  1507. }
  1508. }
  1509. } // namespace KWSYS_NAMESPACE
  1510. #else
  1511. namespace KWSYS_NAMESPACE
  1512. {
  1513. void SystemTools::EnableMSVCDebugHook() {}
  1514. } // namespace KWSYS_NAMESPACE
  1515. #endif