SystemTools.cxx 42 KB

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