SystemTools.cxx 98 KB

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