SystemTools.cxx 40 KB

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