SystemTools.cxx 43 KB

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