SystemTools.cxx 96 KB

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