SystemTools.cxx 71 KB

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