1
0

SystemTools.cxx 44 KB

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