SystemTools.cxx 71 KB

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