SystemTools.cxx 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012
  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. // Work-around CMake dependency scanning limitation. This must
  17. // duplicate the above list of headers.
  18. #if 0
  19. # include "SystemTools.hxx.in"
  20. # include "Directory.hxx.in"
  21. # include "kwsys_ios_iostream.h.in"
  22. # include "kwsys_ios_fstream.h.in"
  23. # include "kwsys_ios_sstream.h.in"
  24. #endif
  25. #ifdef _MSC_VER
  26. # pragma warning (disable: 4786)
  27. #endif
  28. #if defined(__sgi) && !defined(__GNUC__)
  29. # pragma set woff 1375 /* base class destructor not virtual */
  30. #endif
  31. #include <ctype.h>
  32. #include <errno.h>
  33. #ifdef __QNX__
  34. # include <malloc.h> /* for malloc/free on QNX */
  35. #endif
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #include <sys/stat.h>
  40. #include <time.h>
  41. // support for realpath call
  42. #ifndef _WIN32
  43. #include <limits.h>
  44. #include <sys/param.h>
  45. #include <sys/wait.h>
  46. #include <sys/ioctl.h>
  47. #include <unistd.h>
  48. #include <termios.h>
  49. #endif
  50. // Windows API. Some parts used even on cygwin.
  51. #if defined(_WIN32)
  52. # include <windows.h>
  53. #endif
  54. // This is a hack to prevent warnings about these functions being
  55. // declared but not referenced.
  56. #if defined(__sgi) && !defined(__GNUC__)
  57. # include <sys/termios.h>
  58. namespace KWSYS_NAMESPACE
  59. {
  60. class SystemToolsHack
  61. {
  62. public:
  63. enum
  64. {
  65. Ref1 = sizeof(cfgetospeed(0)),
  66. Ref2 = sizeof(cfgetispeed(0)),
  67. Ref3 = sizeof(tcgetattr(0, 0)),
  68. Ref4 = sizeof(tcsetattr(0, 0, 0)),
  69. Ref5 = sizeof(cfsetospeed(0,0)),
  70. Ref6 = sizeof(cfsetispeed(0,0))
  71. };
  72. };
  73. }
  74. #endif
  75. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
  76. #include <io.h>
  77. #include <direct.h>
  78. #define _unlink unlink
  79. #endif
  80. /* The maximum length of a file name. */
  81. #if defined(PATH_MAX)
  82. # define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
  83. #elif defined(MAXPATHLEN)
  84. # define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
  85. #else
  86. # define KWSYS_SYSTEMTOOLS_MAXPATH 16384
  87. #endif
  88. #if defined(__WATCOMC__)
  89. #include <direct.h>
  90. #define _mkdir mkdir
  91. #define _rmdir rmdir
  92. #define _getcwd getcwd
  93. #define _chdir chdir
  94. #endif
  95. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
  96. inline int Mkdir(const char* dir)
  97. {
  98. return _mkdir(dir);
  99. }
  100. inline int Rmdir(const char* dir)
  101. {
  102. return _rmdir(dir);
  103. }
  104. inline const char* Getcwd(char* buf, unsigned int len)
  105. {
  106. const char* ret = _getcwd(buf, len);
  107. if(!ret)
  108. {
  109. fprintf(stderr, "No current working directory.\n");
  110. abort();
  111. }
  112. return ret;
  113. }
  114. inline int Chdir(const char* dir)
  115. {
  116. #if defined(__BORLANDC__)
  117. return chdir(dir);
  118. #else
  119. return _chdir(dir);
  120. #endif
  121. }
  122. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  123. {
  124. char *ptemp;
  125. char fullpath[MAX_PATH];
  126. if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
  127. {
  128. resolved_path = fullpath;
  129. KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
  130. }
  131. }
  132. #else
  133. #include <sys/types.h>
  134. #include <fcntl.h>
  135. #include <unistd.h>
  136. inline int Mkdir(const char* dir)
  137. {
  138. return mkdir(dir, 00777);
  139. }
  140. inline int Rmdir(const char* dir)
  141. {
  142. return rmdir(dir);
  143. }
  144. inline const char* Getcwd(char* buf, unsigned int len)
  145. {
  146. const char* ret = getcwd(buf, len);
  147. if(!ret)
  148. {
  149. fprintf(stderr, "No current working directory\n");
  150. abort();
  151. }
  152. return ret;
  153. }
  154. inline int Chdir(const char* dir)
  155. {
  156. return chdir(dir);
  157. }
  158. inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
  159. {
  160. char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
  161. realpath(path, resolved_name);
  162. resolved_path = resolved_name;
  163. }
  164. #endif
  165. #if !defined(_WIN32) && defined(__COMO__)
  166. // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
  167. extern "C"
  168. {
  169. extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
  170. extern int pclose (FILE *__stream) __THROW;
  171. extern char *realpath (__const char *__restrict __name,
  172. char *__restrict __resolved) __THROW;
  173. extern char *strdup (__const char *__s) __THROW;
  174. extern int putenv (char *__string) __THROW;
  175. }
  176. #endif
  177. /* Implement floattime() for various platforms */
  178. // Taken from Python 2.1.3
  179. #if defined( _WIN32 ) && !defined( __CYGWIN__ )
  180. # include <sys/timeb.h>
  181. # define HAVE_FTIME
  182. # if defined( __BORLANDC__)
  183. # define FTIME ftime
  184. # define TIMEB timeb
  185. # else // Visual studio?
  186. # define FTIME _ftime
  187. # define TIMEB _timeb
  188. # endif
  189. #elif defined( __CYGWIN__ ) || defined( __linux__ )
  190. # include <sys/time.h>
  191. # include <time.h>
  192. # define HAVE_GETTIMEOFDAY
  193. #endif
  194. namespace KWSYS_NAMESPACE
  195. {
  196. class SystemToolsTranslationMap :
  197. public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
  198. {
  199. };
  200. double
  201. SystemTools::GetTime(void)
  202. {
  203. /* There are three ways to get the time:
  204. (1) gettimeofday() -- resolution in microseconds
  205. (2) ftime() -- resolution in milliseconds
  206. (3) time() -- resolution in seconds
  207. In all cases the return value is a float in seconds.
  208. Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
  209. fail, so we fall back on ftime() or time().
  210. Note: clock resolution does not imply clock accuracy! */
  211. #ifdef HAVE_GETTIMEOFDAY
  212. {
  213. struct timeval t;
  214. #ifdef GETTIMEOFDAY_NO_TZ
  215. if (gettimeofday(&t) == 0)
  216. return (double)t.tv_sec + t.tv_usec*0.000001;
  217. #else /* !GETTIMEOFDAY_NO_TZ */
  218. if (gettimeofday(&t, (struct timezone *)NULL) == 0)
  219. return (double)t.tv_sec + t.tv_usec*0.000001;
  220. #endif /* !GETTIMEOFDAY_NO_TZ */
  221. }
  222. #endif /* !HAVE_GETTIMEOFDAY */
  223. {
  224. #if defined(HAVE_FTIME)
  225. struct TIMEB t;
  226. ::FTIME(&t);
  227. return (double)t.time + (double)t.millitm * (double)0.001;
  228. #else /* !HAVE_FTIME */
  229. time_t secs;
  230. time(&secs);
  231. return (double)secs;
  232. #endif /* !HAVE_FTIME */
  233. }
  234. }
  235. // adds the elements of the env variable path to the arg passed in
  236. void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
  237. {
  238. #if defined(_WIN32) && !defined(__CYGWIN__)
  239. const char* pathSep = ";";
  240. #else
  241. const char* pathSep = ":";
  242. #endif
  243. if(!env)
  244. {
  245. env = "PATH";
  246. }
  247. const char* cpathEnv = SystemTools::GetEnv(env);
  248. if ( !cpathEnv )
  249. {
  250. return;
  251. }
  252. kwsys_stl::string pathEnv = cpathEnv;
  253. // A hack to make the below algorithm work.
  254. if(pathEnv[pathEnv.length()-1] != ':')
  255. {
  256. pathEnv += pathSep;
  257. }
  258. kwsys_stl::string::size_type start =0;
  259. bool done = false;
  260. while(!done)
  261. {
  262. kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
  263. if(endpos != kwsys_stl::string::npos)
  264. {
  265. path.push_back(pathEnv.substr(start, endpos-start));
  266. start = endpos+1;
  267. }
  268. else
  269. {
  270. done = true;
  271. }
  272. }
  273. for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
  274. i != path.end(); ++i)
  275. {
  276. SystemTools::ConvertToUnixSlashes(*i);
  277. }
  278. }
  279. const char* SystemTools::GetEnv(const char* key)
  280. {
  281. return getenv(key);
  282. }
  283. bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
  284. {
  285. const char* v = getenv(key);
  286. if(v)
  287. {
  288. result = v;
  289. return true;
  290. }
  291. else
  292. {
  293. return false;
  294. }
  295. }
  296. const char* SystemTools::GetExecutableExtension()
  297. {
  298. #if defined(_WIN32) || defined(__CYGWIN__)
  299. return ".exe";
  300. #else
  301. return "";
  302. #endif
  303. }
  304. bool SystemTools::MakeDirectory(const char* path)
  305. {
  306. if(SystemTools::FileExists(path))
  307. {
  308. return true;
  309. }
  310. kwsys_stl::string dir = path;
  311. if(dir.size() == 0)
  312. {
  313. return false;
  314. }
  315. SystemTools::ConvertToUnixSlashes(dir);
  316. kwsys_stl::string::size_type pos = dir.find(':');
  317. if(pos == kwsys_stl::string::npos)
  318. {
  319. pos = 0;
  320. }
  321. kwsys_stl::string topdir;
  322. while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
  323. {
  324. topdir = dir.substr(0, pos);
  325. Mkdir(topdir.c_str());
  326. pos++;
  327. }
  328. if(dir[dir.size()-1] == '/')
  329. {
  330. topdir = dir.substr(0, dir.size());
  331. }
  332. else
  333. {
  334. topdir = dir;
  335. }
  336. if(Mkdir(topdir.c_str()) != 0)
  337. {
  338. // There is a bug in the Borland Run time library which makes MKDIR
  339. // return EACCES when it should return EEXISTS
  340. // if it is some other error besides directory exists
  341. // then return false
  342. if( (errno != EEXIST)
  343. #ifdef __BORLANDC__
  344. && (errno != EACCES)
  345. #endif
  346. )
  347. {
  348. return false;
  349. }
  350. }
  351. return true;
  352. }
  353. // replace replace with with as many times as it shows up in source.
  354. // write the result into source.
  355. void SystemTools::ReplaceString(kwsys_stl::string& source,
  356. const char* replace,
  357. const char* with)
  358. {
  359. const char *src = source.c_str();
  360. char *searchPos = const_cast<char *>(strstr(src,replace));
  361. // get out quick if string is not found
  362. if (!searchPos)
  363. {
  364. return;
  365. }
  366. // perform replacements until done
  367. size_t replaceSize = strlen(replace);
  368. char *orig = strdup(src);
  369. char *currentPos = orig;
  370. searchPos = searchPos - src + orig;
  371. // initialize the result
  372. source.erase(source.begin(),source.end());
  373. do
  374. {
  375. *searchPos = '\0';
  376. source += currentPos;
  377. currentPos = searchPos + replaceSize;
  378. // replace
  379. source += with;
  380. searchPos = strstr(currentPos,replace);
  381. }
  382. while (searchPos);
  383. // copy any trailing text
  384. source += currentPos;
  385. free(orig);
  386. }
  387. // Read a registry value.
  388. // Example :
  389. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  390. // => will return the data of the "default" value of the key
  391. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  392. // => will return the data of the "Root" value of the key
  393. #if defined(_WIN32) && !defined(__CYGWIN__)
  394. bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value)
  395. {
  396. kwsys_stl::string primary = key;
  397. kwsys_stl::string second;
  398. kwsys_stl::string valuename;
  399. size_t start = primary.find("\\");
  400. if (start == kwsys_stl::string::npos)
  401. {
  402. return false;
  403. }
  404. size_t valuenamepos = primary.find(";");
  405. if (valuenamepos != kwsys_stl::string::npos)
  406. {
  407. valuename = primary.substr(valuenamepos+1);
  408. }
  409. second = primary.substr(start+1, valuenamepos-start-1);
  410. primary = primary.substr(0, start);
  411. HKEY primaryKey = HKEY_CURRENT_USER;
  412. if (primary == "HKEY_CURRENT_USER")
  413. {
  414. primaryKey = HKEY_CURRENT_USER;
  415. }
  416. if (primary == "HKEY_CURRENT_CONFIG")
  417. {
  418. primaryKey = HKEY_CURRENT_CONFIG;
  419. }
  420. if (primary == "HKEY_CLASSES_ROOT")
  421. {
  422. primaryKey = HKEY_CLASSES_ROOT;
  423. }
  424. if (primary == "HKEY_LOCAL_MACHINE")
  425. {
  426. primaryKey = HKEY_LOCAL_MACHINE;
  427. }
  428. if (primary == "HKEY_USERS")
  429. {
  430. primaryKey = HKEY_USERS;
  431. }
  432. HKEY hKey;
  433. if(RegOpenKeyEx(primaryKey,
  434. second.c_str(),
  435. 0,
  436. KEY_READ,
  437. &hKey) != ERROR_SUCCESS)
  438. {
  439. return false;
  440. }
  441. else
  442. {
  443. DWORD dwType, dwSize;
  444. dwSize = 1023;
  445. char data[1024];
  446. if(RegQueryValueEx(hKey,
  447. (LPTSTR)valuename.c_str(),
  448. NULL,
  449. &dwType,
  450. (BYTE *)data,
  451. &dwSize) == ERROR_SUCCESS)
  452. {
  453. if (dwType == REG_SZ)
  454. {
  455. value = data;
  456. RegCloseKey(hKey);
  457. return true;
  458. }
  459. }
  460. }
  461. return false;
  462. }
  463. #else
  464. bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &)
  465. {
  466. return false;
  467. }
  468. #endif
  469. // Write a registry value.
  470. // Example :
  471. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  472. // => will set the data of the "default" value of the key
  473. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  474. // => will set the data of the "Root" value of the key
  475. #if defined(_WIN32) && !defined(__CYGWIN__)
  476. bool SystemTools::WriteRegistryValue(const char *key, const char *value)
  477. {
  478. kwsys_stl::string primary = key;
  479. kwsys_stl::string second;
  480. kwsys_stl::string valuename;
  481. size_t start = primary.find("\\");
  482. if (start == kwsys_stl::string::npos)
  483. {
  484. return false;
  485. }
  486. size_t valuenamepos = primary.find(";");
  487. if (valuenamepos != kwsys_stl::string::npos)
  488. {
  489. valuename = primary.substr(valuenamepos+1);
  490. }
  491. second = primary.substr(start+1, valuenamepos-start-1);
  492. primary = primary.substr(0, start);
  493. HKEY primaryKey = HKEY_CURRENT_USER;
  494. if (primary == "HKEY_CURRENT_USER")
  495. {
  496. primaryKey = HKEY_CURRENT_USER;
  497. }
  498. if (primary == "HKEY_CURRENT_CONFIG")
  499. {
  500. primaryKey = HKEY_CURRENT_CONFIG;
  501. }
  502. if (primary == "HKEY_CLASSES_ROOT")
  503. {
  504. primaryKey = HKEY_CLASSES_ROOT;
  505. }
  506. if (primary == "HKEY_LOCAL_MACHINE")
  507. {
  508. primaryKey = HKEY_LOCAL_MACHINE;
  509. }
  510. if (primary == "HKEY_USERS")
  511. {
  512. primaryKey = HKEY_USERS;
  513. }
  514. HKEY hKey;
  515. DWORD dwDummy;
  516. if(RegCreateKeyEx(primaryKey,
  517. second.c_str(),
  518. 0,
  519. "",
  520. REG_OPTION_NON_VOLATILE,
  521. KEY_WRITE,
  522. NULL,
  523. &hKey,
  524. &dwDummy) != ERROR_SUCCESS)
  525. {
  526. return false;
  527. }
  528. if(RegSetValueEx(hKey,
  529. (LPTSTR)valuename.c_str(),
  530. 0,
  531. REG_SZ,
  532. (CONST BYTE *)value,
  533. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  534. {
  535. return true;
  536. }
  537. return false;
  538. }
  539. #else
  540. bool SystemTools::WriteRegistryValue(const char *, const char *)
  541. {
  542. return false;
  543. }
  544. #endif
  545. // Delete a registry value.
  546. // Example :
  547. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  548. // => will delete the data of the "default" value of the key
  549. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  550. // => will delete the data of the "Root" value of the key
  551. #if defined(_WIN32) && !defined(__CYGWIN__)
  552. bool SystemTools::DeleteRegistryValue(const char *key)
  553. {
  554. kwsys_stl::string primary = key;
  555. kwsys_stl::string second;
  556. kwsys_stl::string valuename;
  557. size_t start = primary.find("\\");
  558. if (start == kwsys_stl::string::npos)
  559. {
  560. return false;
  561. }
  562. size_t valuenamepos = primary.find(";");
  563. if (valuenamepos != kwsys_stl::string::npos)
  564. {
  565. valuename = primary.substr(valuenamepos+1);
  566. }
  567. second = primary.substr(start+1, valuenamepos-start-1);
  568. primary = primary.substr(0, start);
  569. HKEY primaryKey = HKEY_CURRENT_USER;
  570. if (primary == "HKEY_CURRENT_USER")
  571. {
  572. primaryKey = HKEY_CURRENT_USER;
  573. }
  574. if (primary == "HKEY_CURRENT_CONFIG")
  575. {
  576. primaryKey = HKEY_CURRENT_CONFIG;
  577. }
  578. if (primary == "HKEY_CLASSES_ROOT")
  579. {
  580. primaryKey = HKEY_CLASSES_ROOT;
  581. }
  582. if (primary == "HKEY_LOCAL_MACHINE")
  583. {
  584. primaryKey = HKEY_LOCAL_MACHINE;
  585. }
  586. if (primary == "HKEY_USERS")
  587. {
  588. primaryKey = HKEY_USERS;
  589. }
  590. HKEY hKey;
  591. if(RegOpenKeyEx(primaryKey,
  592. second.c_str(),
  593. 0,
  594. KEY_WRITE,
  595. &hKey) != ERROR_SUCCESS)
  596. {
  597. return false;
  598. }
  599. else
  600. {
  601. if(RegDeleteValue(hKey,
  602. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  603. {
  604. RegCloseKey(hKey);
  605. return true;
  606. }
  607. }
  608. return false;
  609. }
  610. #else
  611. bool SystemTools::DeleteRegistryValue(const char *)
  612. {
  613. return false;
  614. }
  615. #endif
  616. bool SystemTools::SameFile(const char* file1, const char* file2)
  617. {
  618. #ifdef _WIN32
  619. HANDLE hFile1, hFile2;
  620. hFile1 = CreateFile( file1,
  621. GENERIC_READ,
  622. FILE_SHARE_READ ,
  623. NULL,
  624. OPEN_EXISTING,
  625. FILE_FLAG_BACKUP_SEMANTICS,
  626. NULL
  627. );
  628. hFile2 = CreateFile( file2,
  629. GENERIC_READ,
  630. FILE_SHARE_READ,
  631. NULL,
  632. OPEN_EXISTING,
  633. FILE_FLAG_BACKUP_SEMANTICS,
  634. NULL
  635. );
  636. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  637. {
  638. if(hFile1 != INVALID_HANDLE_VALUE)
  639. {
  640. CloseHandle(hFile1);
  641. }
  642. if(hFile2 != INVALID_HANDLE_VALUE)
  643. {
  644. CloseHandle(hFile2);
  645. }
  646. return false;
  647. }
  648. BY_HANDLE_FILE_INFORMATION fiBuf1;
  649. BY_HANDLE_FILE_INFORMATION fiBuf2;
  650. GetFileInformationByHandle( hFile1, &fiBuf1 );
  651. GetFileInformationByHandle( hFile2, &fiBuf2 );
  652. CloseHandle(hFile1);
  653. CloseHandle(hFile2);
  654. return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
  655. fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  656. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  657. #else
  658. struct stat fileStat1, fileStat2;
  659. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  660. {
  661. // see if the files are the same file
  662. // check the device inode and size
  663. if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
  664. memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
  665. fileStat2.st_size == fileStat1.st_size
  666. )
  667. {
  668. return true;
  669. }
  670. }
  671. return false;
  672. #endif
  673. }
  674. // return true if the file exists
  675. bool SystemTools::FileExists(const char* filename)
  676. {
  677. #ifdef _MSC_VER
  678. # define access _access
  679. #endif
  680. #ifndef R_OK
  681. # define R_OK 04
  682. #endif
  683. if ( access(filename, R_OK) != 0 )
  684. {
  685. return false;
  686. }
  687. else
  688. {
  689. return true;
  690. }
  691. }
  692. bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
  693. int* result)
  694. {
  695. // Default to same time.
  696. *result = 0;
  697. #if !defined(_WIN32) || defined(__CYGWIN__)
  698. // POSIX version. Use stat function to get file modification time.
  699. struct stat s1;
  700. if(stat(f1, &s1) != 0)
  701. {
  702. return false;
  703. }
  704. struct stat s2;
  705. if(stat(f2, &s2) != 0)
  706. {
  707. return false;
  708. }
  709. # if KWSYS_STAT_HAS_ST_MTIM
  710. // Compare using nanosecond resolution.
  711. if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
  712. {
  713. *result = -1;
  714. }
  715. else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
  716. {
  717. *result = 1;
  718. }
  719. else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
  720. {
  721. *result = -1;
  722. }
  723. else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
  724. {
  725. *result = 1;
  726. }
  727. # else
  728. // Compare using 1 second resolution.
  729. if(s1.st_mtime < s2.st_mtime)
  730. {
  731. *result = -1;
  732. }
  733. else if(s1.st_mtime > s2.st_mtime)
  734. {
  735. *result = 1;
  736. }
  737. # endif
  738. #else
  739. // Windows version. Get the modification time from extended file attributes.
  740. WIN32_FILE_ATTRIBUTE_DATA f1d;
  741. WIN32_FILE_ATTRIBUTE_DATA f2d;
  742. if(!GetFileAttributesEx(f1, GetFileExInfoStandard, &f1d))
  743. {
  744. return false;
  745. }
  746. if(!GetFileAttributesEx(f2, GetFileExInfoStandard, &f2d))
  747. {
  748. return false;
  749. }
  750. // Compare the file times using resolution provided by system call.
  751. *result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime);
  752. #endif
  753. return true;
  754. }
  755. // Return a capitalized string (i.e the first letter is uppercased, all other
  756. // are lowercased)
  757. kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
  758. {
  759. kwsys_stl::string n;
  760. if(s.size() == 0)
  761. {
  762. return n;
  763. }
  764. n.resize(s.size());
  765. n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
  766. for (size_t i = 1; i < s.size(); i++)
  767. {
  768. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  769. }
  770. return n;
  771. }
  772. // Return capitalized words
  773. kwsys_stl::string SystemTools::CapitalizedWords(const kwsys_stl::string& s)
  774. {
  775. kwsys_stl::string n(s);
  776. for (size_t i = 0; i < s.size(); i++)
  777. {
  778. #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
  779. // MS has an assert that will fail if s[i] < 0; setting
  780. // LC_CTYPE using setlocale() does *not* help. Painful.
  781. if ((int)s[i] >= 0 && isalpha(s[i]) &&
  782. (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
  783. #else
  784. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  785. #endif
  786. {
  787. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  788. }
  789. }
  790. return n;
  791. }
  792. // Return uncapitalized words
  793. kwsys_stl::string SystemTools::UnCapitalizedWords(const kwsys_stl::string& s)
  794. {
  795. kwsys_stl::string n(s);
  796. for (size_t i = 0; i < s.size(); i++)
  797. {
  798. #if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
  799. // MS has an assert that will fail if s[i] < 0; setting
  800. // LC_CTYPE using setlocale() does *not* help. Painful.
  801. if ((int)s[i] >= 0 && isalpha(s[i]) &&
  802. (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
  803. #else
  804. if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
  805. #endif
  806. {
  807. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  808. }
  809. }
  810. return n;
  811. }
  812. kwsys_stl::string SystemTools::AddSpaceBetweenCapitalizedWords(
  813. const kwsys_stl::string& s)
  814. {
  815. kwsys_stl::string n;
  816. if (s.size())
  817. {
  818. n.reserve(s.size());
  819. n += s[0];
  820. for (size_t i = 1; i < s.size(); i++)
  821. {
  822. if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1]))
  823. {
  824. n += ' ';
  825. }
  826. n += s[i];
  827. }
  828. }
  829. return n;
  830. }
  831. char* SystemTools::AppendStrings(const char* str1, const char* str2)
  832. {
  833. if (!str1)
  834. {
  835. return SystemTools::DuplicateString(str2);
  836. }
  837. if (!str2)
  838. {
  839. return SystemTools::DuplicateString(str1);
  840. }
  841. size_t len1 = strlen(str1);
  842. char *newstr = new char[len1 + strlen(str2) + 1];
  843. if (!newstr)
  844. {
  845. return 0;
  846. }
  847. strcpy(newstr, str1);
  848. strcat(newstr + len1, str2);
  849. return newstr;
  850. }
  851. char* SystemTools::AppendStrings(
  852. const char* str1, const char* str2, const char* str3)
  853. {
  854. if (!str1)
  855. {
  856. return SystemTools::AppendStrings(str2, str3);
  857. }
  858. if (!str2)
  859. {
  860. return SystemTools::AppendStrings(str1, str3);
  861. }
  862. if (!str3)
  863. {
  864. return SystemTools::AppendStrings(str1, str2);
  865. }
  866. size_t len1 = strlen(str1), len2 = strlen(str2);
  867. char *newstr = new char[len1 + len2 + strlen(str3) + 1];
  868. if (!newstr)
  869. {
  870. return 0;
  871. }
  872. strcpy(newstr, str1);
  873. strcat(newstr + len1, str2);
  874. strcat(newstr + len1 + len2, str3);
  875. return newstr;
  876. }
  877. // Return a lower case string
  878. kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
  879. {
  880. kwsys_stl::string n;
  881. n.resize(s.size());
  882. for (size_t i = 0; i < s.size(); i++)
  883. {
  884. n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
  885. }
  886. return n;
  887. }
  888. // Return a lower case string
  889. kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
  890. {
  891. kwsys_stl::string n;
  892. n.resize(s.size());
  893. for (size_t i = 0; i < s.size(); i++)
  894. {
  895. n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
  896. }
  897. return n;
  898. }
  899. // Count char in string
  900. size_t SystemTools::CountChar(const char* str, char c)
  901. {
  902. size_t count = 0;
  903. if (str)
  904. {
  905. while (*str)
  906. {
  907. if (*str == c)
  908. {
  909. ++count;
  910. }
  911. ++str;
  912. }
  913. }
  914. return count;
  915. }
  916. // Remove chars in string
  917. char* SystemTools::RemoveChars(const char* str, const char *toremove)
  918. {
  919. if (!str)
  920. {
  921. return NULL;
  922. }
  923. char *clean_str = new char [strlen(str) + 1];
  924. char *ptr = clean_str;
  925. while (*str)
  926. {
  927. const char *str2 = toremove;
  928. while (*str2 && *str != *str2)
  929. {
  930. ++str2;
  931. }
  932. if (!*str2)
  933. {
  934. *ptr++ = *str;
  935. }
  936. ++str;
  937. }
  938. *ptr = '\0';
  939. return clean_str;
  940. }
  941. // Remove chars in string
  942. char* SystemTools::RemoveCharsButUpperHex(const char* str)
  943. {
  944. if (!str)
  945. {
  946. return 0;
  947. }
  948. char *clean_str = new char [strlen(str) + 1];
  949. char *ptr = clean_str;
  950. while (*str)
  951. {
  952. if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'H'))
  953. {
  954. *ptr++ = *str;
  955. }
  956. ++str;
  957. }
  958. *ptr = '\0';
  959. return clean_str;
  960. }
  961. // Replace chars in string
  962. char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
  963. {
  964. if (str)
  965. {
  966. char *ptr = str;
  967. while (*ptr)
  968. {
  969. const char *ptr2 = toreplace;
  970. while (*ptr2)
  971. {
  972. if (*ptr == *ptr2)
  973. {
  974. *ptr = replacement;
  975. }
  976. ++ptr2;
  977. }
  978. ++ptr;
  979. }
  980. }
  981. return str;
  982. }
  983. // Returns if string starts with another string
  984. bool SystemTools::StringStartsWith(const char* str1, const char* str2)
  985. {
  986. if (!str1 || !str2)
  987. {
  988. return false;
  989. }
  990. size_t len1 = strlen(str1), len2 = strlen(str2);
  991. return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
  992. }
  993. // Returns if string ends with another string
  994. bool SystemTools::StringEndsWith(const char* str1, const char* str2)
  995. {
  996. if (!str1 || !str2)
  997. {
  998. return false;
  999. }
  1000. size_t len1 = strlen(str1), len2 = strlen(str2);
  1001. return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
  1002. }
  1003. // Returns a pointer to the last occurence of str2 in str1
  1004. const char* SystemTools::FindLastString(const char* str1, const char* str2)
  1005. {
  1006. if (!str1 || !str2)
  1007. {
  1008. return NULL;
  1009. }
  1010. size_t len1 = strlen(str1), len2 = strlen(str2);
  1011. if (len1 >= len2)
  1012. {
  1013. const char *ptr = str1 + len1 - len2;
  1014. do
  1015. {
  1016. if (!strncmp(ptr, str2, len2))
  1017. {
  1018. return ptr;
  1019. }
  1020. } while (ptr-- != str1);
  1021. }
  1022. return NULL;
  1023. }
  1024. // Duplicate string
  1025. char* SystemTools::DuplicateString(const char* str)
  1026. {
  1027. if (str)
  1028. {
  1029. char *newstr = new char [strlen(str) + 1];
  1030. return strcpy(newstr, str);
  1031. }
  1032. return NULL;
  1033. }
  1034. // Return a cropped string
  1035. kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s,
  1036. size_t max_len)
  1037. {
  1038. if (!s.size() || max_len == 0 || max_len >= s.size())
  1039. {
  1040. return s;
  1041. }
  1042. kwsys_stl::string n;
  1043. n.reserve(max_len);
  1044. size_t middle = max_len / 2;
  1045. n += s.substr(0, middle);
  1046. n += s.substr(s.size() - (max_len - middle), kwsys_stl::string::npos);
  1047. if (max_len > 2)
  1048. {
  1049. n[middle] = '.';
  1050. if (max_len > 3)
  1051. {
  1052. n[middle - 1] = '.';
  1053. if (max_len > 4)
  1054. {
  1055. n[middle + 1] = '.';
  1056. }
  1057. }
  1058. }
  1059. return n;
  1060. }
  1061. //----------------------------------------------------------------------------
  1062. kwsys_stl::vector<kwsys::String> SystemTools::SplitString(const char* p, char sep, bool isPath)
  1063. {
  1064. kwsys_stl::string path = p;
  1065. kwsys_stl::vector<kwsys::String> paths;
  1066. if(isPath && path[0] == '/')
  1067. {
  1068. path.erase(path.begin());
  1069. paths.push_back("/");
  1070. }
  1071. kwsys_stl::string::size_type pos1 = 0;
  1072. kwsys_stl::string::size_type pos2 = path.find(sep, pos1+1);
  1073. while(pos2 != kwsys_stl::string::npos)
  1074. {
  1075. paths.push_back(path.substr(pos1, pos2-pos1));
  1076. pos1 = pos2+1;
  1077. pos2 = path.find(sep, pos1+1);
  1078. }
  1079. paths.push_back(path.substr(pos1, pos2-pos1));
  1080. return paths;
  1081. }
  1082. //----------------------------------------------------------------------------
  1083. int SystemTools::EstimateFormatLength(const char *format, va_list ap)
  1084. {
  1085. if (!format)
  1086. {
  1087. return 0;
  1088. }
  1089. // Quick-hack attempt at estimating the length of the string.
  1090. // Should never under-estimate.
  1091. // Start with the length of the format string itself.
  1092. size_t length = strlen(format);
  1093. // Increase the length for every argument in the format.
  1094. const char* cur = format;
  1095. while(*cur)
  1096. {
  1097. if(*cur++ == '%')
  1098. {
  1099. // Skip "%%" since it doesn't correspond to a va_arg.
  1100. if(*cur != '%')
  1101. {
  1102. while(!int(isalpha(*cur)))
  1103. {
  1104. ++cur;
  1105. }
  1106. switch (*cur)
  1107. {
  1108. case 's':
  1109. {
  1110. // Check the length of the string.
  1111. char* s = va_arg(ap, char*);
  1112. if(s)
  1113. {
  1114. length += strlen(s);
  1115. }
  1116. } break;
  1117. case 'e':
  1118. case 'f':
  1119. case 'g':
  1120. {
  1121. // Assume the argument contributes no more than 64 characters.
  1122. length += 64;
  1123. // Eat the argument.
  1124. static_cast<void>(va_arg(ap, double));
  1125. } break;
  1126. default:
  1127. {
  1128. // Assume the argument contributes no more than 64 characters.
  1129. length += 64;
  1130. // Eat the argument.
  1131. static_cast<void>(va_arg(ap, int));
  1132. } break;
  1133. }
  1134. }
  1135. // Move past the characters just tested.
  1136. ++cur;
  1137. }
  1138. }
  1139. return (int)length;
  1140. }
  1141. kwsys_stl::string SystemTools::EscapeChars(
  1142. const char *str,
  1143. const char *chars_to_escape,
  1144. char escape_char)
  1145. {
  1146. kwsys_stl::string n;
  1147. if (str)
  1148. {
  1149. if (!chars_to_escape | !*chars_to_escape)
  1150. {
  1151. n.append(str);
  1152. }
  1153. else
  1154. {
  1155. n.reserve(strlen(str));
  1156. while (*str)
  1157. {
  1158. const char *ptr = chars_to_escape;
  1159. while (*ptr)
  1160. {
  1161. if (*str == *ptr)
  1162. {
  1163. n += escape_char;
  1164. break;
  1165. }
  1166. ++ptr;
  1167. }
  1168. n += *str;
  1169. ++str;
  1170. }
  1171. }
  1172. }
  1173. return n;
  1174. }
  1175. // convert windows slashes to unix slashes
  1176. void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
  1177. {
  1178. const char* pathCString = path.c_str();
  1179. bool hasDoubleSlash = false;
  1180. const char* pos0 = pathCString;
  1181. const char* pos1 = pathCString+1;
  1182. for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
  1183. {
  1184. // make sure we don't convert an escaped space to a unix slash
  1185. if ( *pos0 == '\\' && *pos1 != ' ' )
  1186. {
  1187. path[pos] = '/';
  1188. }
  1189. // Also, reuse the loop to check for slash followed by another slash
  1190. if ( !hasDoubleSlash && *pos1 &&
  1191. *pos1 == '/' && *(pos1+1) == '/' )
  1192. {
  1193. #ifdef _WIN32
  1194. // However, on windows if the first characters are both slashes,
  1195. // then keep them that way, so that network paths can be handled.
  1196. if ( pos > 0)
  1197. {
  1198. hasDoubleSlash = true;
  1199. }
  1200. #else
  1201. hasDoubleSlash = true;
  1202. #endif
  1203. }
  1204. pos0 ++;
  1205. pos1 ++;
  1206. }
  1207. if ( hasDoubleSlash )
  1208. {
  1209. SystemTools::ReplaceString(path, "//", "/");
  1210. }
  1211. // remove any trailing slash
  1212. if(!path.empty())
  1213. {
  1214. // if there is a tilda ~ then replace it with HOME
  1215. pathCString = path.c_str();
  1216. if(*pathCString == '~')
  1217. {
  1218. const char* homeEnv = SystemTools::GetEnv("HOME");
  1219. if (homeEnv)
  1220. {
  1221. path.replace(0,1,homeEnv);
  1222. }
  1223. }
  1224. pathCString = path.c_str();
  1225. if (*(pathCString+(path.size()-1)) == '/')
  1226. {
  1227. path = path.substr(0, path.size()-1);
  1228. }
  1229. }
  1230. }
  1231. // change // to /, and escape any spaces in the path
  1232. kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
  1233. {
  1234. kwsys_stl::string ret = path;
  1235. // remove // except at the beginning might be a cygwin drive
  1236. kwsys_stl::string::size_type pos=0;
  1237. while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
  1238. {
  1239. ret.erase(pos, 1);
  1240. }
  1241. // now escape spaces if there is a space in the path
  1242. if(ret.find(" ") != kwsys_stl::string::npos)
  1243. {
  1244. kwsys_stl::string result = "";
  1245. char lastch = 1;
  1246. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  1247. {
  1248. // if it is already escaped then don't try to escape it again
  1249. if(*ch == ' ' && lastch != '\\')
  1250. {
  1251. result += '\\';
  1252. }
  1253. result += *ch;
  1254. lastch = *ch;
  1255. }
  1256. ret = result;
  1257. }
  1258. return ret;
  1259. }
  1260. kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
  1261. {
  1262. #if defined(_WIN32) && !defined(__CYGWIN__)
  1263. return SystemTools::ConvertToWindowsOutputPath(path);
  1264. #else
  1265. return SystemTools::ConvertToUnixOutputPath(path);
  1266. #endif
  1267. }
  1268. // remove double slashes not at the start
  1269. kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  1270. {
  1271. kwsys_stl::string ret;
  1272. // make it big enough for all of path and double quotes
  1273. ret.reserve(strlen(path)+3);
  1274. // put path into the string
  1275. ret.insert(0,path);
  1276. kwsys_stl::string::size_type pos = 0;
  1277. // first convert all of the slashes
  1278. while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
  1279. {
  1280. ret[pos] = '\\';
  1281. pos++;
  1282. }
  1283. // check for really small paths
  1284. if(ret.size() < 2)
  1285. {
  1286. return ret;
  1287. }
  1288. // now clean up a bit and remove double slashes
  1289. // Only if it is not the first position in the path which is a network
  1290. // path on windows
  1291. pos = 1; // start at position 1
  1292. if(ret[0] == '\"')
  1293. {
  1294. pos = 2; // if the string is already quoted then start at 2
  1295. if(ret.size() < 3)
  1296. {
  1297. return ret;
  1298. }
  1299. }
  1300. while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
  1301. {
  1302. ret.erase(pos, 1);
  1303. }
  1304. // now double quote the path if it has spaces in it
  1305. // and is not already double quoted
  1306. if(ret.find(' ') != kwsys_stl::string::npos
  1307. && ret[0] != '\"')
  1308. {
  1309. ret.insert(static_cast<kwsys_stl::string::size_type>(0),
  1310. static_cast<kwsys_stl::string::size_type>(1), '\"');
  1311. ret.append(1, '\"');
  1312. }
  1313. return ret;
  1314. }
  1315. bool SystemTools::CopyFileIfDifferent(const char* source,
  1316. const char* destination)
  1317. {
  1318. if(SystemTools::FilesDiffer(source, destination))
  1319. {
  1320. return SystemTools::CopyFileAlways(source, destination);
  1321. }
  1322. return true;
  1323. }
  1324. #define KWSYS_ST_BUFFER 4096
  1325. bool SystemTools::FilesDiffer(const char* source,
  1326. const char* destination)
  1327. {
  1328. struct stat statSource;
  1329. if (stat(source, &statSource) != 0)
  1330. {
  1331. return true;
  1332. }
  1333. struct stat statDestination;
  1334. if (stat(destination, &statDestination) != 0)
  1335. {
  1336. return true;
  1337. }
  1338. if(statSource.st_size != statDestination.st_size)
  1339. {
  1340. return true;
  1341. }
  1342. if(statSource.st_size == 0)
  1343. {
  1344. return false;
  1345. }
  1346. #if defined(_WIN32) || defined(__CYGWIN__)
  1347. kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
  1348. kwsys_ios::ios::in));
  1349. kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
  1350. kwsys_ios::ios::in));
  1351. #else
  1352. kwsys_ios::ifstream finSource(source);
  1353. kwsys_ios::ifstream finDestination(destination);
  1354. #endif
  1355. if(!finSource || !finDestination)
  1356. {
  1357. return true;
  1358. }
  1359. // Compare the files a block at a time.
  1360. char source_buf[KWSYS_ST_BUFFER];
  1361. char dest_buf[KWSYS_ST_BUFFER];
  1362. long nleft = statSource.st_size;
  1363. while(nleft > 0)
  1364. {
  1365. // Read a block from each file.
  1366. long nnext = (nleft > KWSYS_ST_BUFFER)? KWSYS_ST_BUFFER : nleft;
  1367. finSource.read(source_buf, nnext);
  1368. finDestination.read(dest_buf, nnext);
  1369. // If either failed to read assume they are different.
  1370. if(static_cast<long>(finSource.gcount()) != nnext ||
  1371. static_cast<long>(finDestination.gcount()) != nnext)
  1372. {
  1373. return true;
  1374. }
  1375. // If this block differs the file differs.
  1376. if(memcmp((const void*)source_buf, (const void*)dest_buf, nnext) != 0)
  1377. {
  1378. return true;
  1379. }
  1380. // Update the byte count remaining.
  1381. nleft -= nnext;
  1382. }
  1383. // No differences found.
  1384. return false;
  1385. }
  1386. /**
  1387. * Copy a file named by "source" to the file named by "destination".
  1388. */
  1389. bool SystemTools::CopyFileAlways(const char* source, const char* destination)
  1390. {
  1391. // If files are the same do not copy
  1392. if ( SystemTools::SameFile(source, destination) )
  1393. {
  1394. return true;
  1395. }
  1396. mode_t perm = 0;
  1397. bool perms = SystemTools::GetPermissions(source, perm);
  1398. const int bufferSize = 4096;
  1399. char buffer[bufferSize];
  1400. // If destination is a directory, try to create a file with the same
  1401. // name as the source in that directory.
  1402. kwsys_stl::string new_destination;
  1403. if(SystemTools::FileExists(destination) &&
  1404. SystemTools::FileIsDirectory(destination))
  1405. {
  1406. new_destination = destination;
  1407. SystemTools::ConvertToUnixSlashes(new_destination);
  1408. new_destination += '/';
  1409. kwsys_stl::string source_name = source;
  1410. new_destination += SystemTools::GetFilenameName(source_name);
  1411. destination = new_destination.c_str();
  1412. }
  1413. // Create destination directory
  1414. kwsys_stl::string destination_dir = destination;
  1415. destination_dir = SystemTools::GetFilenamePath(destination_dir);
  1416. SystemTools::MakeDirectory(destination_dir.c_str());
  1417. // Open files
  1418. #if defined(_WIN32) || defined(__CYGWIN__)
  1419. kwsys_ios::ifstream fin(source,
  1420. kwsys_ios::ios::binary | kwsys_ios::ios::in);
  1421. #else
  1422. kwsys_ios::ifstream fin(source);
  1423. #endif
  1424. if(!fin)
  1425. {
  1426. return false;
  1427. }
  1428. // try and remove the destination file so that read only destination files
  1429. // can be written to.
  1430. // If the remove fails continue so that files in read only directories
  1431. // that do not allow file removal can be modified.
  1432. SystemTools::RemoveFile(destination);
  1433. #if defined(_WIN32) || defined(__CYGWIN__)
  1434. kwsys_ios::ofstream fout(destination,
  1435. kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1436. #else
  1437. kwsys_ios::ofstream fout(destination,
  1438. kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1439. #endif
  1440. if(!fout)
  1441. {
  1442. return false;
  1443. }
  1444. // This copy loop is very sensitive on certain platforms with
  1445. // slightly broken stream libraries (like HPUX). Normally, it is
  1446. // incorrect to not check the error condition on the fin.read()
  1447. // before using the data, but the fin.gcount() will be zero if an
  1448. // error occurred. Therefore, the loop should be safe everywhere.
  1449. while(fin)
  1450. {
  1451. fin.read(buffer, bufferSize);
  1452. if(fin.gcount())
  1453. {
  1454. fout.write(buffer, fin.gcount());
  1455. }
  1456. }
  1457. // Make sure the operating system has finished writing the file
  1458. // before closing it. This will ensure the file is finished before
  1459. // the check below.
  1460. fout.flush();
  1461. fin.close();
  1462. fout.close();
  1463. // More checks.
  1464. struct stat statSource, statDestination;
  1465. statSource.st_size = 12345;
  1466. statDestination.st_size = 12345;
  1467. if(stat(source, &statSource) != 0)
  1468. {
  1469. return false;
  1470. }
  1471. else if(stat(destination, &statDestination) != 0)
  1472. {
  1473. return false;
  1474. }
  1475. else if(statSource.st_size != statDestination.st_size)
  1476. {
  1477. return false;
  1478. }
  1479. if ( perms )
  1480. {
  1481. if ( !SystemTools::SetPermissions(destination, perm) )
  1482. {
  1483. return false;
  1484. }
  1485. }
  1486. return true;
  1487. }
  1488. /**
  1489. * Copy a directory content from "source" directory to the directory named by
  1490. * "destination".
  1491. */
  1492. bool SystemTools::CopyADirectory(const char* source, const char* destination)
  1493. {
  1494. Directory dir;
  1495. dir.Load(source);
  1496. size_t fileNum;
  1497. if ( !SystemTools::MakeDirectory(destination) )
  1498. {
  1499. return false;
  1500. }
  1501. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1502. {
  1503. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1504. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1505. {
  1506. kwsys_stl::string fullPath = source;
  1507. fullPath += "/";
  1508. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1509. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  1510. {
  1511. kwsys_stl::string fullDestPath = destination;
  1512. fullDestPath += "/";
  1513. fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1514. if (!SystemTools::CopyADirectory(fullPath.c_str(), fullDestPath.c_str()))
  1515. {
  1516. return false;
  1517. }
  1518. }
  1519. else
  1520. {
  1521. if(!SystemTools::CopyFileAlways(fullPath.c_str(), destination))
  1522. {
  1523. return false;
  1524. }
  1525. }
  1526. }
  1527. }
  1528. return true;
  1529. }
  1530. // return size of file; also returns zero if no file exists
  1531. unsigned long SystemTools::FileLength(const char* filename)
  1532. {
  1533. struct stat fs;
  1534. if (stat(filename, &fs) != 0)
  1535. {
  1536. return 0;
  1537. }
  1538. else
  1539. {
  1540. return static_cast<unsigned long>(fs.st_size);
  1541. }
  1542. }
  1543. int SystemTools::Strucmp(const char *s1, const char *s2)
  1544. {
  1545. // lifted from Graphvis http://www.graphviz.org
  1546. while ((*s1 != '\0')
  1547. && (tolower(*s1) == tolower(*s2)))
  1548. {
  1549. s1++;
  1550. s2++;
  1551. }
  1552. return tolower(*s1) - tolower(*s2);
  1553. }
  1554. // return file's modified time
  1555. long int SystemTools::ModifiedTime(const char* filename)
  1556. {
  1557. struct stat fs;
  1558. if (stat(filename, &fs) != 0)
  1559. {
  1560. return 0;
  1561. }
  1562. else
  1563. {
  1564. return (long int)fs.st_mtime;
  1565. }
  1566. }
  1567. // return file's creation time
  1568. long int SystemTools::CreationTime(const char* filename)
  1569. {
  1570. struct stat fs;
  1571. if (stat(filename, &fs) != 0)
  1572. {
  1573. return 0;
  1574. }
  1575. else
  1576. {
  1577. return fs.st_ctime >= 0 ? (long int)fs.st_ctime : 0;
  1578. }
  1579. }
  1580. bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
  1581. {
  1582. if (!str || !tmt || strlen(str) < 12)
  1583. {
  1584. return false;
  1585. }
  1586. struct tm tmt2;
  1587. // __DATE__
  1588. // The compilation date of the current source file. The date is a string
  1589. // literal of the form Mmm dd yyyy. The month name Mmm is the same as for
  1590. // dates generated by the library function asctime declared in TIME.H.
  1591. // index: 012345678901
  1592. // format: Mmm dd yyyy
  1593. // example: Dec 19 2003
  1594. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  1595. char buffer[12];
  1596. strcpy(buffer, str);
  1597. buffer[3] = 0;
  1598. char *ptr = strstr(month_names, buffer);
  1599. if (!ptr)
  1600. {
  1601. return false;
  1602. }
  1603. int month = (ptr - month_names) / 3;
  1604. int day = atoi(buffer + 4);
  1605. int year = atoi(buffer + 7);
  1606. tmt2.tm_isdst = -1;
  1607. tmt2.tm_hour = 0;
  1608. tmt2.tm_min = 0;
  1609. tmt2.tm_sec = 0;
  1610. tmt2.tm_wday = 0;
  1611. tmt2.tm_yday = 0;
  1612. tmt2.tm_mday = day;
  1613. tmt2.tm_mon = month;
  1614. tmt2.tm_year = year - 1900;
  1615. *tmt = mktime(&tmt2);
  1616. return true;
  1617. }
  1618. bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
  1619. {
  1620. if (!str || !tmt || strlen(str) < 27)
  1621. {
  1622. return false;
  1623. }
  1624. struct tm tmt2;
  1625. // __TIMESTAMP__
  1626. // The date and time of the last modification of the current source file,
  1627. // expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy,
  1628. /// where Ddd is the abbreviated day of the week and Date is an integer
  1629. // from 1 to 31.
  1630. // index: 0123456789
  1631. // 0123456789
  1632. // 0123456789
  1633. // format: Ddd Mmm Date hh:mm:ss yyyy
  1634. // example: Fri Dec 19 14:34:58 2003
  1635. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  1636. char buffer[27];
  1637. strcpy(buffer, str);
  1638. buffer[7] = 0;
  1639. char *ptr = strstr(month_names, buffer + 4);
  1640. if (!ptr)
  1641. {
  1642. return false;
  1643. }
  1644. int month = (ptr - month_names) / 3;
  1645. int day = atoi(buffer + 8);
  1646. int hour = atoi(buffer + 11);
  1647. int min = atoi(buffer + 14);
  1648. int sec = atoi(buffer + 17);
  1649. int year = atoi(buffer + 20);
  1650. tmt2.tm_isdst = -1;
  1651. tmt2.tm_hour = hour;
  1652. tmt2.tm_min = min;
  1653. tmt2.tm_sec = sec;
  1654. tmt2.tm_wday = 0;
  1655. tmt2.tm_yday = 0;
  1656. tmt2.tm_mday = day;
  1657. tmt2.tm_mon = month;
  1658. tmt2.tm_year = year - 1900;
  1659. *tmt = mktime(&tmt2);
  1660. return true;
  1661. }
  1662. kwsys_stl::string SystemTools::GetLastSystemError()
  1663. {
  1664. int e = errno;
  1665. return strerror(e);
  1666. }
  1667. bool SystemTools::RemoveFile(const char* source)
  1668. {
  1669. #ifdef _WIN32
  1670. mode_t mode;
  1671. if ( !SystemTools::GetPermissions(source, mode) )
  1672. {
  1673. return false;
  1674. }
  1675. /* Win32 unlink is stupid --- it fails if the file is read-only */
  1676. SystemTools::SetPermissions(source, S_IWRITE);
  1677. #endif
  1678. bool res = unlink(source) != 0 ? false : true;
  1679. #ifdef _WIN32
  1680. if ( !res )
  1681. {
  1682. SystemTools::SetPermissions(source, mode);
  1683. }
  1684. #endif
  1685. return res;
  1686. }
  1687. bool SystemTools::RemoveADirectory(const char* source)
  1688. {
  1689. Directory dir;
  1690. dir.Load(source);
  1691. size_t fileNum;
  1692. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1693. {
  1694. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1695. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1696. {
  1697. kwsys_stl::string fullPath = source;
  1698. fullPath += "/";
  1699. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1700. if(SystemTools::FileIsDirectory(fullPath.c_str()) &&
  1701. !SystemTools::FileIsSymlink(fullPath.c_str()))
  1702. {
  1703. if (!SystemTools::RemoveADirectory(fullPath.c_str()))
  1704. {
  1705. return false;
  1706. }
  1707. }
  1708. else
  1709. {
  1710. if(!SystemTools::RemoveFile(fullPath.c_str()))
  1711. {
  1712. return false;
  1713. }
  1714. }
  1715. }
  1716. }
  1717. return (Rmdir(source) == 0);
  1718. }
  1719. /**
  1720. */
  1721. size_t SystemTools::GetMaximumFilePathLength()
  1722. {
  1723. return KWSYS_SYSTEMTOOLS_MAXPATH;
  1724. }
  1725. /**
  1726. * Find the file the given name. Searches the given path and then
  1727. * the system search path. Returns the full path to the file if it is
  1728. * found. Otherwise, the empty string is returned.
  1729. */
  1730. kwsys_stl::string SystemTools
  1731. ::FindName(const char* name,
  1732. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1733. bool no_system_path)
  1734. {
  1735. // Add the system search path to our path first
  1736. kwsys_stl::vector<kwsys_stl::string> path;
  1737. if (!no_system_path)
  1738. {
  1739. SystemTools::GetPath(path, "CMAKE_FILE_PATH");
  1740. SystemTools::GetPath(path);
  1741. }
  1742. // now add the additional paths
  1743. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
  1744. i != userPaths.end(); ++i)
  1745. {
  1746. path.push_back(*i);
  1747. }
  1748. // now look for the file
  1749. kwsys_stl::string tryPath;
  1750. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1751. p != path.end(); ++p)
  1752. {
  1753. tryPath = *p;
  1754. tryPath += "/";
  1755. tryPath += name;
  1756. if(SystemTools::FileExists(tryPath.c_str()))
  1757. {
  1758. return tryPath;
  1759. }
  1760. }
  1761. // Couldn't find the file.
  1762. return "";
  1763. }
  1764. /**
  1765. * Find the file the given name. Searches the given path and then
  1766. * the system search path. Returns the full path to the file if it is
  1767. * found. Otherwise, the empty string is returned.
  1768. */
  1769. kwsys_stl::string SystemTools
  1770. ::FindFile(const char* name,
  1771. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1772. bool no_system_path)
  1773. {
  1774. kwsys_stl::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
  1775. if(tryPath != "" && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1776. {
  1777. return SystemTools::CollapseFullPath(tryPath.c_str());
  1778. }
  1779. // Couldn't find the file.
  1780. return "";
  1781. }
  1782. /**
  1783. * Find the directory the given name. Searches the given path and then
  1784. * the system search path. Returns the full path to the directory if it is
  1785. * found. Otherwise, the empty string is returned.
  1786. */
  1787. kwsys_stl::string SystemTools
  1788. ::FindDirectory(const char* name,
  1789. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1790. bool no_system_path)
  1791. {
  1792. kwsys_stl::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
  1793. if(tryPath != "" && SystemTools::FileIsDirectory(tryPath.c_str()))
  1794. {
  1795. return SystemTools::CollapseFullPath(tryPath.c_str());
  1796. }
  1797. // Couldn't find the file.
  1798. return "";
  1799. }
  1800. /**
  1801. * Find the executable with the given name. Searches the given path and then
  1802. * the system search path. Returns the full path to the executable if it is
  1803. * found. Otherwise, the empty string is returned.
  1804. */
  1805. kwsys_stl::string SystemTools::FindProgram(
  1806. const char* nameIn,
  1807. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1808. bool no_system_path)
  1809. {
  1810. if(!nameIn || !*nameIn)
  1811. {
  1812. return "";
  1813. }
  1814. kwsys_stl::string name = nameIn;
  1815. kwsys_stl::vector<kwsys_stl::string> extensions;
  1816. #if defined (_WIN32) || defined(__CYGWIN__) | defined(__MINGW32__)
  1817. bool hasExtension = false;
  1818. // check to see if the name already has a .xxx at
  1819. // the end of it
  1820. if(name.size() > 3 && name[name.size()-4] == '.')
  1821. {
  1822. hasExtension = true;
  1823. }
  1824. // on windows try .com then .exe
  1825. if(!hasExtension)
  1826. {
  1827. extensions.push_back(".com");
  1828. extensions.push_back(".exe");
  1829. }
  1830. #endif
  1831. kwsys_stl::string tryPath;
  1832. // first try the name as it was given (adding extensions
  1833. // if needed.)
  1834. if(extensions.size())
  1835. {
  1836. for(kwsys_stl::vector<kwsys_stl::string>::iterator i =
  1837. extensions.begin(); i != extensions.end(); ++i)
  1838. {
  1839. tryPath = name;
  1840. tryPath += *i;
  1841. if(SystemTools::FileExists(tryPath.c_str()) &&
  1842. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1843. {
  1844. return SystemTools::CollapseFullPath(tryPath.c_str());
  1845. }
  1846. }
  1847. }
  1848. else
  1849. {
  1850. tryPath = name;
  1851. if(SystemTools::FileExists(tryPath.c_str()) &&
  1852. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1853. {
  1854. return SystemTools::CollapseFullPath(tryPath.c_str());
  1855. }
  1856. }
  1857. // now construct the path
  1858. kwsys_stl::vector<kwsys_stl::string> path;
  1859. // Add the system search path to our path.
  1860. if (!no_system_path)
  1861. {
  1862. SystemTools::GetPath(path);
  1863. }
  1864. // now add the additional paths
  1865. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i =
  1866. userPaths.begin(); i != userPaths.end(); ++i)
  1867. {
  1868. path.push_back(*i);
  1869. }
  1870. // Try each path
  1871. for(kwsys_stl::vector<kwsys_stl::string>::iterator p = path.begin();
  1872. p != path.end(); ++p)
  1873. {
  1874. #ifdef _WIN32
  1875. // Remove double quotes from the path on windows
  1876. SystemTools::ReplaceString(*p, "\"", "");
  1877. #endif
  1878. if(extensions.size())
  1879. {
  1880. for(kwsys_stl::vector<kwsys_stl::string>::iterator ext
  1881. = extensions.begin(); ext != extensions.end(); ++ext)
  1882. {
  1883. tryPath = *p;
  1884. tryPath += "/";
  1885. tryPath += name;
  1886. tryPath += *ext;
  1887. if(SystemTools::FileExists(tryPath.c_str()) &&
  1888. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1889. {
  1890. return SystemTools::CollapseFullPath(tryPath.c_str());
  1891. }
  1892. }
  1893. }
  1894. else
  1895. {
  1896. tryPath = *p;
  1897. tryPath += "/";
  1898. tryPath += name;
  1899. if(SystemTools::FileExists(tryPath.c_str()) &&
  1900. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1901. {
  1902. return SystemTools::CollapseFullPath(tryPath.c_str());
  1903. }
  1904. }
  1905. }
  1906. // Couldn't find the program.
  1907. return "";
  1908. }
  1909. kwsys_stl::string SystemTools::FindProgram(
  1910. const kwsys_stl::vector<kwsys_stl::string>& names,
  1911. const kwsys_stl::vector<kwsys_stl::string>& path,
  1912. bool noSystemPath)
  1913. {
  1914. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator it = names.begin();
  1915. it != names.end() ; ++it)
  1916. {
  1917. // Try to find the program.
  1918. kwsys_stl::string result = SystemTools::FindProgram(it->c_str(),
  1919. path,
  1920. noSystemPath);
  1921. if ( !result.empty() )
  1922. {
  1923. return result;
  1924. }
  1925. }
  1926. return "";
  1927. }
  1928. /**
  1929. * Find the library with the given name. Searches the given path and then
  1930. * the system search path. Returns the full path to the library if it is
  1931. * found. Otherwise, the empty string is returned.
  1932. */
  1933. kwsys_stl::string SystemTools
  1934. ::FindLibrary(const char* name,
  1935. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1936. {
  1937. // See if the executable exists as written.
  1938. if(SystemTools::FileExists(name) &&
  1939. !SystemTools::FileIsDirectory(name))
  1940. {
  1941. return SystemTools::CollapseFullPath(name);
  1942. }
  1943. // Add the system search path to our path.
  1944. kwsys_stl::vector<kwsys_stl::string> path;
  1945. SystemTools::GetPath(path);
  1946. // now add the additional paths
  1947. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
  1948. i != userPaths.end(); ++i)
  1949. {
  1950. path.push_back(*i);
  1951. }
  1952. kwsys_stl::string tryPath;
  1953. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1954. p != path.end(); ++p)
  1955. {
  1956. #if defined(__APPLE__)
  1957. tryPath = *p;
  1958. tryPath += "/";
  1959. tryPath += name;
  1960. tryPath += ".framework";
  1961. if(SystemTools::FileExists(tryPath.c_str())
  1962. && SystemTools::FileIsDirectory(tryPath.c_str()))
  1963. {
  1964. return SystemTools::CollapseFullPath(tryPath.c_str());
  1965. }
  1966. #endif
  1967. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
  1968. tryPath = *p;
  1969. tryPath += "/";
  1970. tryPath += name;
  1971. tryPath += ".lib";
  1972. if(SystemTools::FileExists(tryPath.c_str())
  1973. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1974. {
  1975. return SystemTools::CollapseFullPath(tryPath.c_str());
  1976. }
  1977. #else
  1978. tryPath = *p;
  1979. tryPath += "/lib";
  1980. tryPath += name;
  1981. tryPath += ".so";
  1982. if(SystemTools::FileExists(tryPath.c_str())
  1983. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1984. {
  1985. return SystemTools::CollapseFullPath(tryPath.c_str());
  1986. }
  1987. tryPath = *p;
  1988. tryPath += "/lib";
  1989. tryPath += name;
  1990. tryPath += ".a";
  1991. if(SystemTools::FileExists(tryPath.c_str())
  1992. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1993. {
  1994. return SystemTools::CollapseFullPath(tryPath.c_str());
  1995. }
  1996. tryPath = *p;
  1997. tryPath += "/lib";
  1998. tryPath += name;
  1999. tryPath += ".sl";
  2000. if(SystemTools::FileExists(tryPath.c_str())
  2001. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2002. {
  2003. return SystemTools::CollapseFullPath(tryPath.c_str());
  2004. }
  2005. tryPath = *p;
  2006. tryPath += "/lib";
  2007. tryPath += name;
  2008. tryPath += ".dylib";
  2009. if(SystemTools::FileExists(tryPath.c_str())
  2010. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2011. {
  2012. return SystemTools::CollapseFullPath(tryPath.c_str());
  2013. }
  2014. tryPath = *p;
  2015. tryPath += "/lib";
  2016. tryPath += name;
  2017. tryPath += ".dll";
  2018. if(SystemTools::FileExists(tryPath.c_str())
  2019. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2020. {
  2021. return SystemTools::CollapseFullPath(tryPath.c_str());
  2022. }
  2023. #endif
  2024. }
  2025. // Couldn't find the library.
  2026. return "";
  2027. }
  2028. bool SystemTools::FileIsDirectory(const char* name)
  2029. {
  2030. struct stat fs;
  2031. if(stat(name, &fs) == 0)
  2032. {
  2033. #if _WIN32
  2034. return ((fs.st_mode & _S_IFDIR) != 0);
  2035. #else
  2036. return S_ISDIR(fs.st_mode);
  2037. #endif
  2038. }
  2039. else
  2040. {
  2041. return false;
  2042. }
  2043. }
  2044. bool SystemTools::FileIsSymlink(const char* name)
  2045. {
  2046. #if _WIN32
  2047. (void)name;
  2048. return false;
  2049. #else
  2050. struct stat fs;
  2051. if(lstat(name, &fs) == 0)
  2052. {
  2053. return S_ISLNK(fs.st_mode);
  2054. }
  2055. else
  2056. {
  2057. return false;
  2058. }
  2059. #endif
  2060. }
  2061. int SystemTools::ChangeDirectory(const char *dir)
  2062. {
  2063. return Chdir(dir);
  2064. }
  2065. kwsys_stl::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
  2066. {
  2067. char buf[2048];
  2068. const char* cwd = Getcwd(buf, 2048);
  2069. kwsys_stl::string path;
  2070. if ( cwd )
  2071. {
  2072. path = cwd;
  2073. }
  2074. if(collapse)
  2075. {
  2076. return SystemTools::CollapseFullPath(path.c_str());
  2077. }
  2078. return path;
  2079. }
  2080. kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
  2081. {
  2082. kwsys_stl::string dir, file;
  2083. SystemTools::SplitProgramPath(in_name, dir, file);
  2084. return dir;
  2085. }
  2086. bool SystemTools::SplitProgramPath(const char* in_name,
  2087. kwsys_stl::string& dir,
  2088. kwsys_stl::string& file,
  2089. bool)
  2090. {
  2091. dir = in_name;
  2092. file = "";
  2093. SystemTools::ConvertToUnixSlashes(dir);
  2094. if(!SystemTools::FileIsDirectory(dir.c_str()))
  2095. {
  2096. kwsys_stl::string::size_type slashPos = dir.rfind("/");
  2097. if(slashPos != kwsys_stl::string::npos)
  2098. {
  2099. file = dir.substr(slashPos+1);
  2100. dir = dir.substr(0, slashPos);
  2101. }
  2102. else
  2103. {
  2104. file = dir;
  2105. dir = "";
  2106. }
  2107. }
  2108. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  2109. {
  2110. kwsys_stl::string oldDir = in_name;
  2111. SystemTools::ConvertToUnixSlashes(oldDir);
  2112. dir = in_name;
  2113. return false;
  2114. }
  2115. return true;
  2116. }
  2117. bool SystemTools::FindProgramPath(const char* argv0,
  2118. kwsys_stl::string& pathOut,
  2119. kwsys_stl::string& errorMsg,
  2120. const char* exeName,
  2121. const char* buildDir,
  2122. const char* installPrefix )
  2123. {
  2124. kwsys_stl::vector<kwsys_stl::string> failures;
  2125. kwsys_stl::string self = argv0 ? argv0 : "";
  2126. failures.push_back(self);
  2127. SystemTools::ConvertToUnixSlashes(self);
  2128. self = SystemTools::FindProgram(self.c_str());
  2129. if(!SystemTools::FileExists(self.c_str()))
  2130. {
  2131. if(buildDir)
  2132. {
  2133. kwsys_stl::string intdir = ".";
  2134. #ifdef CMAKE_INTDIR
  2135. intdir = CMAKE_INTDIR;
  2136. #endif
  2137. self = buildDir;
  2138. self += "/bin/";
  2139. self += intdir;
  2140. self += "/";
  2141. self += exeName;
  2142. self += SystemTools::GetExecutableExtension();
  2143. }
  2144. }
  2145. if(installPrefix)
  2146. {
  2147. if(!SystemTools::FileExists(self.c_str()))
  2148. {
  2149. failures.push_back(self);
  2150. self = installPrefix;
  2151. self += "/bin/";
  2152. self += exeName;
  2153. }
  2154. }
  2155. if(!SystemTools::FileExists(self.c_str()))
  2156. {
  2157. failures.push_back(self);
  2158. kwsys_ios::ostringstream msg;
  2159. msg << "Can not find the command line program ";
  2160. if (exeName)
  2161. {
  2162. msg << exeName;
  2163. }
  2164. msg << "\n";
  2165. if (argv0)
  2166. {
  2167. msg << " argv[0] = \"" << argv0 << "\"\n";
  2168. }
  2169. msg << " Attempted paths:\n";
  2170. kwsys_stl::vector<kwsys_stl::string>::iterator i;
  2171. for(i=failures.begin(); i != failures.end(); ++i)
  2172. {
  2173. msg << " \"" << i->c_str() << "\"\n";
  2174. }
  2175. errorMsg = msg.str();
  2176. return false;
  2177. }
  2178. pathOut = self;
  2179. return true;
  2180. }
  2181. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
  2182. {
  2183. return SystemTools::CollapseFullPath(in_relative, 0);
  2184. }
  2185. void SystemTools::AddTranslationPath(const char * a, const char * b)
  2186. {
  2187. kwsys_stl::string path_a = a;
  2188. kwsys_stl::string path_b = b;
  2189. SystemTools::ConvertToUnixSlashes(path_a);
  2190. SystemTools::ConvertToUnixSlashes(path_b);
  2191. // First check this is a directory path, since we don't want the table to
  2192. // grow too fat
  2193. if( SystemTools::FileIsDirectory( path_a.c_str() ) )
  2194. {
  2195. // Make sure the path is a full path and does not contain no '..'
  2196. if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
  2197. == kwsys_stl::string::npos )
  2198. {
  2199. // Before inserting make sure path ends with '/'
  2200. if(path_a.size() && path_a[path_a.size() -1] != '/')
  2201. {
  2202. path_a += '/';
  2203. }
  2204. if(path_b.size() && path_b[path_b.size() -1] != '/')
  2205. {
  2206. path_b += '/';
  2207. }
  2208. if( !(path_a == path_b) )
  2209. {
  2210. SystemTools::TranslationMap->insert(
  2211. SystemToolsTranslationMap::value_type(path_a, path_b));
  2212. }
  2213. }
  2214. }
  2215. }
  2216. void SystemTools::AddKeepPath(const char* dir)
  2217. {
  2218. kwsys_stl::string cdir = SystemTools::CollapseFullPath(dir);
  2219. SystemTools::AddTranslationPath(cdir.c_str(), dir);
  2220. }
  2221. void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
  2222. {
  2223. // Do not translate paths that are too short to have meaningful
  2224. // translations.
  2225. if(path.size() < 2)
  2226. {
  2227. return;
  2228. }
  2229. // Always add a trailing slash before translation. It does not
  2230. // matter if this adds an extra slash, but we do not want to
  2231. // translate part of a directory (like the foo part of foo-dir).
  2232. path += "/";
  2233. // In case a file was specified we still have to go through this:
  2234. // Now convert any path found in the table back to the one desired:
  2235. kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
  2236. for(it = SystemTools::TranslationMap->begin();
  2237. it != SystemTools::TranslationMap->end();
  2238. ++it )
  2239. {
  2240. // We need to check of the path is a substring of the other path
  2241. if(path.find( it->first ) == 0)
  2242. {
  2243. path = path.replace( 0, it->first.size(), it->second);
  2244. }
  2245. }
  2246. // Remove the trailing slash we added before.
  2247. path.erase(path.end()-1, path.end());
  2248. }
  2249. void
  2250. SystemToolsAppendComponents(
  2251. kwsys_stl::vector<kwsys_stl::string>& out_components,
  2252. kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
  2253. kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
  2254. {
  2255. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = first;
  2256. i != last; ++i)
  2257. {
  2258. if(*i == "..")
  2259. {
  2260. if(out_components.begin() != out_components.end())
  2261. {
  2262. out_components.erase(out_components.end()-1, out_components.end());
  2263. }
  2264. }
  2265. else if(!(*i == ".") && !(*i == ""))
  2266. {
  2267. out_components.push_back(*i);
  2268. }
  2269. }
  2270. }
  2271. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_path,
  2272. const char* in_base)
  2273. {
  2274. // Collect the output path components.
  2275. kwsys_stl::vector<kwsys_stl::string> out_components;
  2276. // Split the input path components.
  2277. kwsys_stl::vector<kwsys_stl::string> path_components;
  2278. SystemTools::SplitPath(in_path, path_components);
  2279. // If the input path is relative, start with a base path.
  2280. if(path_components[0].length() == 0)
  2281. {
  2282. kwsys_stl::vector<kwsys_stl::string> base_components;
  2283. if(in_base)
  2284. {
  2285. // Use the given base path.
  2286. SystemTools::SplitPath(in_base, base_components);
  2287. }
  2288. else
  2289. {
  2290. // Use the current working directory as a base path.
  2291. char buf[2048];
  2292. if(const char* cwd = Getcwd(buf, 2048))
  2293. {
  2294. SystemTools::SplitPath(cwd, base_components);
  2295. }
  2296. else
  2297. {
  2298. // ??
  2299. }
  2300. }
  2301. // Append base path components to the output path.
  2302. out_components.push_back(base_components[0]);
  2303. SystemToolsAppendComponents(out_components,
  2304. base_components.begin()+1,
  2305. base_components.end());
  2306. }
  2307. // Append input path components to the output path.
  2308. SystemToolsAppendComponents(out_components,
  2309. path_components.begin(),
  2310. path_components.end());
  2311. // Transform the path back to a string.
  2312. kwsys_stl::string newPath = SystemTools::JoinPath(out_components);
  2313. // Update the translation table with this potentially new path.
  2314. SystemTools::AddTranslationPath(newPath.c_str(), in_path);
  2315. SystemTools::CheckTranslationPath(newPath);
  2316. #ifdef _WIN32
  2317. newPath = SystemTools::GetActualCaseForPath(newPath.c_str());
  2318. SystemTools::ConvertToUnixSlashes(newPath);
  2319. #endif
  2320. // Return the reconstructed path.
  2321. return newPath;
  2322. }
  2323. // compute the relative path from here to there
  2324. kwsys_stl::string SystemTools::RelativePath(const char* local, const char* remote)
  2325. {
  2326. if(!SystemTools::FileIsFullPath(local))
  2327. {
  2328. return "";
  2329. }
  2330. if(!SystemTools::FileIsFullPath(remote))
  2331. {
  2332. return "";
  2333. }
  2334. // split up both paths into arrays of strings using / as a separator
  2335. kwsys_stl::vector<kwsys::String> localSplit = SystemTools::SplitString(local, '/', true);
  2336. kwsys_stl::vector<kwsys::String> remoteSplit = SystemTools::SplitString(remote, '/', true);
  2337. kwsys_stl::vector<kwsys::String> commonPath; // store shared parts of path in this array
  2338. kwsys_stl::vector<kwsys::String> finalPath; // store the final relative path here
  2339. // count up how many matching directory names there are from the start
  2340. unsigned int sameCount = 0;
  2341. while(
  2342. ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1)))
  2343. &&
  2344. // for windows and apple do a case insensitive string compare
  2345. #if defined(_WIN32) || defined(__APPLE__)
  2346. SystemTools::Strucmp(localSplit[sameCount].c_str(),
  2347. remoteSplit[sameCount].c_str()) == 0
  2348. #else
  2349. localSplit[sameCount] == remoteSplit[sameCount]
  2350. #endif
  2351. )
  2352. {
  2353. // put the common parts of the path into the commonPath array
  2354. commonPath.push_back(localSplit[sameCount]);
  2355. // erase the common parts of the path from the original path arrays
  2356. localSplit[sameCount] = "";
  2357. remoteSplit[sameCount] = "";
  2358. sameCount++;
  2359. }
  2360. // If there is nothing in common but the root directory, then just
  2361. // return the full path.
  2362. if(sameCount <= 1)
  2363. {
  2364. return remote;
  2365. }
  2366. // for each entry that is not common in the local path
  2367. // add a ../ to the finalpath array, this gets us out of the local
  2368. // path into the remote dir
  2369. for(unsigned int i = 0; i < localSplit.size(); ++i)
  2370. {
  2371. if(localSplit[i].size())
  2372. {
  2373. finalPath.push_back("../");
  2374. }
  2375. }
  2376. // for each entry that is not common in the remote path add it
  2377. // to the final path.
  2378. for(kwsys_stl::vector<String>::iterator vit = remoteSplit.begin();
  2379. vit != remoteSplit.end(); ++vit)
  2380. {
  2381. if(vit->size())
  2382. {
  2383. finalPath.push_back(*vit);
  2384. }
  2385. }
  2386. kwsys_stl::string relativePath; // result string
  2387. // now turn the array of directories into a unix path by puttint /
  2388. // between each entry that does not already have one
  2389. for(kwsys_stl::vector<String>::iterator vit1 = finalPath.begin();
  2390. vit1 != finalPath.end(); ++vit1)
  2391. {
  2392. if(relativePath.size() && relativePath[relativePath.size()-1] != '/')
  2393. {
  2394. relativePath += "/";
  2395. }
  2396. relativePath += *vit1;
  2397. }
  2398. return relativePath;
  2399. }
  2400. // OK, some fun stuff to get the actual case of a given path.
  2401. // Basically, you just need to call ShortPath, then GetLongPathName,
  2402. // However, GetLongPathName is not implemented on windows NT and 95,
  2403. // so we have to simulate it on those versions
  2404. #ifdef _WIN32
  2405. int OldWindowsGetLongPath(kwsys_stl::string const& shortPath,
  2406. kwsys_stl::string& longPath )
  2407. {
  2408. kwsys_stl::string::size_type iFound = shortPath.rfind('/');
  2409. if (iFound > 1 && iFound != shortPath.npos)
  2410. {
  2411. // recurse to peel off components
  2412. //
  2413. if (OldWindowsGetLongPath(shortPath.substr(0, iFound), longPath) > 0)
  2414. {
  2415. longPath += '/';
  2416. if (shortPath[1] != '/')
  2417. {
  2418. WIN32_FIND_DATA findData;
  2419. // append the long component name to the path
  2420. //
  2421. if (INVALID_HANDLE_VALUE != ::FindFirstFile
  2422. (shortPath.c_str(), &findData))
  2423. {
  2424. longPath += findData.cFileName;
  2425. }
  2426. else
  2427. {
  2428. // if FindFirstFile fails, return the error code
  2429. //
  2430. longPath = "";
  2431. return 0;
  2432. }
  2433. }
  2434. }
  2435. }
  2436. else
  2437. {
  2438. longPath = shortPath;
  2439. }
  2440. return (int)longPath.size();
  2441. }
  2442. int PortableGetLongPathName(const char* pathIn,
  2443. kwsys_stl::string & longPath)
  2444. {
  2445. HMODULE lh = LoadLibrary("Kernel32.dll");
  2446. if(lh)
  2447. {
  2448. FARPROC proc = GetProcAddress(lh, "GetLongPathNameA");
  2449. if(proc)
  2450. {
  2451. typedef DWORD (WINAPI * GetLongFunctionPtr) (LPCSTR,LPSTR,DWORD);
  2452. GetLongFunctionPtr func = (GetLongFunctionPtr)proc;
  2453. char buffer[MAX_PATH+1];
  2454. int len = (*func)(pathIn, buffer, MAX_PATH+1);
  2455. if(len == 0 || len > MAX_PATH+1)
  2456. {
  2457. FreeLibrary(lh);
  2458. return 0;
  2459. }
  2460. longPath = buffer;
  2461. FreeLibrary(lh);
  2462. return len;
  2463. }
  2464. FreeLibrary(lh);
  2465. }
  2466. return OldWindowsGetLongPath(pathIn, longPath);
  2467. }
  2468. #endif
  2469. //----------------------------------------------------------------------------
  2470. kwsys_stl::string SystemTools::GetActualCaseForPath(const char* p)
  2471. {
  2472. #ifndef _WIN32
  2473. return p;
  2474. #else
  2475. kwsys_stl::string shortPath;
  2476. if(!SystemTools::GetShortPath(p, shortPath))
  2477. {
  2478. return p;
  2479. }
  2480. kwsys_stl::string longPath;
  2481. int len = PortableGetLongPathName(shortPath.c_str(), longPath);
  2482. if(len == 0 || len > MAX_PATH+1)
  2483. {
  2484. return p;
  2485. }
  2486. return longPath;
  2487. #endif
  2488. }
  2489. //----------------------------------------------------------------------------
  2490. void SystemTools::SplitPath(const char* p,
  2491. kwsys_stl::vector<kwsys_stl::string>& components)
  2492. {
  2493. components.clear();
  2494. // Identify the root component.
  2495. const char* c = p;
  2496. if((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\'))
  2497. {
  2498. // Network path.
  2499. components.push_back("//");
  2500. c += 2;
  2501. }
  2502. else if(c[0] == '/')
  2503. {
  2504. // Unix path.
  2505. components.push_back("/");
  2506. c += 1;
  2507. }
  2508. else if(c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\'))
  2509. {
  2510. // Windows path.
  2511. kwsys_stl::string root = "_:/";
  2512. root[0] = c[0];
  2513. components.push_back(root);
  2514. c += 3;
  2515. }
  2516. else if(c[0] && c[1] == ':')
  2517. {
  2518. // Path relative to a windows drive working directory.
  2519. kwsys_stl::string root = "_:";
  2520. root[0] = c[0];
  2521. components.push_back(root);
  2522. c += 2;
  2523. }
  2524. else
  2525. {
  2526. // Relative path.
  2527. components.push_back("");
  2528. }
  2529. // Parse the remaining components.
  2530. const char* first = c;
  2531. const char* last = first;
  2532. for(;*last; ++last)
  2533. {
  2534. if(*last == '/' || *last == '\\')
  2535. {
  2536. // End of a component. Save it.
  2537. components.push_back(kwsys_stl::string(first, last-first));
  2538. first = last+1;
  2539. }
  2540. }
  2541. // Save the last component unless there were no components.
  2542. if(last != c)
  2543. {
  2544. components.push_back(kwsys_stl::string(first, last-first));
  2545. }
  2546. }
  2547. //----------------------------------------------------------------------------
  2548. kwsys_stl::string
  2549. SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components)
  2550. {
  2551. kwsys_stl::string result;
  2552. if(components.size() > 0)
  2553. {
  2554. result += components[0];
  2555. }
  2556. if(components.size() > 1)
  2557. {
  2558. result += components[1];
  2559. }
  2560. for(unsigned int i=2; i < components.size(); ++i)
  2561. {
  2562. result += "/";
  2563. result += components[i];
  2564. }
  2565. return result;
  2566. }
  2567. //----------------------------------------------------------------------------
  2568. bool SystemTools::ComparePath(const char* c1, const char* c2)
  2569. {
  2570. #if defined(_WIN32) || defined(__APPLE__)
  2571. # ifdef _MSC_VER
  2572. return _stricmp(c1, c2) == 0;
  2573. # elif defined(__APPLE__) || defined(__GNUC__)
  2574. return strcasecmp(c1, c2) == 0;
  2575. #else
  2576. return SystemTools::Strucmp(c1, c2) == 0;
  2577. # endif
  2578. #else
  2579. return strcmp(c1, c2) == 0;
  2580. #endif
  2581. }
  2582. //----------------------------------------------------------------------------
  2583. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines, char separator)
  2584. {
  2585. kwsys_stl::string data(str);
  2586. kwsys_stl::string::size_type lpos = 0;
  2587. while(lpos < data.length())
  2588. {
  2589. kwsys_stl::string::size_type rpos = data.find_first_of(separator, lpos);
  2590. if(rpos == kwsys_stl::string::npos)
  2591. {
  2592. // Line ends at end of string without a newline.
  2593. lines.push_back(data.substr(lpos));
  2594. return false;
  2595. }
  2596. else
  2597. {
  2598. // Line ends in a "\n", remove the character.
  2599. lines.push_back(data.substr(lpos, rpos-lpos));
  2600. }
  2601. lpos = rpos+1;
  2602. }
  2603. return true;
  2604. }
  2605. //----------------------------------------------------------------------------
  2606. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
  2607. {
  2608. kwsys_stl::string data(str);
  2609. kwsys_stl::string::size_type lpos = 0;
  2610. while(lpos < data.length())
  2611. {
  2612. kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
  2613. if(rpos == kwsys_stl::string::npos)
  2614. {
  2615. // Line ends at end of string without a newline.
  2616. lines.push_back(data.substr(lpos));
  2617. return false;
  2618. }
  2619. if((rpos > lpos) && (data[rpos-1] == '\r'))
  2620. {
  2621. // Line ends in a "\r\n" pair, remove both characters.
  2622. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  2623. }
  2624. else
  2625. {
  2626. // Line ends in a "\n", remove the character.
  2627. lines.push_back(data.substr(lpos, rpos-lpos));
  2628. }
  2629. lpos = rpos+1;
  2630. }
  2631. return true;
  2632. }
  2633. /**
  2634. * Return path of a full filename (no trailing slashes).
  2635. * Warning: returned path is converted to Unix slashes format.
  2636. */
  2637. kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
  2638. {
  2639. kwsys_stl::string fn = filename;
  2640. SystemTools::ConvertToUnixSlashes(fn);
  2641. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  2642. if(slash_pos != kwsys_stl::string::npos)
  2643. {
  2644. return fn.substr(0, slash_pos);
  2645. }
  2646. else
  2647. {
  2648. return "";
  2649. }
  2650. }
  2651. /**
  2652. * Return file name of a full filename (i.e. file name without path).
  2653. */
  2654. kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
  2655. {
  2656. #if defined(_WIN32)
  2657. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/\\");
  2658. #else
  2659. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/");
  2660. #endif
  2661. if(slash_pos != kwsys_stl::string::npos)
  2662. {
  2663. return filename.substr(slash_pos + 1);
  2664. }
  2665. else
  2666. {
  2667. return filename;
  2668. }
  2669. }
  2670. /**
  2671. * Return file extension of a full filename (dot included).
  2672. * Warning: this is the longest extension (for example: .tar.gz)
  2673. */
  2674. kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
  2675. {
  2676. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2677. kwsys_stl::string::size_type dot_pos = name.find(".");
  2678. if(dot_pos != kwsys_stl::string::npos)
  2679. {
  2680. return name.substr(dot_pos);
  2681. }
  2682. else
  2683. {
  2684. return "";
  2685. }
  2686. }
  2687. /**
  2688. * Return file extension of a full filename (dot included).
  2689. * Warning: this is the shortest extension (for example: .tar.gz)
  2690. */
  2691. kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
  2692. {
  2693. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2694. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2695. if(dot_pos != kwsys_stl::string::npos)
  2696. {
  2697. return name.substr(dot_pos);
  2698. }
  2699. else
  2700. {
  2701. return "";
  2702. }
  2703. }
  2704. /**
  2705. * Return file name without extension of a full filename (i.e. without path).
  2706. * Warning: it considers the longest extension (for example: .tar.gz)
  2707. */
  2708. kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
  2709. {
  2710. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2711. kwsys_stl::string::size_type dot_pos = name.find(".");
  2712. if(dot_pos != kwsys_stl::string::npos)
  2713. {
  2714. return name.substr(0, dot_pos);
  2715. }
  2716. else
  2717. {
  2718. return name;
  2719. }
  2720. }
  2721. /**
  2722. * Return file name without extension of a full filename (i.e. without path).
  2723. * Warning: it considers the last extension (for example: removes .gz
  2724. * from .tar.gz)
  2725. */
  2726. kwsys_stl::string
  2727. SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
  2728. {
  2729. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2730. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2731. if(dot_pos != kwsys_stl::string::npos)
  2732. {
  2733. return name.substr(0, dot_pos);
  2734. }
  2735. else
  2736. {
  2737. return name;
  2738. }
  2739. }
  2740. bool SystemTools::FileHasSignature(const char *filename,
  2741. const char *signature,
  2742. long offset)
  2743. {
  2744. if (!filename || !signature)
  2745. {
  2746. return false;
  2747. }
  2748. FILE *fp;
  2749. fp = fopen(filename, "rb");
  2750. if (!fp)
  2751. {
  2752. return false;
  2753. }
  2754. fseek(fp, offset, SEEK_SET);
  2755. bool res = false;
  2756. size_t signature_len = strlen(signature);
  2757. char *buffer = new char [signature_len];
  2758. if (fread(buffer, 1, signature_len, fp) == signature_len)
  2759. {
  2760. res = (!strncmp(buffer, signature, signature_len) ? true : false);
  2761. }
  2762. delete [] buffer;
  2763. fclose(fp);
  2764. return res;
  2765. }
  2766. SystemTools::FileTypeEnum
  2767. SystemTools::DetectFileType(const char *filename,
  2768. unsigned long length,
  2769. double percent_bin)
  2770. {
  2771. if (!filename || percent_bin < 0)
  2772. {
  2773. return SystemTools::FileTypeUnknown;
  2774. }
  2775. FILE *fp;
  2776. fp = fopen(filename, "rb");
  2777. if (!fp)
  2778. {
  2779. return SystemTools::FileTypeUnknown;
  2780. }
  2781. // Allocate buffer and read bytes
  2782. unsigned char *buffer = new unsigned char [length];
  2783. size_t read_length = fread(buffer, 1, length, fp);
  2784. fclose(fp);
  2785. if (read_length == 0)
  2786. {
  2787. return SystemTools::FileTypeUnknown;
  2788. }
  2789. // Loop over contents and count
  2790. size_t text_count = 0;
  2791. const unsigned char *ptr = buffer;
  2792. const unsigned char *buffer_end = buffer + read_length;
  2793. while (ptr != buffer_end)
  2794. {
  2795. if ((*ptr >= 0x20 && *ptr <= 0x7F) ||
  2796. *ptr == '\n' ||
  2797. *ptr == '\r' ||
  2798. *ptr == '\t')
  2799. {
  2800. text_count++;
  2801. }
  2802. ptr++;
  2803. }
  2804. delete [] buffer;
  2805. double current_percent_bin =
  2806. ((double)(read_length - text_count) / (double)read_length);
  2807. if (current_percent_bin >= percent_bin)
  2808. {
  2809. return SystemTools::FileTypeBinary;
  2810. }
  2811. return SystemTools::FileTypeText;
  2812. }
  2813. bool SystemTools::LocateFileInDir(const char *filename,
  2814. const char *dir,
  2815. kwsys_stl::string& filename_found,
  2816. int try_filename_dirs)
  2817. {
  2818. if (!filename || !dir)
  2819. {
  2820. return false;
  2821. }
  2822. // Get the basename of 'filename'
  2823. kwsys_stl::string filename_base = SystemTools::GetFilenameName(filename);
  2824. // Check if 'dir' is really a directory
  2825. // If win32 and matches something like C:, accept it as a dir
  2826. kwsys_stl::string real_dir;
  2827. if (!SystemTools::FileIsDirectory(dir))
  2828. {
  2829. #if _WIN32
  2830. size_t dir_len = strlen(dir);
  2831. if (dir_len < 2 || dir[dir_len - 1] != ':')
  2832. {
  2833. #endif
  2834. real_dir = SystemTools::GetFilenamePath(dir);
  2835. dir = real_dir.c_str();
  2836. #if _WIN32
  2837. }
  2838. #endif
  2839. }
  2840. // Try to find the file in 'dir'
  2841. bool res = false;
  2842. if (filename_base.size() && dir)
  2843. {
  2844. size_t dir_len = strlen(dir);
  2845. int need_slash =
  2846. (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
  2847. kwsys_stl::string temp = dir;
  2848. if (need_slash)
  2849. {
  2850. temp += "/";
  2851. }
  2852. temp += filename_base;
  2853. if (SystemTools::FileExists(filename_found.c_str()))
  2854. {
  2855. res = true;
  2856. filename_found = temp;
  2857. }
  2858. // If not found, we can try harder by appending part of the file to
  2859. // to the directory to look inside.
  2860. // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
  2861. // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
  2862. else if (try_filename_dirs)
  2863. {
  2864. kwsys_stl::string filename_dir(filename);
  2865. kwsys_stl::string filename_dir_base;
  2866. kwsys_stl::string filename_dir_bases;
  2867. do
  2868. {
  2869. filename_dir = SystemTools::GetFilenamePath(filename_dir);
  2870. filename_dir_base = SystemTools::GetFilenameName(filename_dir);
  2871. #if _WIN32
  2872. if (!filename_dir_base.size() ||
  2873. filename_dir_base[filename_dir_base.size() - 1] == ':')
  2874. #else
  2875. if (!filename_dir_base.size())
  2876. #endif
  2877. {
  2878. break;
  2879. }
  2880. filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
  2881. temp = dir;
  2882. if (need_slash)
  2883. {
  2884. temp += "/";
  2885. }
  2886. temp += filename_dir_bases;
  2887. res = SystemTools::LocateFileInDir(
  2888. filename_base.c_str(), temp.c_str(), filename_found, 0);
  2889. } while (!res && filename_dir_base.size());
  2890. }
  2891. }
  2892. return res;
  2893. }
  2894. bool SystemTools::FileIsFullPath(const char* in_name)
  2895. {
  2896. kwsys_stl::string name = in_name;
  2897. #if defined(_WIN32) || defined(__CYGWIN__)
  2898. // On Windows, the name must be at least two characters long.
  2899. if(name.length() < 2)
  2900. {
  2901. return false;
  2902. }
  2903. if(name[1] == ':')
  2904. {
  2905. return true;
  2906. }
  2907. if(name[0] == '\\')
  2908. {
  2909. return true;
  2910. }
  2911. #else
  2912. // On UNIX, the name must be at least one character long.
  2913. if(name.length() < 1)
  2914. {
  2915. return false;
  2916. }
  2917. #endif
  2918. // On UNIX, the name must begin in a '/'.
  2919. // On Windows, if the name begins in a '/', then it is a full
  2920. // network path.
  2921. if(name[0] == '/')
  2922. {
  2923. return true;
  2924. }
  2925. return false;
  2926. }
  2927. bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
  2928. {
  2929. #if defined(WIN32) && !defined(__CYGWIN__)
  2930. const int size = int(strlen(path)) +1; // size of return
  2931. char *buffer = new char[size]; // create a buffer
  2932. char *tempPath = new char[size]; // create a buffer
  2933. int ret;
  2934. // if the path passed in has quotes around it, first remove the quotes
  2935. if (path[0] == '"' && path[strlen(path)-1] == '"')
  2936. {
  2937. strcpy(tempPath,path+1);
  2938. tempPath[strlen(tempPath)-1] = '\0';
  2939. }
  2940. else
  2941. {
  2942. strcpy(tempPath,path);
  2943. }
  2944. buffer[0] = 0;
  2945. ret = GetShortPathName(tempPath, buffer, size);
  2946. if(buffer[0] == 0 || ret > size)
  2947. {
  2948. delete [] buffer;
  2949. delete [] tempPath;
  2950. return false;
  2951. }
  2952. else
  2953. {
  2954. shortPath = buffer;
  2955. delete [] buffer;
  2956. delete [] tempPath;
  2957. return true;
  2958. }
  2959. #else
  2960. shortPath = path;
  2961. return true;
  2962. #endif
  2963. }
  2964. void SystemTools::SplitProgramFromArgs(const char* path,
  2965. kwsys_stl::string& program, kwsys_stl::string& args)
  2966. {
  2967. // see if this is a full path to a program
  2968. // if so then set program to path and args to nothing
  2969. if(SystemTools::FileExists(path))
  2970. {
  2971. program = path;
  2972. args = "";
  2973. return;
  2974. }
  2975. // Try to find the program in the path, note the program
  2976. // may have spaces in its name so we have to look for it
  2977. kwsys_stl::vector<kwsys_stl::string> e;
  2978. kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
  2979. if(findProg.size())
  2980. {
  2981. program = findProg;
  2982. args = "";
  2983. return;
  2984. }
  2985. // Now try and peel off space separated chunks from the end of the string
  2986. // so the largest path possible is found allowing for spaces in the path
  2987. kwsys_stl::string dir = path;
  2988. kwsys_stl::string::size_type spacePos = dir.rfind(' ');
  2989. while(spacePos != kwsys_stl::string::npos)
  2990. {
  2991. kwsys_stl::string tryProg = dir.substr(0, spacePos);
  2992. // See if the file exists
  2993. if(SystemTools::FileExists(tryProg.c_str()))
  2994. {
  2995. program = tryProg;
  2996. // remove trailing spaces from program
  2997. kwsys_stl::string::size_type pos = program.size()-1;
  2998. while(program[pos] == ' ')
  2999. {
  3000. program.erase(pos);
  3001. pos--;
  3002. }
  3003. args = dir.substr(spacePos, dir.size()-spacePos);
  3004. return;
  3005. }
  3006. // Now try and find the the program in the path
  3007. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  3008. if(findProg.size())
  3009. {
  3010. program = findProg;
  3011. // remove trailing spaces from program
  3012. kwsys_stl::string::size_type pos = program.size()-1;
  3013. while(program[pos] == ' ')
  3014. {
  3015. program.erase(pos);
  3016. pos--;
  3017. }
  3018. args = dir.substr(spacePos, dir.size()-spacePos);
  3019. return;
  3020. }
  3021. // move past the space for the next search
  3022. spacePos--;
  3023. spacePos = dir.rfind(' ', spacePos);
  3024. }
  3025. program = "";
  3026. args = "";
  3027. }
  3028. kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
  3029. {
  3030. char buf[1024];
  3031. time_t t;
  3032. time(&t);
  3033. strftime(buf, sizeof(buf), format, localtime(&t));
  3034. return buf;
  3035. }
  3036. kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
  3037. {
  3038. kwsys_stl::string str(s);
  3039. if (str.find_first_of("0123456789") == 0)
  3040. {
  3041. str = "_" + str;
  3042. }
  3043. kwsys_stl::string permited_chars("_"
  3044. "abcdefghijklmnopqrstuvwxyz"
  3045. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3046. "0123456789");
  3047. kwsys_stl::string::size_type pos = 0;
  3048. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
  3049. {
  3050. str[pos] = '_';
  3051. }
  3052. return str;
  3053. }
  3054. // Due to a buggy stream library on the HP and another on Mac OSX, we
  3055. // need this very carefully written version of getline. Returns true
  3056. // if any data were read before the end-of-file was reached.
  3057. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, kwsys_stl::string& line,
  3058. bool *has_newline /* = 0 */)
  3059. {
  3060. const int bufferSize = 1024;
  3061. char buffer[bufferSize];
  3062. line = "";
  3063. bool haveData = false;
  3064. if ( has_newline )
  3065. {
  3066. *has_newline = false;
  3067. }
  3068. // If no characters are read from the stream, the end of file has
  3069. // been reached.
  3070. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  3071. {
  3072. haveData = true;
  3073. line.append(buffer);
  3074. // If newline character was read, the gcount includes the
  3075. // character, but the buffer does not. The end of line has been
  3076. // reached.
  3077. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  3078. {
  3079. if ( has_newline )
  3080. {
  3081. *has_newline = true;
  3082. }
  3083. break;
  3084. }
  3085. // The fail bit may be set. Clear it.
  3086. is.clear(is.rdstate() & ~kwsys_ios::ios::failbit);
  3087. }
  3088. return haveData;
  3089. }
  3090. int SystemTools::GetTerminalWidth()
  3091. {
  3092. int width = -1;
  3093. #ifndef _WIN32
  3094. struct winsize ws;
  3095. char *columns; /* Unix98 environment variable */
  3096. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  3097. {
  3098. width = ws.ws_col;
  3099. }
  3100. if(!isatty(STDOUT_FILENO))
  3101. {
  3102. width = -1;
  3103. }
  3104. columns = getenv("COLUMNS");
  3105. if(columns && *columns)
  3106. {
  3107. long t;
  3108. char *endptr;
  3109. t = strtol(columns, &endptr, 0);
  3110. if(endptr && !*endptr && (t>0) && (t<1000))
  3111. {
  3112. width = (int)t;
  3113. }
  3114. }
  3115. if ( width < 9 )
  3116. {
  3117. width = -1;
  3118. }
  3119. #endif
  3120. return width;
  3121. }
  3122. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  3123. {
  3124. if ( !file )
  3125. {
  3126. return false;
  3127. }
  3128. struct stat st;
  3129. if ( stat(file, &st) < 0 )
  3130. {
  3131. return false;
  3132. }
  3133. mode = st.st_mode;
  3134. return true;
  3135. }
  3136. bool SystemTools::SetPermissions(const char* file, mode_t mode)
  3137. {
  3138. if ( !file )
  3139. {
  3140. return false;
  3141. }
  3142. if ( !SystemTools::FileExists(file) )
  3143. {
  3144. return false;
  3145. }
  3146. if ( chmod(file, mode) < 0 )
  3147. {
  3148. return false;
  3149. }
  3150. return true;
  3151. }
  3152. kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
  3153. {
  3154. if ( !fileOrDir || !*fileOrDir )
  3155. {
  3156. return "";
  3157. }
  3158. kwsys_stl::string res = fileOrDir;
  3159. SystemTools::ConvertToUnixSlashes(res);
  3160. kwsys_stl::string::size_type cc = res.size()-1;
  3161. if ( res[cc] == '/' )
  3162. {
  3163. cc --;
  3164. }
  3165. for ( ; cc > 0; cc -- )
  3166. {
  3167. if ( res[cc] == '/' )
  3168. {
  3169. break;
  3170. }
  3171. }
  3172. return res.substr(0, cc);
  3173. }
  3174. bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
  3175. {
  3176. kwsys_stl::string subdir = cSubdir;
  3177. kwsys_stl::string dir = cDir;
  3178. SystemTools::ConvertToUnixSlashes(dir);
  3179. kwsys_stl::string path = subdir;
  3180. do
  3181. {
  3182. path = SystemTools::GetParentDirectory(path.c_str());
  3183. if(SystemTools::ComparePath(dir.c_str(), path.c_str()))
  3184. {
  3185. return true;
  3186. }
  3187. }
  3188. while ( path.size() > dir.size() );
  3189. return false;
  3190. }
  3191. kwsys_stl::string SystemTools::FileExistsInParentDirectories(const char* fname,
  3192. const char* directory, const char* toplevel)
  3193. {
  3194. kwsys_stl::string file = fname;
  3195. SystemTools::ConvertToUnixSlashes(file);
  3196. kwsys_stl::string dir = directory;
  3197. SystemTools::ConvertToUnixSlashes(dir);
  3198. while ( !dir.empty() )
  3199. {
  3200. kwsys_stl::string path = dir + "/" + file;
  3201. if ( SystemTools::FileExists(path.c_str()) )
  3202. {
  3203. return path;
  3204. }
  3205. if ( dir.size() < strlen(toplevel) )
  3206. {
  3207. break;
  3208. }
  3209. dir = SystemTools::GetParentDirectory(dir.c_str());
  3210. }
  3211. return "";
  3212. }
  3213. void SystemTools::Delay(unsigned int msec)
  3214. {
  3215. #ifdef _WIN32
  3216. Sleep(msec);
  3217. #else
  3218. usleep(msec * 1000);
  3219. #endif
  3220. }
  3221. void SystemTools::ConvertWindowsCommandLineToUnixArguments(
  3222. const char *cmd_line, int *argc, char ***argv)
  3223. {
  3224. if (!cmd_line || !argc || !argv)
  3225. {
  3226. return;
  3227. }
  3228. // A space delimites an argument except when it is inside a quote
  3229. (*argc) = 1;
  3230. size_t cmd_line_len = strlen(cmd_line);
  3231. size_t i;
  3232. for (i = 0; i < cmd_line_len; i++)
  3233. {
  3234. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3235. {
  3236. i++;
  3237. }
  3238. if (i < cmd_line_len)
  3239. {
  3240. if (cmd_line[i] == '\"')
  3241. {
  3242. i++;
  3243. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3244. {
  3245. i++;
  3246. }
  3247. (*argc)++;
  3248. }
  3249. else
  3250. {
  3251. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3252. {
  3253. i++;
  3254. }
  3255. (*argc)++;
  3256. }
  3257. }
  3258. }
  3259. (*argv) = new char* [(*argc) + 1];
  3260. (*argv)[(*argc)] = NULL;
  3261. // Set the first arg to be the exec name
  3262. (*argv)[0] = new char [1024];
  3263. #ifdef _WIN32
  3264. ::GetModuleFileName(0, (*argv)[0], 1024);
  3265. #else
  3266. (*argv)[0][0] = '\0';
  3267. #endif
  3268. // Allocate the others
  3269. int j;
  3270. for (j = 1; j < (*argc); j++)
  3271. {
  3272. (*argv)[j] = new char [cmd_line_len + 10];
  3273. }
  3274. // Grab the args
  3275. size_t pos;
  3276. int argc_idx = 1;
  3277. for (i = 0; i < cmd_line_len; i++)
  3278. {
  3279. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3280. {
  3281. i++;
  3282. }
  3283. if (i < cmd_line_len)
  3284. {
  3285. if (cmd_line[i] == '\"')
  3286. {
  3287. i++;
  3288. pos = i;
  3289. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3290. {
  3291. i++;
  3292. }
  3293. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3294. (*argv)[argc_idx][i - pos] = '\0';
  3295. argc_idx++;
  3296. }
  3297. else
  3298. {
  3299. pos = i;
  3300. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3301. {
  3302. i++;
  3303. }
  3304. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3305. (*argv)[argc_idx][i - pos] = '\0';
  3306. argc_idx++;
  3307. }
  3308. }
  3309. }
  3310. }
  3311. kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
  3312. {
  3313. kwsys_stl::string res;
  3314. #ifdef _WIN32
  3315. char buffer[256];
  3316. OSVERSIONINFOEX osvi;
  3317. BOOL bOsVersionInfoEx;
  3318. // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
  3319. // If that fails, try using the OSVERSIONINFO structure.
  3320. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  3321. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  3322. bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi);
  3323. if (!bOsVersionInfoEx)
  3324. {
  3325. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  3326. if (!GetVersionEx((OSVERSIONINFO *)&osvi))
  3327. {
  3328. return 0;
  3329. }
  3330. }
  3331. switch (osvi.dwPlatformId)
  3332. {
  3333. // Test for the Windows NT product family.
  3334. case VER_PLATFORM_WIN32_NT:
  3335. // Test for the specific product family.
  3336. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  3337. {
  3338. res += "Microsoft Windows Server 2003 family";
  3339. }
  3340. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  3341. {
  3342. res += "Microsoft Windows XP";
  3343. }
  3344. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  3345. {
  3346. res += "Microsoft Windows 2000";
  3347. }
  3348. if (osvi.dwMajorVersion <= 4)
  3349. {
  3350. res += "Microsoft Windows NT";
  3351. }
  3352. // Test for specific product on Windows NT 4.0 SP6 and later.
  3353. if (bOsVersionInfoEx)
  3354. {
  3355. // Test for the workstation type.
  3356. #if (_MSC_VER >= 1300)
  3357. if (osvi.wProductType == VER_NT_WORKSTATION)
  3358. {
  3359. if (osvi.dwMajorVersion == 4)
  3360. {
  3361. res += " Workstation 4.0";
  3362. }
  3363. else if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
  3364. {
  3365. res += " Home Edition";
  3366. }
  3367. else
  3368. {
  3369. res += " Professional";
  3370. }
  3371. }
  3372. // Test for the server type.
  3373. else if (osvi.wProductType == VER_NT_SERVER)
  3374. {
  3375. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  3376. {
  3377. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  3378. {
  3379. res += " Datacenter Edition";
  3380. }
  3381. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3382. {
  3383. res += " Enterprise Edition";
  3384. }
  3385. else if (osvi.wSuiteMask == VER_SUITE_BLADE)
  3386. {
  3387. res += " Web Edition";
  3388. }
  3389. else
  3390. {
  3391. res += " Standard Edition";
  3392. }
  3393. }
  3394. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  3395. {
  3396. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  3397. {
  3398. res += " Datacenter Server";
  3399. }
  3400. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3401. {
  3402. res += " Advanced Server";
  3403. }
  3404. else
  3405. {
  3406. res += " Server";
  3407. }
  3408. }
  3409. else // Windows NT 4.0
  3410. {
  3411. if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3412. {
  3413. res += " Server 4.0, Enterprise Edition";
  3414. }
  3415. else
  3416. {
  3417. res += " Server 4.0";
  3418. }
  3419. }
  3420. }
  3421. #endif // Visual Studio 7 and up
  3422. }
  3423. // Test for specific product on Windows NT 4.0 SP5 and earlier
  3424. else
  3425. {
  3426. HKEY hKey;
  3427. #define BUFSIZE 80
  3428. char szProductType[BUFSIZE];
  3429. DWORD dwBufLen=BUFSIZE;
  3430. LONG lRet;
  3431. lRet = RegOpenKeyEx(
  3432. HKEY_LOCAL_MACHINE,
  3433. "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
  3434. 0, KEY_QUERY_VALUE, &hKey);
  3435. if (lRet != ERROR_SUCCESS)
  3436. {
  3437. return 0;
  3438. }
  3439. lRet = RegQueryValueEx(hKey, "ProductType", NULL, NULL,
  3440. (LPBYTE) szProductType, &dwBufLen);
  3441. if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))
  3442. {
  3443. return 0;
  3444. }
  3445. RegCloseKey(hKey);
  3446. if (lstrcmpi("WINNT", szProductType) == 0)
  3447. {
  3448. res += " Workstation";
  3449. }
  3450. if (lstrcmpi("LANMANNT", szProductType) == 0)
  3451. {
  3452. res += " Server";
  3453. }
  3454. if (lstrcmpi("SERVERNT", szProductType) == 0)
  3455. {
  3456. res += " Advanced Server";
  3457. }
  3458. res += " ";
  3459. sprintf(buffer, "%d", osvi.dwMajorVersion);
  3460. res += buffer;
  3461. res += ".";
  3462. sprintf(buffer, "%d", osvi.dwMinorVersion);
  3463. res += buffer;
  3464. }
  3465. // Display service pack (if any) and build number.
  3466. if (osvi.dwMajorVersion == 4 &&
  3467. lstrcmpi(osvi.szCSDVersion, "Service Pack 6") == 0)
  3468. {
  3469. HKEY hKey;
  3470. LONG lRet;
  3471. // Test for SP6 versus SP6a.
  3472. lRet = RegOpenKeyEx(
  3473. HKEY_LOCAL_MACHINE,
  3474. "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
  3475. 0, KEY_QUERY_VALUE, &hKey);
  3476. if (lRet == ERROR_SUCCESS)
  3477. {
  3478. res += " Service Pack 6a (Build ";
  3479. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3480. res += buffer;
  3481. res += ")";
  3482. }
  3483. else // Windows NT 4.0 prior to SP6a
  3484. {
  3485. res += " ";
  3486. res += osvi.szCSDVersion;
  3487. res += " (Build ";
  3488. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3489. res += buffer;
  3490. res += ")";
  3491. }
  3492. RegCloseKey(hKey);
  3493. }
  3494. else // Windows NT 3.51 and earlier or Windows 2000 and later
  3495. {
  3496. res += " ";
  3497. res += osvi.szCSDVersion;
  3498. res += " (Build ";
  3499. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3500. res += buffer;
  3501. res += ")";
  3502. }
  3503. break;
  3504. // Test for the Windows 95 product family.
  3505. case VER_PLATFORM_WIN32_WINDOWS:
  3506. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
  3507. {
  3508. res += "Microsoft Windows 95";
  3509. if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
  3510. {
  3511. res += " OSR2";
  3512. }
  3513. }
  3514. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
  3515. {
  3516. res += "Microsoft Windows 98";
  3517. if (osvi.szCSDVersion[1] == 'A')
  3518. {
  3519. res += " SE";
  3520. }
  3521. }
  3522. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
  3523. {
  3524. res += "Microsoft Windows Millennium Edition";
  3525. }
  3526. break;
  3527. case VER_PLATFORM_WIN32s:
  3528. res += "Microsoft Win32s";
  3529. break;
  3530. }
  3531. #endif
  3532. return res;
  3533. }
  3534. // These must NOT be initialized. Default initialization to zero is
  3535. // necessary.
  3536. unsigned int SystemToolsManagerCount;
  3537. SystemToolsTranslationMap *SystemTools::TranslationMap;
  3538. // SystemToolsManager manages the SystemTools singleton.
  3539. // SystemToolsManager should be included in any translation unit
  3540. // that will use SystemTools or that implements the singleton
  3541. // pattern. It makes sure that the SystemTools singleton is created
  3542. // before and destroyed after all other singletons in CMake.
  3543. SystemToolsManager::SystemToolsManager()
  3544. {
  3545. if(++SystemToolsManagerCount == 1)
  3546. {
  3547. SystemTools::ClassInitialize();
  3548. }
  3549. }
  3550. SystemToolsManager::~SystemToolsManager()
  3551. {
  3552. if(--SystemToolsManagerCount == 0)
  3553. {
  3554. SystemTools::ClassFinalize();
  3555. }
  3556. }
  3557. void SystemTools::ClassInitialize()
  3558. {
  3559. // Allocate the translation map first.
  3560. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  3561. // Add some special translation paths for unix. These are not added
  3562. // for windows because drive letters need to be maintained. Also,
  3563. // there are not sym-links and mount points on windows anyway.
  3564. #if !defined(_WIN32) || defined(__CYGWIN__)
  3565. // Work-around an SGI problem by always adding this mapping:
  3566. SystemTools::AddTranslationPath("/tmp_mnt/", "/");
  3567. // The tmp path is frequently a logical path so always keep it:
  3568. SystemTools::AddKeepPath("/tmp/");
  3569. // If the current working directory is a logical path then keep the
  3570. // logical name.
  3571. if(const char* pwd = getenv("PWD"))
  3572. {
  3573. char buf[2048];
  3574. if(const char* cwd = Getcwd(buf, 2048))
  3575. {
  3576. // The current working directory may be a logical path. Find
  3577. // the shortest logical path that still produces the correct
  3578. // physical path.
  3579. kwsys_stl::string cwd_changed;
  3580. kwsys_stl::string pwd_changed;
  3581. // Test progressively shorter logical-to-physical mappings.
  3582. kwsys_stl::string pwd_str = pwd;
  3583. kwsys_stl::string cwd_str = cwd;
  3584. kwsys_stl::string pwd_path;
  3585. Realpath(pwd, pwd_path);
  3586. while(cwd_str == pwd_path && cwd_str != pwd_str)
  3587. {
  3588. // The current pair of paths is a working logical mapping.
  3589. cwd_changed = cwd_str;
  3590. pwd_changed = pwd_str;
  3591. // Strip off one directory level and see if the logical
  3592. // mapping still works.
  3593. pwd_str = SystemTools::GetFilenamePath(pwd_str.c_str());
  3594. cwd_str = SystemTools::GetFilenamePath(cwd_str.c_str());
  3595. Realpath(pwd_str.c_str(), pwd_path);
  3596. }
  3597. // Add the translation to keep the logical path name.
  3598. if(!cwd_changed.empty() && !pwd_changed.empty())
  3599. {
  3600. SystemTools::AddTranslationPath(cwd_changed.c_str(),
  3601. pwd_changed.c_str());
  3602. }
  3603. }
  3604. }
  3605. #endif
  3606. }
  3607. void SystemTools::ClassFinalize()
  3608. {
  3609. delete SystemTools::TranslationMap;
  3610. }
  3611. } // namespace KWSYS_NAMESPACE
  3612. #if defined(_MSC_VER) && defined(_DEBUG)
  3613. # include <crtdbg.h>
  3614. # include <stdio.h>
  3615. # include <stdlib.h>
  3616. namespace KWSYS_NAMESPACE
  3617. {
  3618. static int SystemToolsDebugReport(int, char* message, int*)
  3619. {
  3620. fprintf(stderr, message);
  3621. exit(1);
  3622. }
  3623. void SystemTools::EnableMSVCDebugHook()
  3624. {
  3625. if(getenv("DART_TEST_FROM_DART"))
  3626. {
  3627. _CrtSetReportHook(SystemToolsDebugReport);
  3628. }
  3629. }
  3630. } // namespace KWSYS_NAMESPACE
  3631. #else
  3632. namespace KWSYS_NAMESPACE
  3633. {
  3634. void SystemTools::EnableMSVCDebugHook() {}
  3635. } // namespace KWSYS_NAMESPACE
  3636. #endif