SystemTools.cxx 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461
  1. /*=========================================================================
  2. Program: KWSys - Kitware System Library
  3. Module: $RCSfile$
  4. Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.
  5. See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even
  7. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  8. PURPOSE. See the above copyright notices for more information.
  9. =========================================================================*/
  10. #include "kwsysPrivate.h"
  11. #include KWSYS_HEADER(SystemTools.hxx)
  12. #include KWSYS_HEADER(Directory.hxx)
  13. #include KWSYS_HEADER(ios/iostream)
  14. #include KWSYS_HEADER(ios/fstream)
  15. #include KWSYS_HEADER(ios/sstream)
  16. #ifdef _MSC_VER
  17. # pragma warning (disable: 4786)
  18. #endif
  19. #include <stdio.h>
  20. #include <sys/stat.h>
  21. #include <ctype.h>
  22. #include <errno.h>
  23. #include <time.h>
  24. // support for realpath call
  25. #ifndef _WIN32
  26. #include <limits.h>
  27. #include <stdlib.h>
  28. #include <sys/param.h>
  29. #include <sys/wait.h>
  30. #include <sys/ioctl.h>
  31. #include <unistd.h>
  32. #include <termios.h>
  33. #endif
  34. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__))
  35. #include <io.h>
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #include <windows.h>
  40. #include <direct.h>
  41. #define _unlink unlink
  42. inline int Mkdir(const char* dir)
  43. {
  44. return _mkdir(dir);
  45. }
  46. inline int Rmdir(const char* dir)
  47. {
  48. return _rmdir(dir);
  49. }
  50. inline const char* Getcwd(char* buf, unsigned int len)
  51. {
  52. return _getcwd(buf, len);
  53. }
  54. inline int Chdir(const char* dir)
  55. {
  56. #if defined(__BORLANDC__)
  57. return chdir(dir);
  58. #else
  59. return _chdir(dir);
  60. #endif
  61. }
  62. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  63. {
  64. char *ptemp;
  65. char fullpath[MAX_PATH];
  66. if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
  67. {
  68. resolved_path = fullpath;
  69. KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
  70. }
  71. }
  72. #else
  73. #include <sys/types.h>
  74. #include <fcntl.h>
  75. #include <unistd.h>
  76. inline int Mkdir(const char* dir)
  77. {
  78. return mkdir(dir, 00777);
  79. }
  80. inline int Rmdir(const char* dir)
  81. {
  82. return rmdir(dir);
  83. }
  84. inline const char* Getcwd(char* buf, unsigned int len)
  85. {
  86. return getcwd(buf, len);
  87. }
  88. inline int Chdir(const char* dir)
  89. {
  90. return chdir(dir);
  91. }
  92. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  93. {
  94. # ifdef MAXPATHLEN
  95. char resolved_name[MAXPATHLEN];
  96. # else
  97. # ifdef PATH_MAX
  98. char resolved_name[PATH_MAX];
  99. # else
  100. char resolved_name[5024];
  101. # endif //PATH_MAX
  102. # endif //MAXPATHLEN
  103. realpath(path, resolved_name);
  104. resolved_path = resolved_name;
  105. }
  106. #endif
  107. #if !defined(_WIN32) && defined(__COMO__)
  108. // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
  109. extern "C"
  110. {
  111. extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
  112. extern int pclose (FILE *__stream) __THROW;
  113. extern char *realpath (__const char *__restrict __name,
  114. char *__restrict __resolved) __THROW;
  115. extern char *strdup (__const char *__s) __THROW;
  116. extern int putenv (char *__string) __THROW;
  117. }
  118. #endif
  119. /* Implement floattime() for various platforms */
  120. // Taken from Python 2.1.3
  121. #if defined( _WIN32 ) && !defined( __CYGWIN__ )
  122. # include <sys/timeb.h>
  123. # define HAVE_FTIME
  124. # if defined( __BORLANDC__)
  125. # define FTIME ftime
  126. # define TIMEB timeb
  127. # else // Visual studio?
  128. # define FTIME _ftime
  129. # define TIMEB _timeb
  130. # endif
  131. #elif defined( __CYGWIN__ ) || defined( __linux__ )
  132. # include <sys/time.h>
  133. # include <time.h>
  134. # define HAVE_GETTIMEOFDAY
  135. #endif
  136. namespace KWSYS_NAMESPACE
  137. {
  138. class SystemToolsTranslationMap :
  139. public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
  140. {
  141. };
  142. double
  143. SystemTools::GetTime(void)
  144. {
  145. /* There are three ways to get the time:
  146. (1) gettimeofday() -- resolution in microseconds
  147. (2) ftime() -- resolution in milliseconds
  148. (3) time() -- resolution in seconds
  149. In all cases the return value is a float in seconds.
  150. Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
  151. fail, so we fall back on ftime() or time().
  152. Note: clock resolution does not imply clock accuracy! */
  153. #ifdef HAVE_GETTIMEOFDAY
  154. {
  155. struct timeval t;
  156. #ifdef GETTIMEOFDAY_NO_TZ
  157. if (gettimeofday(&t) == 0)
  158. return (double)t.tv_sec + t.tv_usec*0.000001;
  159. #else /* !GETTIMEOFDAY_NO_TZ */
  160. if (gettimeofday(&t, (struct timezone *)NULL) == 0)
  161. return (double)t.tv_sec + t.tv_usec*0.000001;
  162. #endif /* !GETTIMEOFDAY_NO_TZ */
  163. }
  164. #endif /* !HAVE_GETTIMEOFDAY */
  165. {
  166. #if defined(HAVE_FTIME)
  167. struct TIMEB t;
  168. ::FTIME(&t);
  169. return (double)t.time + (double)t.millitm * (double)0.001;
  170. #else /* !HAVE_FTIME */
  171. time_t secs;
  172. time(&secs);
  173. return (double)secs;
  174. #endif /* !HAVE_FTIME */
  175. }
  176. }
  177. // adds the elements of the env variable path to the arg passed in
  178. void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
  179. {
  180. #if defined(_WIN32) && !defined(__CYGWIN__)
  181. const char* pathSep = ";";
  182. #else
  183. const char* pathSep = ":";
  184. #endif
  185. if(!env)
  186. {
  187. env = "PATH";
  188. }
  189. const char* cpathEnv = SystemTools::GetEnv(env);
  190. if ( !cpathEnv )
  191. {
  192. return;
  193. }
  194. kwsys_stl::string pathEnv = cpathEnv;
  195. // A hack to make the below algorithm work.
  196. if(pathEnv[pathEnv.length()-1] != ':')
  197. {
  198. pathEnv += pathSep;
  199. }
  200. kwsys_stl::string::size_type start =0;
  201. bool done = false;
  202. while(!done)
  203. {
  204. kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
  205. if(endpos != kwsys_stl::string::npos)
  206. {
  207. path.push_back(pathEnv.substr(start, endpos-start));
  208. start = endpos+1;
  209. }
  210. else
  211. {
  212. done = true;
  213. }
  214. }
  215. for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
  216. i != path.end(); ++i)
  217. {
  218. SystemTools::ConvertToUnixSlashes(*i);
  219. }
  220. }
  221. const char* SystemTools::GetEnv(const char* key)
  222. {
  223. return getenv(key);
  224. }
  225. bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
  226. {
  227. const char* v = getenv(key);
  228. if(v)
  229. {
  230. result = v;
  231. return true;
  232. }
  233. else
  234. {
  235. return false;
  236. }
  237. }
  238. const char* SystemTools::GetExecutableExtension()
  239. {
  240. #if defined(_WIN32) || defined(__CYGWIN__)
  241. return ".exe";
  242. #else
  243. return "";
  244. #endif
  245. }
  246. bool SystemTools::MakeDirectory(const char* path)
  247. {
  248. if(SystemTools::FileExists(path))
  249. {
  250. return true;
  251. }
  252. kwsys_stl::string dir = path;
  253. if(dir.size() == 0)
  254. {
  255. return false;
  256. }
  257. SystemTools::ConvertToUnixSlashes(dir);
  258. kwsys_stl::string::size_type pos = dir.find(':');
  259. if(pos == kwsys_stl::string::npos)
  260. {
  261. pos = 0;
  262. }
  263. kwsys_stl::string topdir;
  264. while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
  265. {
  266. topdir = dir.substr(0, pos);
  267. Mkdir(topdir.c_str());
  268. pos++;
  269. }
  270. if(dir[dir.size()-1] == '/')
  271. {
  272. topdir = dir.substr(0, dir.size());
  273. }
  274. else
  275. {
  276. topdir = dir;
  277. }
  278. if(Mkdir(topdir.c_str()) != 0)
  279. {
  280. // There is a bug in the Borland Run time library which makes MKDIR
  281. // return EACCES when it should return EEXISTS
  282. // if it is some other error besides directory exists
  283. // then return false
  284. if( (errno != EEXIST)
  285. #ifdef __BORLANDC__
  286. && (errno != EACCES)
  287. #endif
  288. )
  289. {
  290. return false;
  291. }
  292. }
  293. return true;
  294. }
  295. // replace replace with with as many times as it shows up in source.
  296. // write the result into source.
  297. void SystemTools::ReplaceString(kwsys_stl::string& source,
  298. const char* replace,
  299. const char* with)
  300. {
  301. const char *src = source.c_str();
  302. char *searchPos = const_cast<char *>(strstr(src,replace));
  303. // get out quick if string is not found
  304. if (!searchPos)
  305. {
  306. return;
  307. }
  308. // perform replacements until done
  309. size_t replaceSize = strlen(replace);
  310. char *orig = strdup(src);
  311. char *currentPos = orig;
  312. searchPos = searchPos - src + orig;
  313. // initialize the result
  314. source.erase(source.begin(),source.end());
  315. do
  316. {
  317. *searchPos = '\0';
  318. source += currentPos;
  319. currentPos = searchPos + replaceSize;
  320. // replace
  321. source += with;
  322. searchPos = strstr(currentPos,replace);
  323. }
  324. while (searchPos);
  325. // copy any trailing text
  326. source += currentPos;
  327. free(orig);
  328. }
  329. // Read a registry value.
  330. // Example :
  331. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  332. // => will return the data of the "default" value of the key
  333. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  334. // => will return the data of the "Root" value of the key
  335. #if defined(_WIN32) && !defined(__CYGWIN__)
  336. bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value)
  337. {
  338. kwsys_stl::string primary = key;
  339. kwsys_stl::string second;
  340. kwsys_stl::string valuename;
  341. size_t start = primary.find("\\");
  342. if (start == kwsys_stl::string::npos)
  343. {
  344. return false;
  345. }
  346. size_t valuenamepos = primary.find(";");
  347. if (valuenamepos != kwsys_stl::string::npos)
  348. {
  349. valuename = primary.substr(valuenamepos+1);
  350. }
  351. second = primary.substr(start+1, valuenamepos-start-1);
  352. primary = primary.substr(0, start);
  353. HKEY primaryKey = HKEY_CURRENT_USER;
  354. if (primary == "HKEY_CURRENT_USER")
  355. {
  356. primaryKey = HKEY_CURRENT_USER;
  357. }
  358. if (primary == "HKEY_CURRENT_CONFIG")
  359. {
  360. primaryKey = HKEY_CURRENT_CONFIG;
  361. }
  362. if (primary == "HKEY_CLASSES_ROOT")
  363. {
  364. primaryKey = HKEY_CLASSES_ROOT;
  365. }
  366. if (primary == "HKEY_LOCAL_MACHINE")
  367. {
  368. primaryKey = HKEY_LOCAL_MACHINE;
  369. }
  370. if (primary == "HKEY_USERS")
  371. {
  372. primaryKey = HKEY_USERS;
  373. }
  374. HKEY hKey;
  375. if(RegOpenKeyEx(primaryKey,
  376. second.c_str(),
  377. 0,
  378. KEY_READ,
  379. &hKey) != ERROR_SUCCESS)
  380. {
  381. return false;
  382. }
  383. else
  384. {
  385. DWORD dwType, dwSize;
  386. dwSize = 1023;
  387. char data[1024];
  388. if(RegQueryValueEx(hKey,
  389. (LPTSTR)valuename.c_str(),
  390. NULL,
  391. &dwType,
  392. (BYTE *)data,
  393. &dwSize) == ERROR_SUCCESS)
  394. {
  395. if (dwType == REG_SZ)
  396. {
  397. value = data;
  398. RegCloseKey(hKey);
  399. return true;
  400. }
  401. }
  402. }
  403. return false;
  404. }
  405. #else
  406. bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &)
  407. {
  408. return false;
  409. }
  410. #endif
  411. // Write a registry value.
  412. // Example :
  413. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  414. // => will set the data of the "default" value of the key
  415. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  416. // => will set the data of the "Root" value of the key
  417. #if defined(_WIN32) && !defined(__CYGWIN__)
  418. bool SystemTools::WriteRegistryValue(const char *key, const char *value)
  419. {
  420. kwsys_stl::string primary = key;
  421. kwsys_stl::string second;
  422. kwsys_stl::string valuename;
  423. size_t start = primary.find("\\");
  424. if (start == kwsys_stl::string::npos)
  425. {
  426. return false;
  427. }
  428. size_t valuenamepos = primary.find(";");
  429. if (valuenamepos != kwsys_stl::string::npos)
  430. {
  431. valuename = primary.substr(valuenamepos+1);
  432. }
  433. second = primary.substr(start+1, valuenamepos-start-1);
  434. primary = primary.substr(0, start);
  435. HKEY primaryKey = HKEY_CURRENT_USER;
  436. if (primary == "HKEY_CURRENT_USER")
  437. {
  438. primaryKey = HKEY_CURRENT_USER;
  439. }
  440. if (primary == "HKEY_CURRENT_CONFIG")
  441. {
  442. primaryKey = HKEY_CURRENT_CONFIG;
  443. }
  444. if (primary == "HKEY_CLASSES_ROOT")
  445. {
  446. primaryKey = HKEY_CLASSES_ROOT;
  447. }
  448. if (primary == "HKEY_LOCAL_MACHINE")
  449. {
  450. primaryKey = HKEY_LOCAL_MACHINE;
  451. }
  452. if (primary == "HKEY_USERS")
  453. {
  454. primaryKey = HKEY_USERS;
  455. }
  456. HKEY hKey;
  457. DWORD dwDummy;
  458. if(RegCreateKeyEx(primaryKey,
  459. second.c_str(),
  460. 0,
  461. "",
  462. REG_OPTION_NON_VOLATILE,
  463. KEY_WRITE,
  464. NULL,
  465. &hKey,
  466. &dwDummy) != ERROR_SUCCESS)
  467. {
  468. return false;
  469. }
  470. if(RegSetValueEx(hKey,
  471. (LPTSTR)valuename.c_str(),
  472. 0,
  473. REG_SZ,
  474. (CONST BYTE *)value,
  475. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  476. {
  477. return true;
  478. }
  479. return false;
  480. }
  481. #else
  482. bool SystemTools::WriteRegistryValue(const char *, const char *)
  483. {
  484. return false;
  485. }
  486. #endif
  487. // Delete a registry value.
  488. // Example :
  489. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  490. // => will delete the data of the "default" value of the key
  491. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  492. // => will delete the data of the "Root" value of the key
  493. #if defined(_WIN32) && !defined(__CYGWIN__)
  494. bool SystemTools::DeleteRegistryValue(const char *key)
  495. {
  496. kwsys_stl::string primary = key;
  497. kwsys_stl::string second;
  498. kwsys_stl::string valuename;
  499. size_t start = primary.find("\\");
  500. if (start == kwsys_stl::string::npos)
  501. {
  502. return false;
  503. }
  504. size_t valuenamepos = primary.find(";");
  505. if (valuenamepos != kwsys_stl::string::npos)
  506. {
  507. valuename = primary.substr(valuenamepos+1);
  508. }
  509. second = primary.substr(start+1, valuenamepos-start-1);
  510. primary = primary.substr(0, start);
  511. HKEY primaryKey = HKEY_CURRENT_USER;
  512. if (primary == "HKEY_CURRENT_USER")
  513. {
  514. primaryKey = HKEY_CURRENT_USER;
  515. }
  516. if (primary == "HKEY_CURRENT_CONFIG")
  517. {
  518. primaryKey = HKEY_CURRENT_CONFIG;
  519. }
  520. if (primary == "HKEY_CLASSES_ROOT")
  521. {
  522. primaryKey = HKEY_CLASSES_ROOT;
  523. }
  524. if (primary == "HKEY_LOCAL_MACHINE")
  525. {
  526. primaryKey = HKEY_LOCAL_MACHINE;
  527. }
  528. if (primary == "HKEY_USERS")
  529. {
  530. primaryKey = HKEY_USERS;
  531. }
  532. HKEY hKey;
  533. if(RegOpenKeyEx(primaryKey,
  534. second.c_str(),
  535. 0,
  536. KEY_WRITE,
  537. &hKey) != ERROR_SUCCESS)
  538. {
  539. return false;
  540. }
  541. else
  542. {
  543. if(RegDeleteValue(hKey,
  544. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  545. {
  546. RegCloseKey(hKey);
  547. return true;
  548. }
  549. }
  550. return false;
  551. }
  552. #else
  553. bool SystemTools::DeleteRegistryValue(const char *)
  554. {
  555. return false;
  556. }
  557. #endif
  558. bool SystemTools::SameFile(const char* file1, const char* file2)
  559. {
  560. #ifdef _WIN32
  561. HANDLE hFile1, hFile2;
  562. hFile1 = CreateFile( file1,
  563. GENERIC_READ,
  564. FILE_SHARE_READ ,
  565. NULL,
  566. OPEN_EXISTING,
  567. FILE_FLAG_BACKUP_SEMANTICS,
  568. NULL
  569. );
  570. hFile2 = CreateFile( file2,
  571. GENERIC_READ,
  572. FILE_SHARE_READ,
  573. NULL,
  574. OPEN_EXISTING,
  575. FILE_FLAG_BACKUP_SEMANTICS,
  576. NULL
  577. );
  578. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  579. {
  580. if(hFile1 != INVALID_HANDLE_VALUE)
  581. {
  582. CloseHandle(hFile1);
  583. }
  584. if(hFile2 != INVALID_HANDLE_VALUE)
  585. {
  586. CloseHandle(hFile2);
  587. }
  588. return false;
  589. }
  590. BY_HANDLE_FILE_INFORMATION fiBuf1;
  591. BY_HANDLE_FILE_INFORMATION fiBuf2;
  592. GetFileInformationByHandle( hFile1, &fiBuf1 );
  593. GetFileInformationByHandle( hFile2, &fiBuf2 );
  594. CloseHandle(hFile1);
  595. CloseHandle(hFile2);
  596. return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
  597. fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  598. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  599. #else
  600. struct stat fileStat1, fileStat2;
  601. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  602. {
  603. // see if the files are the same file
  604. // check the device inode and size
  605. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  606. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  607. fileStat2.st_size == fileStat1.st_size
  608. )
  609. {
  610. return true;
  611. }
  612. }
  613. return false;
  614. #endif
  615. }
  616. // return true if the file exists
  617. bool SystemTools::FileExists(const char* filename)
  618. {
  619. #ifdef _MSC_VER
  620. # define access _access
  621. #endif
  622. #ifndef R_OK
  623. # define R_OK 04
  624. #endif
  625. if ( access(filename, R_OK) != 0 )
  626. {
  627. return false;
  628. }
  629. else
  630. {
  631. return true;
  632. }
  633. }
  634. bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
  635. int* result)
  636. {
  637. // Default to same time.
  638. *result = 0;
  639. #if !defined(_WIN32) || defined(__CYGWIN__)
  640. // POSIX version. Use stat function to get file modification time.
  641. struct stat s1;
  642. if(stat(f1, &s1) != 0)
  643. {
  644. return false;
  645. }
  646. struct stat s2;
  647. if(stat(f2, &s2) != 0)
  648. {
  649. return false;
  650. }
  651. # if KWSYS_STAT_HAS_ST_MTIM
  652. // Compare using nanosecond resolution.
  653. if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
  654. {
  655. *result = -1;
  656. }
  657. else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
  658. {
  659. *result = 1;
  660. }
  661. else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
  662. {
  663. *result = -1;
  664. }
  665. else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
  666. {
  667. *result = 1;
  668. }
  669. # else
  670. // Compare using 1 second resolution.
  671. if(s1.st_mtime < s2.st_mtime)
  672. {
  673. *result = -1;
  674. }
  675. else if(s1.st_mtime > s2.st_mtime)
  676. {
  677. *result = 1;
  678. }
  679. # endif
  680. #else
  681. // Windows version. Create file handles and get the modification times.
  682. HANDLE hf1 = CreateFile(f1, GENERIC_READ, FILE_SHARE_READ,
  683. NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
  684. NULL);
  685. if(hf1 == INVALID_HANDLE_VALUE)
  686. {
  687. return false;
  688. }
  689. FILETIME tf1;
  690. if(!GetFileTime(hf1, 0, 0, &tf1))
  691. {
  692. CloseHandle(hf1);
  693. return false;
  694. }
  695. CloseHandle(hf1);
  696. HANDLE hf2 = CreateFile(f2, GENERIC_READ, FILE_SHARE_READ,
  697. NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
  698. NULL);
  699. if(hf2 == INVALID_HANDLE_VALUE)
  700. {
  701. return false;
  702. }
  703. FILETIME tf2;
  704. if(!GetFileTime(hf2, 0, 0, &tf2))
  705. {
  706. CloseHandle(hf2);
  707. return false;
  708. }
  709. CloseHandle(hf2);
  710. // Compare the file times using resolution provided by system call.
  711. *result = (int)CompareFileTime(&tf1, &tf2);
  712. #endif
  713. return true;
  714. }
  715. // Return a capitalized string (i.e the first letter is uppercased, all other
  716. // are lowercased)
  717. kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
  718. {
  719. kwsys_stl::string n;
  720. if(s.size() == 0)
  721. {
  722. return n;
  723. }
  724. n.resize(s.size());
  725. n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
  726. for (size_t i = 1; i < s.size(); i++)
  727. {
  728. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  729. }
  730. return n;
  731. }
  732. // Return a lower case string
  733. kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
  734. {
  735. kwsys_stl::string n;
  736. n.resize(s.size());
  737. for (size_t i = 0; i < s.size(); i++)
  738. {
  739. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  740. }
  741. return n;
  742. }
  743. // Return a lower case string
  744. kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
  745. {
  746. kwsys_stl::string n;
  747. n.resize(s.size());
  748. for (size_t i = 0; i < s.size(); i++)
  749. {
  750. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  751. }
  752. return n;
  753. }
  754. // convert windows slashes to unix slashes
  755. void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
  756. {
  757. kwsys_stl::string::size_type pos = 0;
  758. while((pos = path.find('\\', pos)) != kwsys_stl::string::npos)
  759. {
  760. // make sure we don't convert an escaped space to a unix slash
  761. if(pos < path.size()-1)
  762. {
  763. if(path[pos+1] != ' ')
  764. {
  765. path[pos] = '/';
  766. }
  767. }
  768. pos++;
  769. }
  770. // Remove all // from the path just like most unix shells
  771. int start_find;
  772. #ifdef _WIN32
  773. // However, on windows if the first characters are both slashes,
  774. // then keep them that way, so that network paths can be handled.
  775. start_find = 1;
  776. #else
  777. start_find = 0;
  778. #endif
  779. while((pos = path.find("//", start_find)) != kwsys_stl::string::npos)
  780. {
  781. SystemTools::ReplaceString(path, "//", "/");
  782. }
  783. // remove any trailing slash
  784. if(path.size() > 1 && path[path.size()-1] == '/')
  785. {
  786. path = path.substr(0, path.size()-1);
  787. }
  788. // if there is a tilda ~ then replace it with HOME
  789. if(path.find("~") == 0)
  790. {
  791. if (getenv("HOME"))
  792. {
  793. path = kwsys_stl::string(getenv("HOME")) + path.substr(1);
  794. }
  795. }
  796. }
  797. // change // to /, and escape any spaces in the path
  798. kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
  799. {
  800. kwsys_stl::string ret = path;
  801. // remove // except at the beginning might be a cygwin drive
  802. kwsys_stl::string::size_type pos = 1;
  803. while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
  804. {
  805. ret.erase(pos, 1);
  806. }
  807. // now escape spaces if there is a space in the path
  808. if(ret.find(" ") != kwsys_stl::string::npos)
  809. {
  810. kwsys_stl::string result = "";
  811. char lastch = 1;
  812. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  813. {
  814. // if it is already escaped then don't try to escape it again
  815. if(*ch == ' ' && lastch != '\\')
  816. {
  817. result += '\\';
  818. }
  819. result += *ch;
  820. lastch = *ch;
  821. }
  822. ret = result;
  823. }
  824. return ret;
  825. }
  826. kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
  827. {
  828. #if defined(_WIN32) && !defined(__CYGWIN__)
  829. return SystemTools::ConvertToWindowsOutputPath(path);
  830. #else
  831. return SystemTools::ConvertToUnixOutputPath(path);
  832. #endif
  833. }
  834. // remove double slashes not at the start
  835. kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  836. {
  837. kwsys_stl::string ret = path;
  838. kwsys_stl::string::size_type pos = 0;
  839. // first convert all of the slashes
  840. while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
  841. {
  842. ret[pos] = '\\';
  843. pos++;
  844. }
  845. // check for really small paths
  846. if(ret.size() < 2)
  847. {
  848. return ret;
  849. }
  850. // now clean up a bit and remove double slashes
  851. // Only if it is not the first position in the path which is a network
  852. // path on windows
  853. pos = 1; // start at position 1
  854. if(ret[0] == '\"')
  855. {
  856. pos = 2; // if the string is already quoted then start at 2
  857. if(ret.size() < 3)
  858. {
  859. return ret;
  860. }
  861. }
  862. while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
  863. {
  864. ret.erase(pos, 1);
  865. }
  866. // now double quote the path if it has spaces in it
  867. // and is not already double quoted
  868. if(ret.find(" ") != kwsys_stl::string::npos
  869. && ret[0] != '\"')
  870. {
  871. kwsys_stl::string result;
  872. result = "\"" + ret + "\"";
  873. ret = result;
  874. }
  875. return ret;
  876. }
  877. bool SystemTools::CopyFileIfDifferent(const char* source,
  878. const char* destination)
  879. {
  880. if(SystemTools::FilesDiffer(source, destination))
  881. {
  882. return SystemTools::CopyFileAlways(source, destination);
  883. }
  884. return true;
  885. }
  886. bool SystemTools::FilesDiffer(const char* source,
  887. const char* destination)
  888. {
  889. struct stat statSource;
  890. if (stat(source, &statSource) != 0)
  891. {
  892. return true;
  893. }
  894. struct stat statDestination;
  895. if (stat(destination, &statDestination) != 0)
  896. {
  897. return true;
  898. }
  899. if(statSource.st_size != statDestination.st_size)
  900. {
  901. return true;
  902. }
  903. if(statSource.st_size == 0)
  904. {
  905. return false;
  906. }
  907. #if defined(_WIN32) || defined(__CYGWIN__)
  908. kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
  909. kwsys_ios::ios::in));
  910. kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
  911. kwsys_ios::ios::in));
  912. #else
  913. kwsys_ios::ifstream finSource(source);
  914. kwsys_ios::ifstream finDestination(destination);
  915. #endif
  916. if(!finSource || !finDestination)
  917. {
  918. return true;
  919. }
  920. char* source_buf = new char[statSource.st_size];
  921. char* dest_buf = new char[statSource.st_size];
  922. finSource.read(source_buf, statSource.st_size);
  923. finDestination.read(dest_buf, statSource.st_size);
  924. if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
  925. statSource.st_size != static_cast<long>(finDestination.gcount()))
  926. {
  927. // Failed to read files.
  928. delete [] source_buf;
  929. delete [] dest_buf;
  930. return true;
  931. }
  932. int ret = memcmp((const void*)source_buf,
  933. (const void*)dest_buf,
  934. statSource.st_size);
  935. delete [] dest_buf;
  936. delete [] source_buf;
  937. return ret != 0;
  938. }
  939. /**
  940. * Copy a file named by "source" to the file named by "destination".
  941. */
  942. bool SystemTools::CopyFileAlways(const char* source, const char* destination)
  943. {
  944. // If files are the same do not copy
  945. if ( SystemTools::SameFile(source, destination) )
  946. {
  947. return true;
  948. }
  949. mode_t perm = 0;
  950. bool perms = SystemTools::GetPermissions(source, perm);
  951. const int bufferSize = 4096;
  952. char buffer[bufferSize];
  953. // If destination is a directory, try to create a file with the same
  954. // name as the source in that directory.
  955. kwsys_stl::string new_destination;
  956. if(SystemTools::FileExists(destination) &&
  957. SystemTools::FileIsDirectory(destination))
  958. {
  959. new_destination = destination;
  960. SystemTools::ConvertToUnixSlashes(new_destination);
  961. new_destination += '/';
  962. kwsys_stl::string source_name = source;
  963. new_destination += SystemTools::GetFilenameName(source_name);
  964. destination = new_destination.c_str();
  965. }
  966. // Create destination directory
  967. kwsys_stl::string destination_dir = destination;
  968. destination_dir = SystemTools::GetFilenamePath(destination_dir);
  969. SystemTools::MakeDirectory(destination_dir.c_str());
  970. // Open files
  971. #if defined(_WIN32) || defined(__CYGWIN__)
  972. kwsys_ios::ifstream fin(source,
  973. kwsys_ios::ios::binary | kwsys_ios::ios::in);
  974. #else
  975. kwsys_ios::ifstream fin(source);
  976. #endif
  977. if(!fin)
  978. {
  979. return false;
  980. }
  981. // try and remove the destination file so that read only destination files
  982. // can be written to.
  983. // If the remove fails continue so that files in read only directories
  984. // that do not allow file removal can be modified.
  985. SystemTools::RemoveFile(destination);
  986. #if defined(_WIN32) || defined(__CYGWIN__)
  987. kwsys_ios::ofstream fout(destination,
  988. kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  989. #else
  990. kwsys_ios::ofstream fout(destination,
  991. kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  992. #endif
  993. if(!fout)
  994. {
  995. return false;
  996. }
  997. // This copy loop is very sensitive on certain platforms with
  998. // slightly broken stream libraries (like HPUX). Normally, it is
  999. // incorrect to not check the error condition on the fin.read()
  1000. // before using the data, but the fin.gcount() will be zero if an
  1001. // error occurred. Therefore, the loop should be safe everywhere.
  1002. while(fin)
  1003. {
  1004. fin.read(buffer, bufferSize);
  1005. if(fin.gcount())
  1006. {
  1007. fout.write(buffer, fin.gcount());
  1008. }
  1009. }
  1010. // Make sure the operating system has finished writing the file
  1011. // before closing it. This will ensure the file is finished before
  1012. // the check below.
  1013. fout.flush();
  1014. fin.close();
  1015. fout.close();
  1016. // More checks.
  1017. struct stat statSource, statDestination;
  1018. statSource.st_size = 12345;
  1019. statDestination.st_size = 12345;
  1020. if(stat(source, &statSource) != 0)
  1021. {
  1022. return false;
  1023. }
  1024. else if(stat(destination, &statDestination) != 0)
  1025. {
  1026. return false;
  1027. }
  1028. else if(statSource.st_size != statDestination.st_size)
  1029. {
  1030. return false;
  1031. }
  1032. if ( perms )
  1033. {
  1034. if ( !SystemTools::SetPermissions(destination, perm) )
  1035. {
  1036. return false;
  1037. }
  1038. }
  1039. return true;
  1040. }
  1041. /**
  1042. * Copy a directory content from "source" directory to the directory named by
  1043. * "destination".
  1044. */
  1045. bool SystemTools::CopyADirectory(const char* source, const char* destination)
  1046. {
  1047. Directory dir;
  1048. dir.Load(source);
  1049. size_t fileNum;
  1050. if ( !SystemTools::MakeDirectory(destination) )
  1051. {
  1052. return false;
  1053. }
  1054. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1055. {
  1056. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1057. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1058. {
  1059. kwsys_stl::string fullPath = source;
  1060. fullPath += "/";
  1061. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1062. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  1063. {
  1064. kwsys_stl::string fullDestPath = destination;
  1065. fullDestPath += "/";
  1066. fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1067. if (!SystemTools::CopyADirectory(fullPath.c_str(), fullDestPath.c_str()))
  1068. {
  1069. return false;
  1070. }
  1071. }
  1072. else
  1073. {
  1074. if(!SystemTools::CopyFileAlways(fullPath.c_str(), destination))
  1075. {
  1076. return false;
  1077. }
  1078. }
  1079. }
  1080. }
  1081. return true;
  1082. }
  1083. // return size of file; also returns zero if no file exists
  1084. unsigned long SystemTools::FileLength(const char* filename)
  1085. {
  1086. struct stat fs;
  1087. if (stat(filename, &fs) != 0)
  1088. {
  1089. return 0;
  1090. }
  1091. else
  1092. {
  1093. return fs.st_size;
  1094. }
  1095. }
  1096. int SystemTools::Strucmp(const char *s1, const char *s2)
  1097. {
  1098. // lifted from Graphvis http://www.graphviz.org
  1099. while ((*s1 != '\0')
  1100. && (tolower(*s1) == tolower(*s2)))
  1101. {
  1102. s1++;
  1103. s2++;
  1104. }
  1105. return tolower(*s1) - tolower(*s2);
  1106. }
  1107. // return true if the file exists
  1108. long int SystemTools::ModifiedTime(const char* filename)
  1109. {
  1110. struct stat fs;
  1111. if (stat(filename, &fs) != 0)
  1112. {
  1113. return 0;
  1114. }
  1115. else
  1116. {
  1117. return (long int)fs.st_mtime;
  1118. }
  1119. }
  1120. kwsys_stl::string SystemTools::GetLastSystemError()
  1121. {
  1122. int e = errno;
  1123. return strerror(e);
  1124. }
  1125. bool SystemTools::RemoveFile(const char* source)
  1126. {
  1127. #ifdef _WIN32
  1128. mode_t mode;
  1129. if ( !SystemTools::GetPermissions(source, mode) )
  1130. {
  1131. return false;
  1132. }
  1133. /* Win32 unlink is stupid --- it fails if the file is read-only */
  1134. SystemTools::SetPermissions(source, S_IWRITE);
  1135. #endif
  1136. bool res = unlink(source) != 0 ? false : true;
  1137. #ifdef _WIN32
  1138. if ( !res )
  1139. {
  1140. SystemTools::SetPermissions(source, mode);
  1141. }
  1142. #endif
  1143. return res;
  1144. }
  1145. bool SystemTools::RemoveADirectory(const char* source)
  1146. {
  1147. Directory dir;
  1148. dir.Load(source);
  1149. size_t fileNum;
  1150. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1151. {
  1152. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1153. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1154. {
  1155. kwsys_stl::string fullPath = source;
  1156. fullPath += "/";
  1157. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1158. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  1159. {
  1160. if (!SystemTools::RemoveADirectory(fullPath.c_str()))
  1161. {
  1162. return false;
  1163. }
  1164. }
  1165. else
  1166. {
  1167. if(!SystemTools::RemoveFile(fullPath.c_str()))
  1168. {
  1169. return false;
  1170. }
  1171. }
  1172. }
  1173. }
  1174. return (Rmdir(source) == 0);
  1175. }
  1176. /**
  1177. * Find the file the given name. Searches the given path and then
  1178. * the system search path. Returns the full path to the file if it is
  1179. * found. Otherwise, the empty string is returned.
  1180. */
  1181. kwsys_stl::string SystemTools
  1182. ::FindFile(const char* name,
  1183. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1184. {
  1185. // Add the system search path to our path first
  1186. kwsys_stl::vector<kwsys_stl::string> path;
  1187. SystemTools::GetPath(path, "CMAKE_FILE_PATH");
  1188. SystemTools::GetPath(path);
  1189. // now add the additional paths
  1190. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1191. // now look for the file
  1192. kwsys_stl::string tryPath;
  1193. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1194. p != path.end(); ++p)
  1195. {
  1196. tryPath = *p;
  1197. tryPath += "/";
  1198. tryPath += name;
  1199. if(SystemTools::FileExists(tryPath.c_str()) &&
  1200. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1201. {
  1202. return SystemTools::CollapseFullPath(tryPath.c_str());
  1203. }
  1204. }
  1205. // Couldn't find the file.
  1206. return "";
  1207. }
  1208. /**
  1209. * Find the executable with the given name. Searches the given path and then
  1210. * the system search path. Returns the full path to the executable if it is
  1211. * found. Otherwise, the empty string is returned.
  1212. */
  1213. kwsys_stl::string SystemTools::FindProgram(
  1214. const char* name,
  1215. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1216. bool no_system_path)
  1217. {
  1218. if(!name)
  1219. {
  1220. return "";
  1221. }
  1222. // See if the executable exists as written.
  1223. if(SystemTools::FileExists(name) &&
  1224. !SystemTools::FileIsDirectory(name))
  1225. {
  1226. return SystemTools::CollapseFullPath(name);
  1227. }
  1228. kwsys_stl::string tryPath = name;
  1229. tryPath += SystemTools::GetExecutableExtension();
  1230. if(SystemTools::FileExists(tryPath.c_str()) &&
  1231. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1232. {
  1233. return SystemTools::CollapseFullPath(tryPath.c_str());
  1234. }
  1235. kwsys_stl::vector<kwsys_stl::string> path;
  1236. SystemTools::GetPath(path, "CMAKE_PROGRAM_PATH");
  1237. // Add the system search path to our path.
  1238. if (!no_system_path)
  1239. {
  1240. SystemTools::GetPath(path);
  1241. }
  1242. // now add the additional paths
  1243. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1244. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1245. p != path.end(); ++p)
  1246. {
  1247. tryPath = *p;
  1248. tryPath += "/";
  1249. tryPath += name;
  1250. if(SystemTools::FileExists(tryPath.c_str()) &&
  1251. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1252. {
  1253. return SystemTools::CollapseFullPath(tryPath.c_str());
  1254. }
  1255. #ifdef _WIN32
  1256. tryPath += ".com";
  1257. if(SystemTools::FileExists(tryPath.c_str()) &&
  1258. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1259. {
  1260. return SystemTools::CollapseFullPath(tryPath.c_str());
  1261. }
  1262. tryPath = *p;
  1263. tryPath += "/";
  1264. tryPath += name;
  1265. #endif
  1266. tryPath += SystemTools::GetExecutableExtension();
  1267. if(SystemTools::FileExists(tryPath.c_str()) &&
  1268. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1269. {
  1270. return SystemTools::CollapseFullPath(tryPath.c_str());
  1271. }
  1272. }
  1273. // Couldn't find the program.
  1274. return "";
  1275. }
  1276. /**
  1277. * Find the library with the given name. Searches the given path and then
  1278. * the system search path. Returns the full path to the library if it is
  1279. * found. Otherwise, the empty string is returned.
  1280. */
  1281. kwsys_stl::string SystemTools
  1282. ::FindLibrary(const char* name,
  1283. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1284. {
  1285. // See if the executable exists as written.
  1286. if(SystemTools::FileExists(name) &&
  1287. !SystemTools::FileIsDirectory(name))
  1288. {
  1289. return SystemTools::CollapseFullPath(name);
  1290. }
  1291. // Add the system search path to our path.
  1292. kwsys_stl::vector<kwsys_stl::string> path;
  1293. SystemTools::GetPath(path);
  1294. // now add the additional paths
  1295. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1296. kwsys_stl::string tryPath;
  1297. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1298. p != path.end(); ++p)
  1299. {
  1300. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
  1301. tryPath = *p;
  1302. tryPath += "/";
  1303. tryPath += name;
  1304. tryPath += ".lib";
  1305. if(SystemTools::FileExists(tryPath.c_str())
  1306. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1307. {
  1308. return SystemTools::CollapseFullPath(tryPath.c_str());
  1309. }
  1310. #else
  1311. tryPath = *p;
  1312. tryPath += "/lib";
  1313. tryPath += name;
  1314. tryPath += ".so";
  1315. if(SystemTools::FileExists(tryPath.c_str())
  1316. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1317. {
  1318. return SystemTools::CollapseFullPath(tryPath.c_str());
  1319. }
  1320. tryPath = *p;
  1321. tryPath += "/lib";
  1322. tryPath += name;
  1323. tryPath += ".a";
  1324. if(SystemTools::FileExists(tryPath.c_str())
  1325. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1326. {
  1327. return SystemTools::CollapseFullPath(tryPath.c_str());
  1328. }
  1329. tryPath = *p;
  1330. tryPath += "/lib";
  1331. tryPath += name;
  1332. tryPath += ".sl";
  1333. if(SystemTools::FileExists(tryPath.c_str())
  1334. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1335. {
  1336. return SystemTools::CollapseFullPath(tryPath.c_str());
  1337. }
  1338. tryPath = *p;
  1339. tryPath += "/lib";
  1340. tryPath += name;
  1341. tryPath += ".dylib";
  1342. if(SystemTools::FileExists(tryPath.c_str())
  1343. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1344. {
  1345. return SystemTools::CollapseFullPath(tryPath.c_str());
  1346. }
  1347. tryPath = *p;
  1348. tryPath += "/lib";
  1349. tryPath += name;
  1350. tryPath += ".dll";
  1351. if(SystemTools::FileExists(tryPath.c_str())
  1352. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1353. {
  1354. return SystemTools::CollapseFullPath(tryPath.c_str());
  1355. }
  1356. #endif
  1357. }
  1358. // Couldn't find the library.
  1359. return "";
  1360. }
  1361. bool SystemTools::FileIsDirectory(const char* name)
  1362. {
  1363. struct stat fs;
  1364. if(stat(name, &fs) == 0)
  1365. {
  1366. #if _WIN32
  1367. return ((fs.st_mode & _S_IFDIR) != 0);
  1368. #else
  1369. return S_ISDIR(fs.st_mode);
  1370. #endif
  1371. }
  1372. else
  1373. {
  1374. return false;
  1375. }
  1376. }
  1377. int SystemTools::ChangeDirectory(const char *dir)
  1378. {
  1379. return Chdir(dir);
  1380. }
  1381. kwsys_stl::string SystemTools::GetCurrentWorkingDirectory()
  1382. {
  1383. char buf[2048];
  1384. const char* cwd = Getcwd(buf, 2048);
  1385. kwsys_stl::string path;
  1386. if ( cwd )
  1387. {
  1388. path = cwd;
  1389. }
  1390. return SystemTools::CollapseFullPath(path.c_str());
  1391. }
  1392. kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
  1393. {
  1394. kwsys_stl::string dir, file;
  1395. SystemTools::SplitProgramPath(in_name, dir, file);
  1396. return dir;
  1397. }
  1398. bool SystemTools::SplitProgramPath(const char* in_name,
  1399. kwsys_stl::string& dir,
  1400. kwsys_stl::string& file,
  1401. bool)
  1402. {
  1403. dir = in_name;
  1404. file = "";
  1405. SystemTools::ConvertToUnixSlashes(dir);
  1406. if(!SystemTools::FileIsDirectory(dir.c_str()))
  1407. {
  1408. kwsys_stl::string::size_type slashPos = dir.rfind("/");
  1409. if(slashPos != kwsys_stl::string::npos)
  1410. {
  1411. file = dir.substr(slashPos+1);
  1412. dir = dir.substr(0, slashPos);
  1413. }
  1414. else
  1415. {
  1416. file = dir;
  1417. dir = "";
  1418. }
  1419. }
  1420. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  1421. {
  1422. kwsys_stl::string oldDir = in_name;
  1423. SystemTools::ConvertToUnixSlashes(oldDir);
  1424. dir = in_name;
  1425. return false;
  1426. }
  1427. return true;
  1428. }
  1429. bool SystemTools::FindProgramPath(const char* argv0,
  1430. kwsys_stl::string& pathOut,
  1431. kwsys_stl::string& errorMsg,
  1432. const char* exeName,
  1433. const char* buildDir,
  1434. const char* installPrefix )
  1435. {
  1436. kwsys_stl::vector<kwsys_stl::string> failures;
  1437. kwsys_stl::string self = argv0;
  1438. SystemTools::ConvertToUnixSlashes(self);
  1439. failures.push_back(argv0);
  1440. self = SystemTools::FindProgram(self.c_str());
  1441. if(!SystemTools::FileExists(self.c_str()))
  1442. {
  1443. if(buildDir)
  1444. {
  1445. kwsys_stl::string intdir = ".";
  1446. #ifdef CMAKE_INTDIR
  1447. intdir = CMAKE_INTDIR;
  1448. #endif
  1449. self = buildDir;
  1450. self += "/bin/";
  1451. self += intdir;
  1452. self += "/";
  1453. self += exeName;
  1454. self += SystemTools::GetExecutableExtension();
  1455. }
  1456. }
  1457. if(installPrefix)
  1458. {
  1459. if(!SystemTools::FileExists(self.c_str()))
  1460. {
  1461. failures.push_back(self);
  1462. self = installPrefix;
  1463. self += "/bin/";
  1464. self += exeName;
  1465. }
  1466. }
  1467. if(!SystemTools::FileExists(self.c_str()))
  1468. {
  1469. failures.push_back(self);
  1470. kwsys_ios::ostringstream msg;
  1471. msg << "Can not find the command line program " << exeName << "\n";
  1472. msg << " argv[0] = \"" << argv0 << "\"\n";
  1473. msg << " Attempted paths:\n";
  1474. kwsys_stl::vector<kwsys_stl::string>::iterator i;
  1475. for(i=failures.begin(); i != failures.end(); ++i)
  1476. {
  1477. msg << " \"" << i->c_str() << "\"\n";
  1478. }
  1479. errorMsg = msg.str();
  1480. return false;
  1481. }
  1482. pathOut = self;
  1483. return true;
  1484. }
  1485. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
  1486. {
  1487. return SystemTools::CollapseFullPath(in_relative, 0);
  1488. }
  1489. void SystemTools::AddTranslationPath(const char * a, const char * b)
  1490. {
  1491. kwsys_stl::string path_a = a;
  1492. kwsys_stl::string path_b = b;
  1493. SystemTools::ConvertToUnixSlashes(path_a);
  1494. SystemTools::ConvertToUnixSlashes(path_b);
  1495. // First check this is a directory path, since we don't want the table to
  1496. // grow too fat
  1497. if( SystemTools::FileIsDirectory( path_a.c_str() ) )
  1498. {
  1499. // Make sure the path is a full path and does not contain no '..'
  1500. if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
  1501. == kwsys_stl::string::npos )
  1502. {
  1503. // Before inserting make sure path ends with '/'
  1504. if(path_a.size() && path_a[path_a.size() -1] != '/')
  1505. {
  1506. path_a += '/';
  1507. }
  1508. if(path_b.size() && path_b[path_b.size() -1] != '/')
  1509. {
  1510. path_b += '/';
  1511. }
  1512. if( !(path_a == path_b) )
  1513. {
  1514. SystemTools::TranslationMap->insert(
  1515. SystemToolsTranslationMap::value_type(path_a, path_b));
  1516. }
  1517. }
  1518. }
  1519. }
  1520. void SystemTools::AddKeepPath(const char* dir)
  1521. {
  1522. kwsys_stl::string cdir = SystemTools::CollapseFullPath(dir);
  1523. SystemTools::AddTranslationPath(cdir.c_str(), dir);
  1524. }
  1525. void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
  1526. {
  1527. // Do not translate paths that are too short to have meaningful
  1528. // translations.
  1529. if(path.size() < 2)
  1530. {
  1531. return;
  1532. }
  1533. // Always add a trailing slash before translation. It does not
  1534. // matter if this adds an extra slash, but we do not want to
  1535. // translate part of a directory (like the foo part of foo-dir).
  1536. path += "/";
  1537. // In case a file was specified we still have to go through this:
  1538. // Now convert any path found in the table back to the one desired:
  1539. kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
  1540. for(it = SystemTools::TranslationMap->begin();
  1541. it != SystemTools::TranslationMap->end();
  1542. ++it )
  1543. {
  1544. // We need to check of the path is a substring of the other path
  1545. if(path.find( it->first ) == 0)
  1546. {
  1547. path = path.replace( 0, it->first.size(), it->second);
  1548. }
  1549. }
  1550. // Remove the trailing slash we added before.
  1551. path.erase(path.end()-1, path.end());
  1552. }
  1553. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative,
  1554. const char* in_base)
  1555. {
  1556. kwsys_stl::string orig;
  1557. // Change to base of relative path.
  1558. if(in_base)
  1559. {
  1560. // Save original working directory.
  1561. orig = SystemTools::GetCurrentWorkingDirectory();
  1562. Chdir(in_base);
  1563. }
  1564. kwsys_stl::string dir, file;
  1565. SystemTools::SplitProgramPath(in_relative, dir, file, false);
  1566. if(dir.size() == 0 &&
  1567. in_relative && strlen(in_relative) > 0 &&
  1568. in_relative[0] == '/')
  1569. {
  1570. dir = "/";
  1571. }
  1572. // Resolve relative path.
  1573. kwsys_stl::string newDir;
  1574. if(!(dir == ""))
  1575. {
  1576. Realpath(dir.c_str(), newDir);
  1577. }
  1578. else
  1579. {
  1580. newDir = SystemTools::GetCurrentWorkingDirectory();
  1581. }
  1582. if(in_base)
  1583. {
  1584. // Restore original working directory.
  1585. Chdir(orig.c_str());
  1586. }
  1587. // Construct and return the full path.
  1588. kwsys_stl::string newPath = newDir;
  1589. if(!(file == ""))
  1590. {
  1591. if(!(newDir.size() == 1 && newDir[0] == '/'))
  1592. {
  1593. newPath += "/";
  1594. }
  1595. newPath += file;
  1596. }
  1597. // Now we need to update the translation table with this potentially new path
  1598. SystemTools::AddTranslationPath(newPath.c_str(), in_relative);
  1599. SystemTools::CheckTranslationPath(newPath);
  1600. return newPath;
  1601. }
  1602. //----------------------------------------------------------------------------
  1603. void SystemTools::SplitPath(const char* p,
  1604. kwsys_stl::vector<kwsys_stl::string>& components)
  1605. {
  1606. // Identify the root component.
  1607. const char* c = p;
  1608. if(c[0] == '/' && c[1] == '/')
  1609. {
  1610. // Network path.
  1611. components.push_back("//");
  1612. c += 2;
  1613. }
  1614. else if(c[0] == '/')
  1615. {
  1616. // Unix path.
  1617. components.push_back("/");
  1618. c += 1;
  1619. }
  1620. else if(c[0] && c[1] == ':' && c[2] == '/')
  1621. {
  1622. // Windows path.
  1623. kwsys_stl::string root = "_:/";
  1624. root[0] = c[0];
  1625. components.push_back(root);
  1626. c += 3;
  1627. }
  1628. else if(c[0] && c[1] == ':')
  1629. {
  1630. // Path relative to a windows drive working directory.
  1631. kwsys_stl::string root = "_:";
  1632. root[0] = c[0];
  1633. components.push_back(root);
  1634. c += 2;
  1635. }
  1636. else
  1637. {
  1638. // Relative path.
  1639. components.push_back("");
  1640. }
  1641. // Parse the remaining components.
  1642. const char* first = c;
  1643. const char* last = first;
  1644. for(;*last; ++last)
  1645. {
  1646. if(*last == '/')
  1647. {
  1648. // End of a component. Save it.
  1649. components.push_back(kwsys_stl::string(first, last-first));
  1650. first = last+1;
  1651. }
  1652. }
  1653. // Save the last component unless there were no components.
  1654. if(last != c)
  1655. {
  1656. components.push_back(kwsys_stl::string(first, last-first));
  1657. }
  1658. }
  1659. //----------------------------------------------------------------------------
  1660. kwsys_stl::string
  1661. SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components)
  1662. {
  1663. kwsys_stl::string result;
  1664. if(components.size() > 0)
  1665. {
  1666. result += components[0];
  1667. }
  1668. if(components.size() > 1)
  1669. {
  1670. result += components[1];
  1671. }
  1672. for(unsigned int i=2; i < components.size(); ++i)
  1673. {
  1674. result += "/";
  1675. result += components[i];
  1676. }
  1677. return result;
  1678. }
  1679. //----------------------------------------------------------------------------
  1680. bool SystemTools::ComparePath(const char* c1, const char* c2)
  1681. {
  1682. #if defined(_WIN32) || defined(__APPLE__)
  1683. return SystemTools::Strucmp(c1, c2) == 0;
  1684. #else
  1685. return strcmp(c1, c2) == 0;
  1686. #endif
  1687. }
  1688. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
  1689. {
  1690. kwsys_stl::string data(str);
  1691. kwsys_stl::string::size_type lpos = 0;
  1692. while(lpos < data.length())
  1693. {
  1694. kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
  1695. if(rpos == kwsys_stl::string::npos)
  1696. {
  1697. // Line ends at end of string without a newline.
  1698. lines.push_back(data.substr(lpos));
  1699. return false;
  1700. }
  1701. if((rpos > lpos) && (data[rpos-1] == '\r'))
  1702. {
  1703. // Line ends in a "\r\n" pair, remove both characters.
  1704. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  1705. }
  1706. else
  1707. {
  1708. // Line ends in a "\n", remove the character.
  1709. lines.push_back(data.substr(lpos, rpos-lpos));
  1710. }
  1711. lpos = rpos+1;
  1712. }
  1713. return true;
  1714. }
  1715. /**
  1716. * Return path of a full filename (no trailing slashes).
  1717. * Warning: returned path is converted to Unix slashes format.
  1718. */
  1719. kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
  1720. {
  1721. kwsys_stl::string fn = filename;
  1722. SystemTools::ConvertToUnixSlashes(fn);
  1723. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  1724. if(slash_pos != kwsys_stl::string::npos)
  1725. {
  1726. return fn.substr(0, slash_pos);
  1727. }
  1728. else
  1729. {
  1730. return "";
  1731. }
  1732. }
  1733. /**
  1734. * Return file name of a full filename (i.e. file name without path).
  1735. */
  1736. kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
  1737. {
  1738. kwsys_stl::string fn = filename;
  1739. SystemTools::ConvertToUnixSlashes(fn);
  1740. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  1741. if(slash_pos != kwsys_stl::string::npos)
  1742. {
  1743. return fn.substr(slash_pos + 1);
  1744. }
  1745. else
  1746. {
  1747. return filename;
  1748. }
  1749. }
  1750. /**
  1751. * Return file extension of a full filename (dot included).
  1752. * Warning: this is the longest extension (for example: .tar.gz)
  1753. */
  1754. kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
  1755. {
  1756. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  1757. kwsys_stl::string::size_type dot_pos = name.find(".");
  1758. if(dot_pos != kwsys_stl::string::npos)
  1759. {
  1760. return name.substr(dot_pos);
  1761. }
  1762. else
  1763. {
  1764. return "";
  1765. }
  1766. }
  1767. /**
  1768. * Return file extension of a full filename (dot included).
  1769. * Warning: this is the shortest extension (for example: .tar.gz)
  1770. */
  1771. kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
  1772. {
  1773. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  1774. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  1775. if(dot_pos != kwsys_stl::string::npos)
  1776. {
  1777. return name.substr(dot_pos);
  1778. }
  1779. else
  1780. {
  1781. return "";
  1782. }
  1783. }
  1784. /**
  1785. * Return file name without extension of a full filename (i.e. without path).
  1786. * Warning: it considers the longest extension (for example: .tar.gz)
  1787. */
  1788. kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
  1789. {
  1790. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  1791. kwsys_stl::string::size_type dot_pos = name.find(".");
  1792. if(dot_pos != kwsys_stl::string::npos)
  1793. {
  1794. return name.substr(0, dot_pos);
  1795. }
  1796. else
  1797. {
  1798. return name;
  1799. }
  1800. }
  1801. /**
  1802. * Return file name without extension of a full filename (i.e. without path).
  1803. * Warning: it considers the last extension (for example: removes .gz
  1804. * from .tar.gz)
  1805. */
  1806. kwsys_stl::string
  1807. SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
  1808. {
  1809. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  1810. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  1811. if(dot_pos != kwsys_stl::string::npos)
  1812. {
  1813. return name.substr(0, dot_pos);
  1814. }
  1815. else
  1816. {
  1817. return name;
  1818. }
  1819. }
  1820. bool SystemTools::FileIsFullPath(const char* in_name)
  1821. {
  1822. kwsys_stl::string name = in_name;
  1823. #if defined(_WIN32) || defined(__CYGWIN__)
  1824. // On Windows, the name must be at least two characters long.
  1825. if(name.length() < 2)
  1826. {
  1827. return false;
  1828. }
  1829. if(name[1] == ':')
  1830. {
  1831. return true;
  1832. }
  1833. if(name[0] == '\\')
  1834. {
  1835. return true;
  1836. }
  1837. #else
  1838. // On UNIX, the name must be at least one character long.
  1839. if(name.length() < 1)
  1840. {
  1841. return false;
  1842. }
  1843. #endif
  1844. // On UNIX, the name must begin in a '/'.
  1845. // On Windows, if the name begins in a '/', then it is a full
  1846. // network path.
  1847. if(name[0] == '/')
  1848. {
  1849. return true;
  1850. }
  1851. return false;
  1852. }
  1853. bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
  1854. {
  1855. #if defined(WIN32) && !defined(__CYGWIN__)
  1856. const int size = int(strlen(path)) +1; // size of return
  1857. char *buffer = new char[size]; // create a buffer
  1858. char *tempPath = new char[size]; // create a buffer
  1859. int ret;
  1860. // if the path passed in has quotes around it, first remove the quotes
  1861. if (path[0] == '"' && path[strlen(path)-1] == '"')
  1862. {
  1863. strcpy(tempPath,path+1);
  1864. tempPath[strlen(tempPath)-1] = '\0';
  1865. }
  1866. else
  1867. {
  1868. strcpy(tempPath,path);
  1869. }
  1870. buffer[0] = 0;
  1871. ret = GetShortPathName(tempPath, buffer, size);
  1872. if(buffer[0] == 0 || ret > size)
  1873. {
  1874. delete [] buffer;
  1875. delete [] tempPath;
  1876. return false;
  1877. }
  1878. else
  1879. {
  1880. shortPath = buffer;
  1881. delete [] buffer;
  1882. delete [] tempPath;
  1883. return true;
  1884. }
  1885. #else
  1886. shortPath = path;
  1887. return true;
  1888. #endif
  1889. }
  1890. void SystemTools::SplitProgramFromArgs(const char* path,
  1891. kwsys_stl::string& program, kwsys_stl::string& args)
  1892. {
  1893. // see if this is a full path to a program
  1894. // if so then set program to path and args to nothing
  1895. if(SystemTools::FileExists(path))
  1896. {
  1897. program = path;
  1898. args = "";
  1899. return;
  1900. }
  1901. // Try to find the program in the path, note the program
  1902. // may have spaces in its name so we have to look for it
  1903. kwsys_stl::vector<kwsys_stl::string> e;
  1904. kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
  1905. if(findProg.size())
  1906. {
  1907. program = findProg;
  1908. args = "";
  1909. return;
  1910. }
  1911. // Now try and peel off space separated chunks from the end of the string
  1912. // so the largest path possible is found allowing for spaces in the path
  1913. kwsys_stl::string dir = path;
  1914. kwsys_stl::string::size_type spacePos = dir.rfind(' ');
  1915. while(spacePos != kwsys_stl::string::npos)
  1916. {
  1917. kwsys_stl::string tryProg = dir.substr(0, spacePos);
  1918. // See if the file exists
  1919. if(SystemTools::FileExists(tryProg.c_str()))
  1920. {
  1921. program = tryProg;
  1922. // remove trailing spaces from program
  1923. kwsys_stl::string::size_type pos = program.size()-1;
  1924. while(program[pos] == ' ')
  1925. {
  1926. program.erase(pos);
  1927. pos--;
  1928. }
  1929. args = dir.substr(spacePos, dir.size()-spacePos);
  1930. return;
  1931. }
  1932. // Now try and find the the program in the path
  1933. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  1934. if(findProg.size())
  1935. {
  1936. program = findProg;
  1937. // remove trailing spaces from program
  1938. kwsys_stl::string::size_type pos = program.size()-1;
  1939. while(program[pos] == ' ')
  1940. {
  1941. program.erase(pos);
  1942. pos--;
  1943. }
  1944. args = dir.substr(spacePos, dir.size()-spacePos);
  1945. return;
  1946. }
  1947. // move past the space for the next search
  1948. spacePos--;
  1949. spacePos = dir.rfind(' ', spacePos);
  1950. }
  1951. program = "";
  1952. args = "";
  1953. }
  1954. kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
  1955. {
  1956. char buf[1024];
  1957. time_t t;
  1958. time(&t);
  1959. strftime(buf, sizeof(buf), format, localtime(&t));
  1960. return buf;
  1961. }
  1962. kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
  1963. {
  1964. kwsys_stl::string str(s);
  1965. if (str.find_first_of("0123456789") == 0)
  1966. {
  1967. str = "_" + str;
  1968. }
  1969. kwsys_stl::string permited_chars("_"
  1970. "abcdefghijklmnopqrstuvwxyz"
  1971. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1972. "0123456789");
  1973. kwsys_stl::string::size_type pos = 0;
  1974. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
  1975. {
  1976. str[pos] = '_';
  1977. }
  1978. return str;
  1979. }
  1980. // Due to a buggy stream library on the HP and another on Mac OSX, we
  1981. // need this very carefully written version of getline. Returns true
  1982. // if any data were read before the end-of-file was reached.
  1983. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, kwsys_stl::string& line,
  1984. bool *has_newline /* = 0 */)
  1985. {
  1986. const int bufferSize = 1024;
  1987. char buffer[bufferSize];
  1988. line = "";
  1989. bool haveData = false;
  1990. if ( has_newline )
  1991. {
  1992. *has_newline = false;
  1993. }
  1994. // If no characters are read from the stream, the end of file has
  1995. // been reached.
  1996. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  1997. {
  1998. haveData = true;
  1999. line.append(buffer);
  2000. // If newline character was read, the gcount includes the
  2001. // character, but the buffer does not. The end of line has been
  2002. // reached.
  2003. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  2004. {
  2005. if ( has_newline )
  2006. {
  2007. *has_newline = true;
  2008. }
  2009. break;
  2010. }
  2011. // The fail bit may be set. Clear it.
  2012. is.clear(is.rdstate() & ~kwsys_ios::ios::failbit);
  2013. }
  2014. return haveData;
  2015. }
  2016. int SystemTools::GetTerminalWidth()
  2017. {
  2018. int width = -1;
  2019. #ifndef _WIN32
  2020. struct winsize ws;
  2021. char *columns; /* Unix98 environment variable */
  2022. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  2023. {
  2024. width = ws.ws_col;
  2025. }
  2026. if(!isatty(STDOUT_FILENO))
  2027. {
  2028. width = -1;
  2029. }
  2030. columns = getenv("COLUMNS");
  2031. if(columns && *columns)
  2032. {
  2033. long t;
  2034. char *endptr;
  2035. t = strtol(columns, &endptr, 0);
  2036. if(endptr && !*endptr && (t>0) && (t<1000))
  2037. {
  2038. width = (int)t;
  2039. }
  2040. }
  2041. if ( width < 9 )
  2042. {
  2043. width = -1;
  2044. }
  2045. #endif
  2046. return width;
  2047. }
  2048. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  2049. {
  2050. if ( !file )
  2051. {
  2052. return false;
  2053. }
  2054. struct stat st;
  2055. if ( stat(file, &st) < 0 )
  2056. {
  2057. return false;
  2058. }
  2059. mode = st.st_mode;
  2060. return true;
  2061. }
  2062. bool SystemTools::SetPermissions(const char* file, mode_t mode)
  2063. {
  2064. if ( !file )
  2065. {
  2066. return false;
  2067. }
  2068. if ( !SystemTools::FileExists(file) )
  2069. {
  2070. return false;
  2071. }
  2072. if ( chmod(file, mode) < 0 )
  2073. {
  2074. return false;
  2075. }
  2076. return true;
  2077. }
  2078. kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
  2079. {
  2080. if ( !fileOrDir || !*fileOrDir )
  2081. {
  2082. return "";
  2083. }
  2084. kwsys_stl::string res = fileOrDir;
  2085. SystemTools::ConvertToUnixSlashes(res);
  2086. kwsys_stl::string::size_type cc = res.size()-1;
  2087. if ( res[cc] == '/' )
  2088. {
  2089. cc --;
  2090. }
  2091. for ( ; cc > 0; cc -- )
  2092. {
  2093. if ( res[cc] == '/' )
  2094. {
  2095. break;
  2096. }
  2097. }
  2098. return res.substr(0, cc);
  2099. }
  2100. bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
  2101. {
  2102. kwsys_stl::string subdir = cSubdir;
  2103. kwsys_stl::string dir = cDir;
  2104. SystemTools::ConvertToUnixSlashes(dir);
  2105. kwsys_stl::string path = subdir;
  2106. do
  2107. {
  2108. path = SystemTools::GetParentDirectory(path.c_str());
  2109. if ( dir == path )
  2110. {
  2111. return true;
  2112. }
  2113. }
  2114. while ( path.size() > dir.size() );
  2115. return false;
  2116. }
  2117. kwsys_stl::string SystemTools::FileExistsInParentDirectories(const char* fname,
  2118. const char* directory, const char* toplevel)
  2119. {
  2120. kwsys_stl::string file = fname;
  2121. SystemTools::ConvertToUnixSlashes(file);
  2122. kwsys_stl::string dir = directory;
  2123. SystemTools::ConvertToUnixSlashes(dir);
  2124. while ( !dir.empty() )
  2125. {
  2126. kwsys_stl::string path = dir + "/" + file;
  2127. if ( SystemTools::FileExists(path.c_str()) )
  2128. {
  2129. return path;
  2130. }
  2131. if ( dir.size() < strlen(toplevel) )
  2132. {
  2133. break;
  2134. }
  2135. dir = SystemTools::GetParentDirectory(dir.c_str());
  2136. }
  2137. return "";
  2138. }
  2139. void SystemTools::Delay(unsigned int msec)
  2140. {
  2141. #ifdef _WIN32
  2142. Sleep(msec);
  2143. #else
  2144. usleep(msec * 1000);
  2145. #endif
  2146. }
  2147. // These must NOT be initialized. Default initialization to zero is
  2148. // necessary.
  2149. unsigned int SystemToolsManagerCount;
  2150. SystemToolsTranslationMap *SystemTools::TranslationMap;
  2151. // SystemToolsManager manages the SystemTools singleton.
  2152. // SystemToolsManager should be included in any translation unit
  2153. // that will use SystemTools or that implements the singleton
  2154. // pattern. It makes sure that the SystemTools singleton is created
  2155. // before and destroyed after all other singletons in CMake.
  2156. SystemToolsManager::SystemToolsManager()
  2157. {
  2158. if(++SystemToolsManagerCount == 1)
  2159. {
  2160. SystemTools::ClassInitialize();
  2161. }
  2162. }
  2163. SystemToolsManager::~SystemToolsManager()
  2164. {
  2165. if(--SystemToolsManagerCount == 0)
  2166. {
  2167. SystemTools::ClassFinalize();
  2168. }
  2169. }
  2170. void SystemTools::ClassInitialize()
  2171. {
  2172. // Allocate the translation map first.
  2173. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  2174. // Add some special translation paths for unix. These are not added
  2175. // for windows because drive letters need to be maintained. Also,
  2176. // there are not sym-links and mount points on windows anyway.
  2177. #if !defined(_WIN32) || defined(__CYGWIN__)
  2178. // Work-around an SGI problem by always adding this mapping:
  2179. SystemTools::AddTranslationPath("/tmp_mnt/", "/");
  2180. // The tmp path is frequently a logical path so always keep it:
  2181. SystemTools::AddKeepPath("/tmp/");
  2182. // If the current working directory is a logical path then keep the
  2183. // logical name.
  2184. if(const char* pwd = getenv("PWD"))
  2185. {
  2186. char buf[2048];
  2187. if(const char* cwd = Getcwd(buf, 2048))
  2188. {
  2189. kwsys_stl::string pwd_path;
  2190. Realpath(pwd, pwd_path);
  2191. if(cwd == pwd_path && strcmp(cwd, pwd) != 0)
  2192. {
  2193. // The current working directory is a logical path. Split
  2194. // both the logical and physical paths into their components.
  2195. kwsys_stl::vector<kwsys_stl::string> cwd_components;
  2196. kwsys_stl::vector<kwsys_stl::string> pwd_components;
  2197. SystemTools::SplitPath(cwd, cwd_components);
  2198. SystemTools::SplitPath(pwd, pwd_components);
  2199. // Remove the common ending of the paths to leave only the
  2200. // part that changes under the logical mapping.
  2201. kwsys_stl::vector<kwsys_stl::string>::iterator ic = cwd_components.end();
  2202. kwsys_stl::vector<kwsys_stl::string>::iterator ip = pwd_components.end();
  2203. for(;ip != pwd_components.begin() && ic != cwd_components.begin() &&
  2204. *(ip-1) == *(ic-1); --ip,--ic);
  2205. cwd_components.erase(ic, cwd_components.end());
  2206. pwd_components.erase(ip, pwd_components.end());
  2207. // Reconstruct the string versions of the part of the path
  2208. // that changed.
  2209. kwsys_stl::string cwd_changed = SystemTools::JoinPath(cwd_components);
  2210. kwsys_stl::string pwd_changed = SystemTools::JoinPath(pwd_components);
  2211. // Add the translation to keep the logical path name.
  2212. if(!cwd_changed.empty() && !pwd_changed.empty())
  2213. {
  2214. SystemTools::AddTranslationPath(cwd_changed.c_str(),
  2215. pwd_changed.c_str());
  2216. }
  2217. }
  2218. }
  2219. }
  2220. #endif
  2221. }
  2222. void SystemTools::ClassFinalize()
  2223. {
  2224. delete SystemTools::TranslationMap;
  2225. }
  2226. } // namespace KWSYS_NAMESPACE
  2227. #if defined(_MSC_VER) && defined(_DEBUG)
  2228. # include <crtdbg.h>
  2229. # include <stdio.h>
  2230. # include <stdlib.h>
  2231. namespace KWSYS_NAMESPACE
  2232. {
  2233. static int SystemToolsDebugReport(int, char* message, int*)
  2234. {
  2235. fprintf(stderr, message);
  2236. exit(1);
  2237. }
  2238. void SystemTools::EnableMSVCDebugHook()
  2239. {
  2240. if(getenv("DART_TEST_FROM_DART"))
  2241. {
  2242. _CrtSetReportHook(SystemToolsDebugReport);
  2243. }
  2244. }
  2245. } // namespace KWSYS_NAMESPACE
  2246. #else
  2247. namespace KWSYS_NAMESPACE
  2248. {
  2249. void SystemTools::EnableMSVCDebugHook() {}
  2250. } // namespace KWSYS_NAMESPACE
  2251. #endif