SystemTools.cxx 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351
  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. // Return a capitalized string (i.e the first letter is uppercased, all other
  635. // are lowercased)
  636. kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
  637. {
  638. kwsys_stl::string n;
  639. if(s.size() == 0)
  640. {
  641. return n;
  642. }
  643. n.resize(s.size());
  644. n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
  645. for (size_t i = 1; i < s.size(); i++)
  646. {
  647. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  648. }
  649. return n;
  650. }
  651. // Return a lower case string
  652. kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
  653. {
  654. kwsys_stl::string n;
  655. n.resize(s.size());
  656. for (size_t i = 0; i < s.size(); i++)
  657. {
  658. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  659. }
  660. return n;
  661. }
  662. // Return a lower case string
  663. kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
  664. {
  665. kwsys_stl::string n;
  666. n.resize(s.size());
  667. for (size_t i = 0; i < s.size(); i++)
  668. {
  669. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  670. }
  671. return n;
  672. }
  673. // convert windows slashes to unix slashes
  674. void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
  675. {
  676. kwsys_stl::string::size_type pos = 0;
  677. while((pos = path.find('\\', pos)) != kwsys_stl::string::npos)
  678. {
  679. // make sure we don't convert an escaped space to a unix slash
  680. if(pos < path.size()-1)
  681. {
  682. if(path[pos+1] != ' ')
  683. {
  684. path[pos] = '/';
  685. }
  686. }
  687. pos++;
  688. }
  689. // Remove all // from the path just like most unix shells
  690. int start_find;
  691. #ifdef _WIN32
  692. // However, on windows if the first characters are both slashes,
  693. // then keep them that way, so that network paths can be handled.
  694. start_find = 1;
  695. #else
  696. start_find = 0;
  697. #endif
  698. while((pos = path.find("//", start_find)) != kwsys_stl::string::npos)
  699. {
  700. SystemTools::ReplaceString(path, "//", "/");
  701. }
  702. // remove any trailing slash
  703. if(path.size() > 1 && path[path.size()-1] == '/')
  704. {
  705. path = path.substr(0, path.size()-1);
  706. }
  707. // if there is a tilda ~ then replace it with HOME
  708. if(path.find("~") == 0)
  709. {
  710. if (getenv("HOME"))
  711. {
  712. path = kwsys_stl::string(getenv("HOME")) + path.substr(1);
  713. }
  714. }
  715. }
  716. // change // to /, and escape any spaces in the path
  717. kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
  718. {
  719. kwsys_stl::string ret = path;
  720. // remove // except at the beginning might be a cygwin drive
  721. kwsys_stl::string::size_type pos = 1;
  722. while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
  723. {
  724. ret.erase(pos, 1);
  725. }
  726. // now escape spaces if there is a space in the path
  727. if(ret.find(" ") != kwsys_stl::string::npos)
  728. {
  729. kwsys_stl::string result = "";
  730. char lastch = 1;
  731. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  732. {
  733. // if it is already escaped then don't try to escape it again
  734. if(*ch == ' ' && lastch != '\\')
  735. {
  736. result += '\\';
  737. }
  738. result += *ch;
  739. lastch = *ch;
  740. }
  741. ret = result;
  742. }
  743. return ret;
  744. }
  745. kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
  746. {
  747. #if defined(_WIN32) && !defined(__CYGWIN__)
  748. return SystemTools::ConvertToWindowsOutputPath(path);
  749. #else
  750. return SystemTools::ConvertToUnixOutputPath(path);
  751. #endif
  752. }
  753. // remove double slashes not at the start
  754. kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  755. {
  756. kwsys_stl::string ret = path;
  757. kwsys_stl::string::size_type pos = 0;
  758. // first convert all of the slashes
  759. while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
  760. {
  761. ret[pos] = '\\';
  762. pos++;
  763. }
  764. // check for really small paths
  765. if(ret.size() < 2)
  766. {
  767. return ret;
  768. }
  769. // now clean up a bit and remove double slashes
  770. // Only if it is not the first position in the path which is a network
  771. // path on windows
  772. pos = 1; // start at position 1
  773. if(ret[0] == '\"')
  774. {
  775. pos = 2; // if the string is already quoted then start at 2
  776. if(ret.size() < 3)
  777. {
  778. return ret;
  779. }
  780. }
  781. while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
  782. {
  783. ret.erase(pos, 1);
  784. }
  785. // now double quote the path if it has spaces in it
  786. // and is not already double quoted
  787. if(ret.find(" ") != kwsys_stl::string::npos
  788. && ret[0] != '\"')
  789. {
  790. kwsys_stl::string result;
  791. result = "\"" + ret + "\"";
  792. ret = result;
  793. }
  794. return ret;
  795. }
  796. bool SystemTools::CopyFileIfDifferent(const char* source,
  797. const char* destination)
  798. {
  799. if(SystemTools::FilesDiffer(source, destination))
  800. {
  801. return SystemTools::CopyFileAlways(source, destination);
  802. }
  803. return true;
  804. }
  805. bool SystemTools::FilesDiffer(const char* source,
  806. const char* destination)
  807. {
  808. struct stat statSource;
  809. if (stat(source, &statSource) != 0)
  810. {
  811. return true;
  812. }
  813. struct stat statDestination;
  814. if (stat(destination, &statDestination) != 0)
  815. {
  816. return true;
  817. }
  818. if(statSource.st_size != statDestination.st_size)
  819. {
  820. return true;
  821. }
  822. if(statSource.st_size == 0)
  823. {
  824. return false;
  825. }
  826. #if defined(_WIN32) || defined(__CYGWIN__)
  827. kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
  828. kwsys_ios::ios::in));
  829. kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
  830. kwsys_ios::ios::in));
  831. #else
  832. kwsys_ios::ifstream finSource(source);
  833. kwsys_ios::ifstream finDestination(destination);
  834. #endif
  835. if(!finSource || !finDestination)
  836. {
  837. return true;
  838. }
  839. char* source_buf = new char[statSource.st_size];
  840. char* dest_buf = new char[statSource.st_size];
  841. finSource.read(source_buf, statSource.st_size);
  842. finDestination.read(dest_buf, statSource.st_size);
  843. if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
  844. statSource.st_size != static_cast<long>(finDestination.gcount()))
  845. {
  846. // Failed to read files.
  847. delete [] source_buf;
  848. delete [] dest_buf;
  849. return true;
  850. }
  851. int ret = memcmp((const void*)source_buf,
  852. (const void*)dest_buf,
  853. statSource.st_size);
  854. delete [] dest_buf;
  855. delete [] source_buf;
  856. return ret != 0;
  857. }
  858. /**
  859. * Copy a file named by "source" to the file named by "destination".
  860. */
  861. bool SystemTools::CopyFileAlways(const char* source, const char* destination)
  862. {
  863. // If files are the same do not copy
  864. if ( SystemTools::SameFile(source, destination) )
  865. {
  866. return true;
  867. }
  868. mode_t perm = 0;
  869. bool perms = SystemTools::GetPermissions(source, perm);
  870. const int bufferSize = 4096;
  871. char buffer[bufferSize];
  872. // If destination is a directory, try to create a file with the same
  873. // name as the source in that directory.
  874. kwsys_stl::string new_destination;
  875. if(SystemTools::FileExists(destination) &&
  876. SystemTools::FileIsDirectory(destination))
  877. {
  878. new_destination = destination;
  879. SystemTools::ConvertToUnixSlashes(new_destination);
  880. new_destination += '/';
  881. kwsys_stl::string source_name = source;
  882. new_destination += SystemTools::GetFilenameName(source_name);
  883. destination = new_destination.c_str();
  884. }
  885. // Create destination directory
  886. kwsys_stl::string destination_dir = destination;
  887. destination_dir = SystemTools::GetFilenamePath(destination_dir);
  888. SystemTools::MakeDirectory(destination_dir.c_str());
  889. // Open files
  890. #if defined(_WIN32) || defined(__CYGWIN__)
  891. kwsys_ios::ifstream fin(source,
  892. kwsys_ios::ios::binary | kwsys_ios::ios::in);
  893. #else
  894. kwsys_ios::ifstream fin(source);
  895. #endif
  896. if(!fin)
  897. {
  898. return false;
  899. }
  900. // try and remove the destination file so that read only destination files
  901. // can be written to.
  902. // If the remove fails continue so that files in read only directories
  903. // that do not allow file removal can be modified.
  904. SystemTools::RemoveFile(destination);
  905. #if defined(_WIN32) || defined(__CYGWIN__)
  906. kwsys_ios::ofstream fout(destination,
  907. kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  908. #else
  909. kwsys_ios::ofstream fout(destination,
  910. kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  911. #endif
  912. if(!fout)
  913. {
  914. return false;
  915. }
  916. // This copy loop is very sensitive on certain platforms with
  917. // slightly broken stream libraries (like HPUX). Normally, it is
  918. // incorrect to not check the error condition on the fin.read()
  919. // before using the data, but the fin.gcount() will be zero if an
  920. // error occurred. Therefore, the loop should be safe everywhere.
  921. while(fin)
  922. {
  923. fin.read(buffer, bufferSize);
  924. if(fin.gcount())
  925. {
  926. fout.write(buffer, fin.gcount());
  927. }
  928. }
  929. // Make sure the operating system has finished writing the file
  930. // before closing it. This will ensure the file is finished before
  931. // the check below.
  932. fout.flush();
  933. fin.close();
  934. fout.close();
  935. // More checks.
  936. struct stat statSource, statDestination;
  937. statSource.st_size = 12345;
  938. statDestination.st_size = 12345;
  939. if(stat(source, &statSource) != 0)
  940. {
  941. return false;
  942. }
  943. else if(stat(destination, &statDestination) != 0)
  944. {
  945. return false;
  946. }
  947. else if(statSource.st_size != statDestination.st_size)
  948. {
  949. return false;
  950. }
  951. if ( perms )
  952. {
  953. if ( !SystemTools::SetPermissions(destination, perm) )
  954. {
  955. return false;
  956. }
  957. }
  958. return true;
  959. }
  960. /**
  961. * Copy a directory content from "source" directory to the directory named by
  962. * "destination".
  963. */
  964. bool SystemTools::CopyADirectory(const char* source, const char* destination)
  965. {
  966. Directory dir;
  967. dir.Load(source);
  968. size_t fileNum;
  969. if ( !SystemTools::MakeDirectory(destination) )
  970. {
  971. return false;
  972. }
  973. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  974. {
  975. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  976. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  977. {
  978. kwsys_stl::string fullPath = source;
  979. fullPath += "/";
  980. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  981. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  982. {
  983. kwsys_stl::string fullDestPath = destination;
  984. fullDestPath += "/";
  985. fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  986. if (!SystemTools::CopyADirectory(fullPath.c_str(), fullDestPath.c_str()))
  987. {
  988. return false;
  989. }
  990. }
  991. else
  992. {
  993. if(!SystemTools::CopyFileAlways(fullPath.c_str(), destination))
  994. {
  995. return false;
  996. }
  997. }
  998. }
  999. }
  1000. return true;
  1001. }
  1002. // return size of file; also returns zero if no file exists
  1003. unsigned long SystemTools::FileLength(const char* filename)
  1004. {
  1005. struct stat fs;
  1006. if (stat(filename, &fs) != 0)
  1007. {
  1008. return 0;
  1009. }
  1010. else
  1011. {
  1012. return fs.st_size;
  1013. }
  1014. }
  1015. int SystemTools::Strucmp(const char *s1, const char *s2)
  1016. {
  1017. // lifted from Graphvis http://www.graphviz.org
  1018. while ((*s1 != '\0')
  1019. && (tolower(*s1) == tolower(*s2)))
  1020. {
  1021. s1++;
  1022. s2++;
  1023. }
  1024. return tolower(*s1) - tolower(*s2);
  1025. }
  1026. // return true if the file exists
  1027. long int SystemTools::ModifiedTime(const char* filename)
  1028. {
  1029. struct stat fs;
  1030. if (stat(filename, &fs) != 0)
  1031. {
  1032. return 0;
  1033. }
  1034. else
  1035. {
  1036. return (long int)fs.st_mtime;
  1037. }
  1038. }
  1039. kwsys_stl::string SystemTools::GetLastSystemError()
  1040. {
  1041. int e = errno;
  1042. return strerror(e);
  1043. }
  1044. bool SystemTools::RemoveFile(const char* source)
  1045. {
  1046. return unlink(source) != 0 ? false : true;
  1047. }
  1048. bool SystemTools::RemoveADirectory(const char* source)
  1049. {
  1050. Directory dir;
  1051. dir.Load(source);
  1052. size_t fileNum;
  1053. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1054. {
  1055. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1056. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1057. {
  1058. kwsys_stl::string fullPath = source;
  1059. fullPath += "/";
  1060. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1061. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  1062. {
  1063. if (!SystemTools::RemoveADirectory(fullPath.c_str()))
  1064. {
  1065. return false;
  1066. }
  1067. }
  1068. else
  1069. {
  1070. if(!SystemTools::RemoveFile(fullPath.c_str()))
  1071. {
  1072. return false;
  1073. }
  1074. }
  1075. }
  1076. }
  1077. return (Rmdir(source) == 0);
  1078. }
  1079. /**
  1080. * Find the file the given name. Searches the given path and then
  1081. * the system search path. Returns the full path to the file if it is
  1082. * found. Otherwise, the empty string is returned.
  1083. */
  1084. kwsys_stl::string SystemTools
  1085. ::FindFile(const char* name,
  1086. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1087. {
  1088. // Add the system search path to our path first
  1089. kwsys_stl::vector<kwsys_stl::string> path;
  1090. SystemTools::GetPath(path, "CMAKE_FILE_PATH");
  1091. SystemTools::GetPath(path);
  1092. // now add the additional paths
  1093. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1094. // now look for the file
  1095. kwsys_stl::string tryPath;
  1096. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1097. p != path.end(); ++p)
  1098. {
  1099. tryPath = *p;
  1100. tryPath += "/";
  1101. tryPath += name;
  1102. if(SystemTools::FileExists(tryPath.c_str()) &&
  1103. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1104. {
  1105. return SystemTools::CollapseFullPath(tryPath.c_str());
  1106. }
  1107. }
  1108. // Couldn't find the file.
  1109. return "";
  1110. }
  1111. /**
  1112. * Find the executable with the given name. Searches the given path and then
  1113. * the system search path. Returns the full path to the executable if it is
  1114. * found. Otherwise, the empty string is returned.
  1115. */
  1116. kwsys_stl::string SystemTools::FindProgram(
  1117. const char* name,
  1118. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1119. bool no_system_path)
  1120. {
  1121. if(!name)
  1122. {
  1123. return "";
  1124. }
  1125. // See if the executable exists as written.
  1126. if(SystemTools::FileExists(name) &&
  1127. !SystemTools::FileIsDirectory(name))
  1128. {
  1129. return SystemTools::CollapseFullPath(name);
  1130. }
  1131. kwsys_stl::string tryPath = name;
  1132. tryPath += SystemTools::GetExecutableExtension();
  1133. if(SystemTools::FileExists(tryPath.c_str()) &&
  1134. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1135. {
  1136. return SystemTools::CollapseFullPath(tryPath.c_str());
  1137. }
  1138. kwsys_stl::vector<kwsys_stl::string> path;
  1139. SystemTools::GetPath(path, "CMAKE_PROGRAM_PATH");
  1140. // Add the system search path to our path.
  1141. if (!no_system_path)
  1142. {
  1143. SystemTools::GetPath(path);
  1144. }
  1145. // now add the additional paths
  1146. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1147. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1148. p != path.end(); ++p)
  1149. {
  1150. tryPath = *p;
  1151. tryPath += "/";
  1152. tryPath += name;
  1153. if(SystemTools::FileExists(tryPath.c_str()) &&
  1154. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1155. {
  1156. return SystemTools::CollapseFullPath(tryPath.c_str());
  1157. }
  1158. #ifdef _WIN32
  1159. tryPath += ".com";
  1160. if(SystemTools::FileExists(tryPath.c_str()) &&
  1161. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1162. {
  1163. return SystemTools::CollapseFullPath(tryPath.c_str());
  1164. }
  1165. tryPath = *p;
  1166. tryPath += "/";
  1167. tryPath += name;
  1168. #endif
  1169. tryPath += SystemTools::GetExecutableExtension();
  1170. if(SystemTools::FileExists(tryPath.c_str()) &&
  1171. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1172. {
  1173. return SystemTools::CollapseFullPath(tryPath.c_str());
  1174. }
  1175. }
  1176. // Couldn't find the program.
  1177. return "";
  1178. }
  1179. /**
  1180. * Find the library with the given name. Searches the given path and then
  1181. * the system search path. Returns the full path to the library if it is
  1182. * found. Otherwise, the empty string is returned.
  1183. */
  1184. kwsys_stl::string SystemTools
  1185. ::FindLibrary(const char* name,
  1186. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1187. {
  1188. // See if the executable exists as written.
  1189. if(SystemTools::FileExists(name) &&
  1190. !SystemTools::FileIsDirectory(name))
  1191. {
  1192. return SystemTools::CollapseFullPath(name);
  1193. }
  1194. // Add the system search path to our path.
  1195. kwsys_stl::vector<kwsys_stl::string> path;
  1196. SystemTools::GetPath(path);
  1197. // now add the additional paths
  1198. path.insert(path.end(), userPaths.begin(), userPaths.end());
  1199. kwsys_stl::string tryPath;
  1200. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1201. p != path.end(); ++p)
  1202. {
  1203. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
  1204. tryPath = *p;
  1205. tryPath += "/";
  1206. tryPath += name;
  1207. tryPath += ".lib";
  1208. if(SystemTools::FileExists(tryPath.c_str())
  1209. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1210. {
  1211. return SystemTools::CollapseFullPath(tryPath.c_str());
  1212. }
  1213. #else
  1214. tryPath = *p;
  1215. tryPath += "/lib";
  1216. tryPath += name;
  1217. tryPath += ".so";
  1218. if(SystemTools::FileExists(tryPath.c_str())
  1219. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1220. {
  1221. return SystemTools::CollapseFullPath(tryPath.c_str());
  1222. }
  1223. tryPath = *p;
  1224. tryPath += "/lib";
  1225. tryPath += name;
  1226. tryPath += ".a";
  1227. if(SystemTools::FileExists(tryPath.c_str())
  1228. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1229. {
  1230. return SystemTools::CollapseFullPath(tryPath.c_str());
  1231. }
  1232. tryPath = *p;
  1233. tryPath += "/lib";
  1234. tryPath += name;
  1235. tryPath += ".sl";
  1236. if(SystemTools::FileExists(tryPath.c_str())
  1237. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1238. {
  1239. return SystemTools::CollapseFullPath(tryPath.c_str());
  1240. }
  1241. tryPath = *p;
  1242. tryPath += "/lib";
  1243. tryPath += name;
  1244. tryPath += ".dylib";
  1245. if(SystemTools::FileExists(tryPath.c_str())
  1246. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1247. {
  1248. return SystemTools::CollapseFullPath(tryPath.c_str());
  1249. }
  1250. tryPath = *p;
  1251. tryPath += "/lib";
  1252. tryPath += name;
  1253. tryPath += ".dll";
  1254. if(SystemTools::FileExists(tryPath.c_str())
  1255. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1256. {
  1257. return SystemTools::CollapseFullPath(tryPath.c_str());
  1258. }
  1259. #endif
  1260. }
  1261. // Couldn't find the library.
  1262. return "";
  1263. }
  1264. bool SystemTools::FileIsDirectory(const char* name)
  1265. {
  1266. struct stat fs;
  1267. if(stat(name, &fs) == 0)
  1268. {
  1269. #if _WIN32
  1270. return ((fs.st_mode & _S_IFDIR) != 0);
  1271. #else
  1272. return S_ISDIR(fs.st_mode);
  1273. #endif
  1274. }
  1275. else
  1276. {
  1277. return false;
  1278. }
  1279. }
  1280. int SystemTools::ChangeDirectory(const char *dir)
  1281. {
  1282. return Chdir(dir);
  1283. }
  1284. kwsys_stl::string SystemTools::GetCurrentWorkingDirectory()
  1285. {
  1286. char buf[2048];
  1287. const char* cwd = Getcwd(buf, 2048);
  1288. kwsys_stl::string path;
  1289. if ( cwd )
  1290. {
  1291. path = cwd;
  1292. }
  1293. return SystemTools::CollapseFullPath(path.c_str());
  1294. }
  1295. kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
  1296. {
  1297. kwsys_stl::string dir, file;
  1298. SystemTools::SplitProgramPath(in_name, dir, file);
  1299. return dir;
  1300. }
  1301. bool SystemTools::SplitProgramPath(const char* in_name,
  1302. kwsys_stl::string& dir,
  1303. kwsys_stl::string& file,
  1304. bool)
  1305. {
  1306. dir = in_name;
  1307. file = "";
  1308. SystemTools::ConvertToUnixSlashes(dir);
  1309. if(!SystemTools::FileIsDirectory(dir.c_str()))
  1310. {
  1311. kwsys_stl::string::size_type slashPos = dir.rfind("/");
  1312. if(slashPos != kwsys_stl::string::npos)
  1313. {
  1314. file = dir.substr(slashPos+1);
  1315. dir = dir.substr(0, slashPos);
  1316. }
  1317. else
  1318. {
  1319. file = dir;
  1320. dir = "";
  1321. }
  1322. }
  1323. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  1324. {
  1325. kwsys_stl::string oldDir = in_name;
  1326. SystemTools::ConvertToUnixSlashes(oldDir);
  1327. dir = in_name;
  1328. return false;
  1329. }
  1330. return true;
  1331. }
  1332. bool SystemTools::FindProgramPath(const char* argv0,
  1333. kwsys_stl::string& pathOut,
  1334. kwsys_stl::string& errorMsg,
  1335. const char* exeName,
  1336. const char* buildDir,
  1337. const char* installPrefix )
  1338. {
  1339. kwsys_stl::vector<kwsys_stl::string> failures;
  1340. kwsys_stl::string self = argv0;
  1341. SystemTools::ConvertToUnixSlashes(self);
  1342. failures.push_back(argv0);
  1343. self = SystemTools::FindProgram(self.c_str());
  1344. if(!SystemTools::FileExists(self.c_str()))
  1345. {
  1346. if(buildDir)
  1347. {
  1348. kwsys_stl::string intdir = ".";
  1349. #ifdef CMAKE_INTDIR
  1350. intdir = CMAKE_INTDIR;
  1351. #endif
  1352. self = buildDir;
  1353. self += "/bin/";
  1354. self += intdir;
  1355. self += "/";
  1356. self += exeName;
  1357. self += SystemTools::GetExecutableExtension();
  1358. }
  1359. }
  1360. if(installPrefix)
  1361. {
  1362. if(!SystemTools::FileExists(self.c_str()))
  1363. {
  1364. failures.push_back(self);
  1365. self = installPrefix;
  1366. self += "/bin/";
  1367. self += exeName;
  1368. }
  1369. }
  1370. if(!SystemTools::FileExists(self.c_str()))
  1371. {
  1372. failures.push_back(self);
  1373. kwsys_ios::ostringstream msg;
  1374. msg << "Can not find the command line program " << exeName << "\n";
  1375. msg << " argv[0] = \"" << argv0 << "\"\n";
  1376. msg << " Attempted paths:\n";
  1377. kwsys_stl::vector<kwsys_stl::string>::iterator i;
  1378. for(i=failures.begin(); i != failures.end(); ++i)
  1379. {
  1380. msg << " \"" << i->c_str() << "\"\n";
  1381. }
  1382. errorMsg = msg.str();
  1383. return false;
  1384. }
  1385. pathOut = self;
  1386. return true;
  1387. }
  1388. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
  1389. {
  1390. return SystemTools::CollapseFullPath(in_relative, 0);
  1391. }
  1392. void SystemTools::AddTranslationPath(const char * a, const char * b)
  1393. {
  1394. kwsys_stl::string path_a = a;
  1395. kwsys_stl::string path_b = b;
  1396. SystemTools::ConvertToUnixSlashes(path_a);
  1397. SystemTools::ConvertToUnixSlashes(path_b);
  1398. // First check this is a directory path, since we don't want the table to
  1399. // grow too fat
  1400. if( SystemTools::FileIsDirectory( path_a.c_str() ) )
  1401. {
  1402. // Make sure the path is a full path and does not contain no '..'
  1403. if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
  1404. == kwsys_stl::string::npos )
  1405. {
  1406. // Before inserting make sure path ends with '/'
  1407. if(path_a.size() && path_a[path_a.size() -1] != '/')
  1408. {
  1409. path_a += '/';
  1410. }
  1411. if(path_b.size() && path_b[path_b.size() -1] != '/')
  1412. {
  1413. path_b += '/';
  1414. }
  1415. if( !(path_a == path_b) )
  1416. {
  1417. SystemTools::TranslationMap->insert(
  1418. SystemToolsTranslationMap::value_type(path_a, path_b));
  1419. }
  1420. }
  1421. }
  1422. }
  1423. void SystemTools::AddKeepPath(const char* dir)
  1424. {
  1425. kwsys_stl::string cdir = SystemTools::CollapseFullPath(dir);
  1426. SystemTools::AddTranslationPath(cdir.c_str(), dir);
  1427. }
  1428. void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
  1429. {
  1430. // Do not translate paths that are too short to have meaningful
  1431. // translations.
  1432. if(path.size() < 2)
  1433. {
  1434. return;
  1435. }
  1436. // Always add a trailing slash before translation. It does not
  1437. // matter if this adds an extra slash, but we do not want to
  1438. // translate part of a directory (like the foo part of foo-dir).
  1439. path += "/";
  1440. // In case a file was specified we still have to go through this:
  1441. // Now convert any path found in the table back to the one desired:
  1442. kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
  1443. for(it = SystemTools::TranslationMap->begin();
  1444. it != SystemTools::TranslationMap->end();
  1445. ++it )
  1446. {
  1447. // We need to check of the path is a substring of the other path
  1448. if(path.find( it->first ) == 0)
  1449. {
  1450. path = path.replace( 0, it->first.size(), it->second);
  1451. }
  1452. }
  1453. // Remove the trailing slash we added before.
  1454. path.erase(path.end()-1, path.end());
  1455. }
  1456. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative,
  1457. const char* in_base)
  1458. {
  1459. kwsys_stl::string orig;
  1460. // Change to base of relative path.
  1461. if(in_base)
  1462. {
  1463. // Save original working directory.
  1464. orig = SystemTools::GetCurrentWorkingDirectory();
  1465. Chdir(in_base);
  1466. }
  1467. kwsys_stl::string dir, file;
  1468. SystemTools::SplitProgramPath(in_relative, dir, file, false);
  1469. if(dir.size() == 0 &&
  1470. in_relative && strlen(in_relative) > 0 &&
  1471. in_relative[0] == '/')
  1472. {
  1473. dir = "/";
  1474. }
  1475. // Resolve relative path.
  1476. kwsys_stl::string newDir;
  1477. if(!(dir == ""))
  1478. {
  1479. Realpath(dir.c_str(), newDir);
  1480. }
  1481. else
  1482. {
  1483. newDir = SystemTools::GetCurrentWorkingDirectory();
  1484. }
  1485. if(in_base)
  1486. {
  1487. // Restore original working directory.
  1488. Chdir(orig.c_str());
  1489. }
  1490. // Construct and return the full path.
  1491. kwsys_stl::string newPath = newDir;
  1492. if(!(file == ""))
  1493. {
  1494. if(!(newDir.size() == 1 && newDir[0] == '/'))
  1495. {
  1496. newPath += "/";
  1497. }
  1498. newPath += file;
  1499. }
  1500. // Now we need to update the translation table with this potentially new path
  1501. SystemTools::AddTranslationPath(newPath.c_str(), in_relative);
  1502. SystemTools::CheckTranslationPath(newPath);
  1503. return newPath;
  1504. }
  1505. //----------------------------------------------------------------------------
  1506. void SystemTools::SplitPath(const char* p,
  1507. kwsys_stl::vector<kwsys_stl::string>& components)
  1508. {
  1509. // Identify the root component.
  1510. const char* c = p;
  1511. if(c[0] == '/' && c[1] == '/')
  1512. {
  1513. // Network path.
  1514. components.push_back("//");
  1515. c += 2;
  1516. }
  1517. else if(c[0] == '/')
  1518. {
  1519. // Unix path.
  1520. components.push_back("/");
  1521. c += 1;
  1522. }
  1523. else if(c[0] && c[1] == ':' && c[2] == '/')
  1524. {
  1525. // Windows path.
  1526. kwsys_stl::string root = "_:/";
  1527. root[0] = c[0];
  1528. components.push_back(root);
  1529. c += 3;
  1530. }
  1531. else if(c[0] && c[1] == ':')
  1532. {
  1533. // Path relative to a windows drive working directory.
  1534. kwsys_stl::string root = "_:";
  1535. root[0] = c[0];
  1536. components.push_back(root);
  1537. c += 2;
  1538. }
  1539. else
  1540. {
  1541. // Relative path.
  1542. components.push_back("");
  1543. }
  1544. // Parse the remaining components.
  1545. const char* first = c;
  1546. const char* last = first;
  1547. for(;*last; ++last)
  1548. {
  1549. if(*last == '/')
  1550. {
  1551. // End of a component. Save it.
  1552. components.push_back(kwsys_stl::string(first, last-first));
  1553. first = last+1;
  1554. }
  1555. }
  1556. // Save the last component unless there were no components.
  1557. if(last != c)
  1558. {
  1559. components.push_back(kwsys_stl::string(first, last-first));
  1560. }
  1561. }
  1562. //----------------------------------------------------------------------------
  1563. kwsys_stl::string
  1564. SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components)
  1565. {
  1566. kwsys_stl::string result;
  1567. if(components.size() > 0)
  1568. {
  1569. result += components[0];
  1570. }
  1571. if(components.size() > 1)
  1572. {
  1573. result += components[1];
  1574. }
  1575. for(unsigned int i=2; i < components.size(); ++i)
  1576. {
  1577. result += "/";
  1578. result += components[i];
  1579. }
  1580. return result;
  1581. }
  1582. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
  1583. {
  1584. kwsys_stl::string data(str);
  1585. kwsys_stl::string::size_type lpos = 0;
  1586. while(lpos < data.length())
  1587. {
  1588. kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
  1589. if(rpos == kwsys_stl::string::npos)
  1590. {
  1591. // Line ends at end of string without a newline.
  1592. lines.push_back(data.substr(lpos));
  1593. return false;
  1594. }
  1595. if((rpos > lpos) && (data[rpos-1] == '\r'))
  1596. {
  1597. // Line ends in a "\r\n" pair, remove both characters.
  1598. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  1599. }
  1600. else
  1601. {
  1602. // Line ends in a "\n", remove the character.
  1603. lines.push_back(data.substr(lpos, rpos-lpos));
  1604. }
  1605. lpos = rpos+1;
  1606. }
  1607. return true;
  1608. }
  1609. /**
  1610. * Return path of a full filename (no trailing slashes).
  1611. * Warning: returned path is converted to Unix slashes format.
  1612. */
  1613. kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
  1614. {
  1615. kwsys_stl::string fn = filename;
  1616. SystemTools::ConvertToUnixSlashes(fn);
  1617. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  1618. if(slash_pos != kwsys_stl::string::npos)
  1619. {
  1620. return fn.substr(0, slash_pos);
  1621. }
  1622. else
  1623. {
  1624. return "";
  1625. }
  1626. }
  1627. /**
  1628. * Return file name of a full filename (i.e. file name without path).
  1629. */
  1630. kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
  1631. {
  1632. kwsys_stl::string fn = filename;
  1633. SystemTools::ConvertToUnixSlashes(fn);
  1634. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  1635. if(slash_pos != kwsys_stl::string::npos)
  1636. {
  1637. return fn.substr(slash_pos + 1);
  1638. }
  1639. else
  1640. {
  1641. return filename;
  1642. }
  1643. }
  1644. /**
  1645. * Return file extension of a full filename (dot included).
  1646. * Warning: this is the longest extension (for example: .tar.gz)
  1647. */
  1648. kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
  1649. {
  1650. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  1651. kwsys_stl::string::size_type dot_pos = name.find(".");
  1652. if(dot_pos != kwsys_stl::string::npos)
  1653. {
  1654. return name.substr(dot_pos);
  1655. }
  1656. else
  1657. {
  1658. return "";
  1659. }
  1660. }
  1661. /**
  1662. * Return file extension of a full filename (dot included).
  1663. * Warning: this is the shortest extension (for example: .tar.gz)
  1664. */
  1665. kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
  1666. {
  1667. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  1668. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  1669. if(dot_pos != kwsys_stl::string::npos)
  1670. {
  1671. return name.substr(dot_pos);
  1672. }
  1673. else
  1674. {
  1675. return "";
  1676. }
  1677. }
  1678. /**
  1679. * Return file name without extension of a full filename (i.e. without path).
  1680. * Warning: it considers the longest extension (for example: .tar.gz)
  1681. */
  1682. kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
  1683. {
  1684. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  1685. kwsys_stl::string::size_type dot_pos = name.find(".");
  1686. if(dot_pos != kwsys_stl::string::npos)
  1687. {
  1688. return name.substr(0, dot_pos);
  1689. }
  1690. else
  1691. {
  1692. return name;
  1693. }
  1694. }
  1695. /**
  1696. * Return file name without extension of a full filename (i.e. without path).
  1697. * Warning: it considers the last extension (for example: removes .gz
  1698. * from .tar.gz)
  1699. */
  1700. kwsys_stl::string
  1701. SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
  1702. {
  1703. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  1704. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  1705. if(dot_pos != kwsys_stl::string::npos)
  1706. {
  1707. return name.substr(0, dot_pos);
  1708. }
  1709. else
  1710. {
  1711. return name;
  1712. }
  1713. }
  1714. bool SystemTools::FileIsFullPath(const char* in_name)
  1715. {
  1716. kwsys_stl::string name = in_name;
  1717. #if defined(_WIN32) || defined(__CYGWIN__)
  1718. // On Windows, the name must be at least two characters long.
  1719. if(name.length() < 2)
  1720. {
  1721. return false;
  1722. }
  1723. if(name[1] == ':')
  1724. {
  1725. return true;
  1726. }
  1727. if(name[0] == '\\')
  1728. {
  1729. return true;
  1730. }
  1731. #else
  1732. // On UNIX, the name must be at least one character long.
  1733. if(name.length() < 1)
  1734. {
  1735. return false;
  1736. }
  1737. #endif
  1738. // On UNIX, the name must begin in a '/'.
  1739. // On Windows, if the name begins in a '/', then it is a full
  1740. // network path.
  1741. if(name[0] == '/')
  1742. {
  1743. return true;
  1744. }
  1745. return false;
  1746. }
  1747. bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
  1748. {
  1749. #if defined(WIN32) && !defined(__CYGWIN__)
  1750. const int size = int(strlen(path)) +1; // size of return
  1751. char *buffer = new char[size]; // create a buffer
  1752. char *tempPath = new char[size]; // create a buffer
  1753. int ret;
  1754. // if the path passed in has quotes around it, first remove the quotes
  1755. if (path[0] == '"' && path[strlen(path)-1] == '"')
  1756. {
  1757. strcpy(tempPath,path+1);
  1758. tempPath[strlen(tempPath)-1] = '\0';
  1759. }
  1760. else
  1761. {
  1762. strcpy(tempPath,path);
  1763. }
  1764. buffer[0] = 0;
  1765. ret = GetShortPathName(tempPath, buffer, size);
  1766. if(buffer[0] == 0 || ret > size)
  1767. {
  1768. delete [] buffer;
  1769. delete [] tempPath;
  1770. return false;
  1771. }
  1772. else
  1773. {
  1774. shortPath = buffer;
  1775. delete [] buffer;
  1776. delete [] tempPath;
  1777. return true;
  1778. }
  1779. #else
  1780. shortPath = path;
  1781. return true;
  1782. #endif
  1783. }
  1784. void SystemTools::SplitProgramFromArgs(const char* path,
  1785. kwsys_stl::string& program, kwsys_stl::string& args)
  1786. {
  1787. // see if this is a full path to a program
  1788. // if so then set program to path and args to nothing
  1789. if(SystemTools::FileExists(path))
  1790. {
  1791. program = path;
  1792. args = "";
  1793. return;
  1794. }
  1795. // Try to find the program in the path, note the program
  1796. // may have spaces in its name so we have to look for it
  1797. kwsys_stl::vector<kwsys_stl::string> e;
  1798. kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
  1799. if(findProg.size())
  1800. {
  1801. program = findProg;
  1802. args = "";
  1803. return;
  1804. }
  1805. // Now try and peel off space separated chunks from the end of the string
  1806. // so the largest path possible is found allowing for spaces in the path
  1807. kwsys_stl::string dir = path;
  1808. kwsys_stl::string::size_type spacePos = dir.rfind(' ');
  1809. while(spacePos != kwsys_stl::string::npos)
  1810. {
  1811. kwsys_stl::string tryProg = dir.substr(0, spacePos);
  1812. // See if the file exists
  1813. if(SystemTools::FileExists(tryProg.c_str()))
  1814. {
  1815. program = tryProg;
  1816. // remove trailing spaces from program
  1817. kwsys_stl::string::size_type pos = program.size()-1;
  1818. while(program[pos] == ' ')
  1819. {
  1820. program.erase(pos);
  1821. pos--;
  1822. }
  1823. args = dir.substr(spacePos, dir.size()-spacePos);
  1824. return;
  1825. }
  1826. // Now try and find the the program in the path
  1827. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  1828. if(findProg.size())
  1829. {
  1830. program = findProg;
  1831. // remove trailing spaces from program
  1832. kwsys_stl::string::size_type pos = program.size()-1;
  1833. while(program[pos] == ' ')
  1834. {
  1835. program.erase(pos);
  1836. pos--;
  1837. }
  1838. args = dir.substr(spacePos, dir.size()-spacePos);
  1839. return;
  1840. }
  1841. // move past the space for the next search
  1842. spacePos--;
  1843. spacePos = dir.rfind(' ', spacePos);
  1844. }
  1845. program = "";
  1846. args = "";
  1847. }
  1848. kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
  1849. {
  1850. char buf[1024];
  1851. time_t t;
  1852. time(&t);
  1853. strftime(buf, sizeof(buf), format, localtime(&t));
  1854. return buf;
  1855. }
  1856. kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
  1857. {
  1858. kwsys_stl::string str(s);
  1859. if (str.find_first_of("0123456789") == 0)
  1860. {
  1861. str = "_" + str;
  1862. }
  1863. kwsys_stl::string permited_chars("_"
  1864. "abcdefghijklmnopqrstuvwxyz"
  1865. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1866. "0123456789");
  1867. kwsys_stl::string::size_type pos = 0;
  1868. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
  1869. {
  1870. str[pos] = '_';
  1871. }
  1872. return str;
  1873. }
  1874. // Due to a buggy stream library on the HP and another on Mac OSX, we
  1875. // need this very carefully written version of getline. Returns true
  1876. // if any data were read before the end-of-file was reached.
  1877. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, kwsys_stl::string& line,
  1878. bool *has_newline /* = 0 */)
  1879. {
  1880. const int bufferSize = 1024;
  1881. char buffer[bufferSize];
  1882. line = "";
  1883. bool haveData = false;
  1884. if ( has_newline )
  1885. {
  1886. *has_newline = false;
  1887. }
  1888. // If no characters are read from the stream, the end of file has
  1889. // been reached.
  1890. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  1891. {
  1892. haveData = true;
  1893. line.append(buffer);
  1894. // If newline character was read, the gcount includes the
  1895. // character, but the buffer does not. The end of line has been
  1896. // reached.
  1897. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  1898. {
  1899. if ( has_newline )
  1900. {
  1901. *has_newline = true;
  1902. }
  1903. break;
  1904. }
  1905. // The fail bit may be set. Clear it.
  1906. is.clear(is.rdstate() & ~kwsys_ios::ios::failbit);
  1907. }
  1908. return haveData;
  1909. }
  1910. int SystemTools::GetTerminalWidth()
  1911. {
  1912. int width = -1;
  1913. #ifndef _WIN32
  1914. struct winsize ws;
  1915. char *columns; /* Unix98 environment variable */
  1916. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  1917. {
  1918. width = ws.ws_col;
  1919. }
  1920. if(!isatty(STDOUT_FILENO))
  1921. {
  1922. width = -1;
  1923. }
  1924. columns = getenv("COLUMNS");
  1925. if(columns && *columns)
  1926. {
  1927. long t;
  1928. char *endptr;
  1929. t = strtol(columns, &endptr, 0);
  1930. if(endptr && !*endptr && (t>0) && (t<1000))
  1931. {
  1932. width = (int)t;
  1933. }
  1934. }
  1935. if ( width < 9 )
  1936. {
  1937. width = -1;
  1938. }
  1939. #endif
  1940. return width;
  1941. }
  1942. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  1943. {
  1944. if ( !file )
  1945. {
  1946. return false;
  1947. }
  1948. struct stat st;
  1949. if ( stat(file, &st) < 0 )
  1950. {
  1951. return false;
  1952. }
  1953. mode = st.st_mode;
  1954. return true;
  1955. }
  1956. bool SystemTools::SetPermissions(const char* file, mode_t mode)
  1957. {
  1958. if ( !file )
  1959. {
  1960. return false;
  1961. }
  1962. if ( !SystemTools::FileExists(file) )
  1963. {
  1964. return false;
  1965. }
  1966. if ( chmod(file, mode) < 0 )
  1967. {
  1968. return false;
  1969. }
  1970. return true;
  1971. }
  1972. kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
  1973. {
  1974. if ( !fileOrDir || !*fileOrDir )
  1975. {
  1976. return "";
  1977. }
  1978. kwsys_stl::string res = fileOrDir;
  1979. SystemTools::ConvertToUnixSlashes(res);
  1980. kwsys_stl::string::size_type cc = res.size()-1;
  1981. if ( res[cc] == '/' )
  1982. {
  1983. cc --;
  1984. }
  1985. for ( ; cc > 0; cc -- )
  1986. {
  1987. if ( res[cc] == '/' )
  1988. {
  1989. break;
  1990. }
  1991. }
  1992. return res.substr(0, cc);
  1993. }
  1994. bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
  1995. {
  1996. kwsys_stl::string subdir = cSubdir;
  1997. kwsys_stl::string dir = cDir;
  1998. SystemTools::ConvertToUnixSlashes(dir);
  1999. kwsys_stl::string path = subdir;
  2000. do
  2001. {
  2002. path = SystemTools::GetParentDirectory(path.c_str());
  2003. if ( dir == path )
  2004. {
  2005. return true;
  2006. }
  2007. }
  2008. while ( path.size() > dir.size() );
  2009. return false;
  2010. }
  2011. kwsys_stl::string SystemTools::FileExistsInParentDirectories(const char* fname,
  2012. const char* directory, const char* toplevel)
  2013. {
  2014. kwsys_stl::string file = fname;
  2015. SystemTools::ConvertToUnixSlashes(file);
  2016. kwsys_stl::string dir = directory;
  2017. SystemTools::ConvertToUnixSlashes(dir);
  2018. while ( !dir.empty() )
  2019. {
  2020. kwsys_stl::string path = dir + "/" + file;
  2021. if ( SystemTools::FileExists(path.c_str()) )
  2022. {
  2023. return path;
  2024. }
  2025. if ( dir.size() < strlen(toplevel) )
  2026. {
  2027. break;
  2028. }
  2029. dir = SystemTools::GetParentDirectory(dir.c_str());
  2030. }
  2031. return "";
  2032. }
  2033. void SystemTools::Delay(unsigned int msec)
  2034. {
  2035. #ifdef _WIN32
  2036. Sleep(msec);
  2037. #else
  2038. usleep(msec * 1000);
  2039. #endif
  2040. }
  2041. // These must NOT be initialized. Default initialization to zero is
  2042. // necessary.
  2043. unsigned int SystemToolsManagerCount;
  2044. SystemToolsTranslationMap *SystemTools::TranslationMap;
  2045. // SystemToolsManager manages the SystemTools singleton.
  2046. // SystemToolsManager should be included in any translation unit
  2047. // that will use SystemTools or that implements the singleton
  2048. // pattern. It makes sure that the SystemTools singleton is created
  2049. // before and destroyed after all other singletons in CMake.
  2050. SystemToolsManager::SystemToolsManager()
  2051. {
  2052. if(++SystemToolsManagerCount == 1)
  2053. {
  2054. SystemTools::ClassInitialize();
  2055. }
  2056. }
  2057. SystemToolsManager::~SystemToolsManager()
  2058. {
  2059. if(--SystemToolsManagerCount == 0)
  2060. {
  2061. SystemTools::ClassFinalize();
  2062. }
  2063. }
  2064. void SystemTools::ClassInitialize()
  2065. {
  2066. // Allocate the translation map first.
  2067. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  2068. // Add some special translation paths for unix. These are not added
  2069. // for windows because drive letters need to be maintained. Also,
  2070. // there are not sym-links and mount points on windows anyway.
  2071. #if !defined(_WIN32) || defined(__CYGWIN__)
  2072. // Work-around an SGI problem by always adding this mapping:
  2073. SystemTools::AddTranslationPath("/tmp_mnt/", "/");
  2074. // The tmp path is frequently a logical path so always keep it:
  2075. SystemTools::AddKeepPath("/tmp/");
  2076. // If the current working directory is a logical path then keep the
  2077. // logical name.
  2078. if(const char* pwd = getenv("PWD"))
  2079. {
  2080. char buf[2048];
  2081. if(const char* cwd = Getcwd(buf, 2048))
  2082. {
  2083. kwsys_stl::string pwd_path;
  2084. Realpath(pwd, pwd_path);
  2085. if(cwd == pwd_path && strcmp(cwd, pwd) != 0)
  2086. {
  2087. // The current working directory is a logical path. Split
  2088. // both the logical and physical paths into their components.
  2089. kwsys_stl::vector<kwsys_stl::string> cwd_components;
  2090. kwsys_stl::vector<kwsys_stl::string> pwd_components;
  2091. SystemTools::SplitPath(cwd, cwd_components);
  2092. SystemTools::SplitPath(pwd, pwd_components);
  2093. // Remove the common ending of the paths to leave only the
  2094. // part that changes under the logical mapping.
  2095. kwsys_stl::vector<kwsys_stl::string>::iterator ic = cwd_components.end();
  2096. kwsys_stl::vector<kwsys_stl::string>::iterator ip = pwd_components.end();
  2097. for(;ip != pwd_components.begin() && ic != cwd_components.begin() &&
  2098. *(ip-1) == *(ic-1); --ip,--ic);
  2099. cwd_components.erase(ic, cwd_components.end());
  2100. pwd_components.erase(ip, pwd_components.end());
  2101. // Reconstruct the string versions of the part of the path
  2102. // that changed.
  2103. kwsys_stl::string cwd_changed = SystemTools::JoinPath(cwd_components);
  2104. kwsys_stl::string pwd_changed = SystemTools::JoinPath(pwd_components);
  2105. // Add the translation to keep the logical path name.
  2106. if(!cwd_changed.empty() && !pwd_changed.empty())
  2107. {
  2108. SystemTools::AddTranslationPath(cwd_changed.c_str(),
  2109. pwd_changed.c_str());
  2110. }
  2111. }
  2112. }
  2113. }
  2114. #endif
  2115. }
  2116. void SystemTools::ClassFinalize()
  2117. {
  2118. delete SystemTools::TranslationMap;
  2119. }
  2120. } // namespace KWSYS_NAMESPACE
  2121. #if defined(_MSC_VER) && defined(_DEBUG)
  2122. # include <crtdbg.h>
  2123. # include <stdio.h>
  2124. # include <stdlib.h>
  2125. namespace KWSYS_NAMESPACE
  2126. {
  2127. static int SystemToolsDebugReport(int, char* message, int*)
  2128. {
  2129. fprintf(stderr, message);
  2130. exit(1);
  2131. }
  2132. void SystemTools::EnableMSVCDebugHook()
  2133. {
  2134. if(getenv("DART_TEST_FROM_DART"))
  2135. {
  2136. _CrtSetReportHook(SystemToolsDebugReport);
  2137. }
  2138. }
  2139. } // namespace KWSYS_NAMESPACE
  2140. #else
  2141. namespace KWSYS_NAMESPACE
  2142. {
  2143. void SystemTools::EnableMSVCDebugHook() {}
  2144. } // namespace KWSYS_NAMESPACE
  2145. #endif