SystemTools.cxx 46 KB

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