SystemTools.cxx 74 KB

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