SystemTools.cxx 44 KB

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