SystemTools.cxx 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099
  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. // escape spaces and () in the path
  1251. if(ret.find_first_of(" ()") != kwsys_stl::string::npos)
  1252. {
  1253. kwsys_stl::string result = "";
  1254. char lastch = 1;
  1255. bool inDollarVariable = false;
  1256. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  1257. {
  1258. // if it is already escaped then don't try to escape it again
  1259. if((*ch == ' ' || *ch == '(' || *ch == ')') && lastch != '\\')
  1260. {
  1261. if(*ch == '(' && lastch == '$')
  1262. {
  1263. inDollarVariable = true;
  1264. }
  1265. // if we are in a $(..... and we get a ) then do not escape
  1266. // the ) and but set inDollarVariable to false
  1267. else if(*ch == ')' && inDollarVariable)
  1268. {
  1269. inDollarVariable = false;
  1270. }
  1271. else
  1272. {
  1273. result += '\\';
  1274. }
  1275. }
  1276. result += *ch;
  1277. lastch = *ch;
  1278. }
  1279. ret = result;
  1280. }
  1281. return ret;
  1282. }
  1283. kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
  1284. {
  1285. #if defined(_WIN32) && !defined(__CYGWIN__)
  1286. return SystemTools::ConvertToWindowsOutputPath(path);
  1287. #else
  1288. return SystemTools::ConvertToUnixOutputPath(path);
  1289. #endif
  1290. }
  1291. // remove double slashes not at the start
  1292. kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
  1293. {
  1294. kwsys_stl::string ret;
  1295. // make it big enough for all of path and double quotes
  1296. ret.reserve(strlen(path)+3);
  1297. // put path into the string
  1298. ret.insert(0,path);
  1299. kwsys_stl::string::size_type pos = 0;
  1300. // first convert all of the slashes
  1301. while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
  1302. {
  1303. ret[pos] = '\\';
  1304. pos++;
  1305. }
  1306. // check for really small paths
  1307. if(ret.size() < 2)
  1308. {
  1309. return ret;
  1310. }
  1311. // now clean up a bit and remove double slashes
  1312. // Only if it is not the first position in the path which is a network
  1313. // path on windows
  1314. pos = 1; // start at position 1
  1315. if(ret[0] == '\"')
  1316. {
  1317. pos = 2; // if the string is already quoted then start at 2
  1318. if(ret.size() < 3)
  1319. {
  1320. return ret;
  1321. }
  1322. }
  1323. while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
  1324. {
  1325. ret.erase(pos, 1);
  1326. }
  1327. // now double quote the path if it has spaces in it
  1328. // and is not already double quoted
  1329. if(ret.find(' ') != kwsys_stl::string::npos
  1330. && ret[0] != '\"')
  1331. {
  1332. ret.insert(static_cast<kwsys_stl::string::size_type>(0),
  1333. static_cast<kwsys_stl::string::size_type>(1), '\"');
  1334. ret.append(1, '\"');
  1335. }
  1336. return ret;
  1337. }
  1338. bool SystemTools::CopyFileIfDifferent(const char* source,
  1339. const char* destination)
  1340. {
  1341. if(SystemTools::FilesDiffer(source, destination))
  1342. {
  1343. return SystemTools::CopyFileAlways(source, destination);
  1344. }
  1345. return true;
  1346. }
  1347. #define KWSYS_ST_BUFFER 4096
  1348. bool SystemTools::FilesDiffer(const char* source,
  1349. const char* destination)
  1350. {
  1351. struct stat statSource;
  1352. if (stat(source, &statSource) != 0)
  1353. {
  1354. return true;
  1355. }
  1356. struct stat statDestination;
  1357. if (stat(destination, &statDestination) != 0)
  1358. {
  1359. return true;
  1360. }
  1361. if(statSource.st_size != statDestination.st_size)
  1362. {
  1363. return true;
  1364. }
  1365. if(statSource.st_size == 0)
  1366. {
  1367. return false;
  1368. }
  1369. #if defined(_WIN32) || defined(__CYGWIN__)
  1370. kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
  1371. kwsys_ios::ios::in));
  1372. kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
  1373. kwsys_ios::ios::in));
  1374. #else
  1375. kwsys_ios::ifstream finSource(source);
  1376. kwsys_ios::ifstream finDestination(destination);
  1377. #endif
  1378. if(!finSource || !finDestination)
  1379. {
  1380. return true;
  1381. }
  1382. // Compare the files a block at a time.
  1383. char source_buf[KWSYS_ST_BUFFER];
  1384. char dest_buf[KWSYS_ST_BUFFER];
  1385. long nleft = statSource.st_size;
  1386. while(nleft > 0)
  1387. {
  1388. // Read a block from each file.
  1389. long nnext = (nleft > KWSYS_ST_BUFFER)? KWSYS_ST_BUFFER : nleft;
  1390. finSource.read(source_buf, nnext);
  1391. finDestination.read(dest_buf, nnext);
  1392. // If either failed to read assume they are different.
  1393. if(static_cast<long>(finSource.gcount()) != nnext ||
  1394. static_cast<long>(finDestination.gcount()) != nnext)
  1395. {
  1396. return true;
  1397. }
  1398. // If this block differs the file differs.
  1399. if(memcmp(static_cast<const void*>(source_buf),
  1400. static_cast<const void*>(dest_buf), nnext) != 0)
  1401. {
  1402. return true;
  1403. }
  1404. // Update the byte count remaining.
  1405. nleft -= nnext;
  1406. }
  1407. // No differences found.
  1408. return false;
  1409. }
  1410. /**
  1411. * Copy a file named by "source" to the file named by "destination".
  1412. */
  1413. bool SystemTools::CopyFileAlways(const char* source, const char* destination)
  1414. {
  1415. // If files are the same do not copy
  1416. if ( SystemTools::SameFile(source, destination) )
  1417. {
  1418. return true;
  1419. }
  1420. mode_t perm = 0;
  1421. bool perms = SystemTools::GetPermissions(source, perm);
  1422. const int bufferSize = 4096;
  1423. char buffer[bufferSize];
  1424. // If destination is a directory, try to create a file with the same
  1425. // name as the source in that directory.
  1426. kwsys_stl::string new_destination;
  1427. if(SystemTools::FileExists(destination) &&
  1428. SystemTools::FileIsDirectory(destination))
  1429. {
  1430. new_destination = destination;
  1431. SystemTools::ConvertToUnixSlashes(new_destination);
  1432. new_destination += '/';
  1433. kwsys_stl::string source_name = source;
  1434. new_destination += SystemTools::GetFilenameName(source_name);
  1435. destination = new_destination.c_str();
  1436. }
  1437. // Create destination directory
  1438. kwsys_stl::string destination_dir = destination;
  1439. destination_dir = SystemTools::GetFilenamePath(destination_dir);
  1440. SystemTools::MakeDirectory(destination_dir.c_str());
  1441. // Open files
  1442. #if defined(_WIN32) || defined(__CYGWIN__)
  1443. kwsys_ios::ifstream fin(source,
  1444. kwsys_ios::ios::binary | kwsys_ios::ios::in);
  1445. #else
  1446. kwsys_ios::ifstream fin(source);
  1447. #endif
  1448. if(!fin)
  1449. {
  1450. return false;
  1451. }
  1452. // try and remove the destination file so that read only destination files
  1453. // can be written to.
  1454. // If the remove fails continue so that files in read only directories
  1455. // that do not allow file removal can be modified.
  1456. SystemTools::RemoveFile(destination);
  1457. #if defined(_WIN32) || defined(__CYGWIN__)
  1458. kwsys_ios::ofstream fout(destination,
  1459. kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1460. #else
  1461. kwsys_ios::ofstream fout(destination,
  1462. kwsys_ios::ios::out | kwsys_ios::ios::trunc);
  1463. #endif
  1464. if(!fout)
  1465. {
  1466. return false;
  1467. }
  1468. // This copy loop is very sensitive on certain platforms with
  1469. // slightly broken stream libraries (like HPUX). Normally, it is
  1470. // incorrect to not check the error condition on the fin.read()
  1471. // before using the data, but the fin.gcount() will be zero if an
  1472. // error occurred. Therefore, the loop should be safe everywhere.
  1473. while(fin)
  1474. {
  1475. fin.read(buffer, bufferSize);
  1476. if(fin.gcount())
  1477. {
  1478. fout.write(buffer, fin.gcount());
  1479. }
  1480. }
  1481. // Make sure the operating system has finished writing the file
  1482. // before closing it. This will ensure the file is finished before
  1483. // the check below.
  1484. fout.flush();
  1485. fin.close();
  1486. fout.close();
  1487. // More checks.
  1488. struct stat statSource, statDestination;
  1489. statSource.st_size = 12345;
  1490. statDestination.st_size = 12345;
  1491. if(stat(source, &statSource) != 0)
  1492. {
  1493. return false;
  1494. }
  1495. else if(stat(destination, &statDestination) != 0)
  1496. {
  1497. return false;
  1498. }
  1499. else if(statSource.st_size != statDestination.st_size)
  1500. {
  1501. return false;
  1502. }
  1503. if ( perms )
  1504. {
  1505. if ( !SystemTools::SetPermissions(destination, perm) )
  1506. {
  1507. return false;
  1508. }
  1509. }
  1510. return true;
  1511. }
  1512. //----------------------------------------------------------------------------
  1513. bool SystemTools::CopyAFile(const char* source, const char* destination,
  1514. bool always)
  1515. {
  1516. if(always)
  1517. {
  1518. return SystemTools::CopyFileAlways(source, destination);
  1519. }
  1520. else
  1521. {
  1522. return SystemTools::CopyFileIfDifferent(source, destination);
  1523. }
  1524. }
  1525. /**
  1526. * Copy a directory content from "source" directory to the directory named by
  1527. * "destination".
  1528. */
  1529. bool SystemTools::CopyADirectory(const char* source, const char* destination,
  1530. bool always)
  1531. {
  1532. Directory dir;
  1533. dir.Load(source);
  1534. size_t fileNum;
  1535. if ( !SystemTools::MakeDirectory(destination) )
  1536. {
  1537. return false;
  1538. }
  1539. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1540. {
  1541. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1542. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1543. {
  1544. kwsys_stl::string fullPath = source;
  1545. fullPath += "/";
  1546. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1547. if(SystemTools::FileIsDirectory(fullPath.c_str()))
  1548. {
  1549. kwsys_stl::string fullDestPath = destination;
  1550. fullDestPath += "/";
  1551. fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1552. if (!SystemTools::CopyADirectory(fullPath.c_str(),
  1553. fullDestPath.c_str(),
  1554. always))
  1555. {
  1556. return false;
  1557. }
  1558. }
  1559. else
  1560. {
  1561. if(!SystemTools::CopyAFile(fullPath.c_str(), destination, always))
  1562. {
  1563. return false;
  1564. }
  1565. }
  1566. }
  1567. }
  1568. return true;
  1569. }
  1570. // return size of file; also returns zero if no file exists
  1571. unsigned long SystemTools::FileLength(const char* filename)
  1572. {
  1573. struct stat fs;
  1574. if (stat(filename, &fs) != 0)
  1575. {
  1576. return 0;
  1577. }
  1578. else
  1579. {
  1580. return static_cast<unsigned long>(fs.st_size);
  1581. }
  1582. }
  1583. int SystemTools::Strucmp(const char *s1, const char *s2)
  1584. {
  1585. // lifted from Graphvis http://www.graphviz.org
  1586. while ((*s1 != '\0')
  1587. && (tolower(*s1) == tolower(*s2)))
  1588. {
  1589. s1++;
  1590. s2++;
  1591. }
  1592. return tolower(*s1) - tolower(*s2);
  1593. }
  1594. // return file's modified time
  1595. long int SystemTools::ModifiedTime(const char* filename)
  1596. {
  1597. struct stat fs;
  1598. if (stat(filename, &fs) != 0)
  1599. {
  1600. return 0;
  1601. }
  1602. else
  1603. {
  1604. return static_cast<long int>(fs.st_mtime);
  1605. }
  1606. }
  1607. // return file's creation time
  1608. long int SystemTools::CreationTime(const char* filename)
  1609. {
  1610. struct stat fs;
  1611. if (stat(filename, &fs) != 0)
  1612. {
  1613. return 0;
  1614. }
  1615. else
  1616. {
  1617. return fs.st_ctime >= 0 ? static_cast<long int>(fs.st_ctime) : 0;
  1618. }
  1619. }
  1620. bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
  1621. {
  1622. if (!str || !tmt || strlen(str) > 11)
  1623. {
  1624. return false;
  1625. }
  1626. struct tm tmt2;
  1627. // __DATE__
  1628. // The compilation date of the current source file. The date is a string
  1629. // literal of the form Mmm dd yyyy. The month name Mmm is the same as for
  1630. // dates generated by the library function asctime declared in TIME.H.
  1631. // index: 012345678901
  1632. // format: Mmm dd yyyy
  1633. // example: Dec 19 2003
  1634. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  1635. char buffer[12];
  1636. strcpy(buffer, str);
  1637. buffer[3] = 0;
  1638. char *ptr = strstr(month_names, buffer);
  1639. if (!ptr)
  1640. {
  1641. return false;
  1642. }
  1643. int month = (ptr - month_names) / 3;
  1644. int day = atoi(buffer + 4);
  1645. int year = atoi(buffer + 7);
  1646. tmt2.tm_isdst = -1;
  1647. tmt2.tm_hour = 0;
  1648. tmt2.tm_min = 0;
  1649. tmt2.tm_sec = 0;
  1650. tmt2.tm_wday = 0;
  1651. tmt2.tm_yday = 0;
  1652. tmt2.tm_mday = day;
  1653. tmt2.tm_mon = month;
  1654. tmt2.tm_year = year - 1900;
  1655. *tmt = mktime(&tmt2);
  1656. return true;
  1657. }
  1658. bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
  1659. {
  1660. if (!str || !tmt || strlen(str) > 26)
  1661. {
  1662. return false;
  1663. }
  1664. struct tm tmt2;
  1665. // __TIMESTAMP__
  1666. // The date and time of the last modification of the current source file,
  1667. // expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy,
  1668. /// where Ddd is the abbreviated day of the week and Date is an integer
  1669. // from 1 to 31.
  1670. // index: 0123456789
  1671. // 0123456789
  1672. // 0123456789
  1673. // format: Ddd Mmm Date hh:mm:ss yyyy
  1674. // example: Fri Dec 19 14:34:58 2003
  1675. static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  1676. char buffer[27];
  1677. strcpy(buffer, str);
  1678. buffer[7] = 0;
  1679. char *ptr = strstr(month_names, buffer + 4);
  1680. if (!ptr)
  1681. {
  1682. return false;
  1683. }
  1684. int month = (ptr - month_names) / 3;
  1685. int day = atoi(buffer + 8);
  1686. int hour = atoi(buffer + 11);
  1687. int min = atoi(buffer + 14);
  1688. int sec = atoi(buffer + 17);
  1689. int year = atoi(buffer + 20);
  1690. tmt2.tm_isdst = -1;
  1691. tmt2.tm_hour = hour;
  1692. tmt2.tm_min = min;
  1693. tmt2.tm_sec = sec;
  1694. tmt2.tm_wday = 0;
  1695. tmt2.tm_yday = 0;
  1696. tmt2.tm_mday = day;
  1697. tmt2.tm_mon = month;
  1698. tmt2.tm_year = year - 1900;
  1699. *tmt = mktime(&tmt2);
  1700. return true;
  1701. }
  1702. kwsys_stl::string SystemTools::GetLastSystemError()
  1703. {
  1704. int e = errno;
  1705. return strerror(e);
  1706. }
  1707. bool SystemTools::RemoveFile(const char* source)
  1708. {
  1709. #ifdef _WIN32
  1710. mode_t mode;
  1711. if ( !SystemTools::GetPermissions(source, mode) )
  1712. {
  1713. return false;
  1714. }
  1715. /* Win32 unlink is stupid --- it fails if the file is read-only */
  1716. SystemTools::SetPermissions(source, S_IWRITE);
  1717. #endif
  1718. bool res = unlink(source) != 0 ? false : true;
  1719. #ifdef _WIN32
  1720. if ( !res )
  1721. {
  1722. SystemTools::SetPermissions(source, mode);
  1723. }
  1724. #endif
  1725. return res;
  1726. }
  1727. bool SystemTools::RemoveADirectory(const char* source)
  1728. {
  1729. Directory dir;
  1730. dir.Load(source);
  1731. size_t fileNum;
  1732. for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
  1733. {
  1734. if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
  1735. strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
  1736. {
  1737. kwsys_stl::string fullPath = source;
  1738. fullPath += "/";
  1739. fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
  1740. if(SystemTools::FileIsDirectory(fullPath.c_str()) &&
  1741. !SystemTools::FileIsSymlink(fullPath.c_str()))
  1742. {
  1743. if (!SystemTools::RemoveADirectory(fullPath.c_str()))
  1744. {
  1745. return false;
  1746. }
  1747. }
  1748. else
  1749. {
  1750. if(!SystemTools::RemoveFile(fullPath.c_str()))
  1751. {
  1752. return false;
  1753. }
  1754. }
  1755. }
  1756. }
  1757. return (Rmdir(source) == 0);
  1758. }
  1759. /**
  1760. */
  1761. size_t SystemTools::GetMaximumFilePathLength()
  1762. {
  1763. return KWSYS_SYSTEMTOOLS_MAXPATH;
  1764. }
  1765. /**
  1766. * Find the file the given name. Searches the given path and then
  1767. * the system search path. Returns the full path to the file if it is
  1768. * found. Otherwise, the empty string is returned.
  1769. */
  1770. kwsys_stl::string SystemTools
  1771. ::FindName(const char* name,
  1772. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1773. bool no_system_path)
  1774. {
  1775. // Add the system search path to our path first
  1776. kwsys_stl::vector<kwsys_stl::string> path;
  1777. if (!no_system_path)
  1778. {
  1779. SystemTools::GetPath(path, "CMAKE_FILE_PATH");
  1780. SystemTools::GetPath(path);
  1781. }
  1782. // now add the additional paths
  1783. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
  1784. i != userPaths.end(); ++i)
  1785. {
  1786. path.push_back(*i);
  1787. }
  1788. // now look for the file
  1789. kwsys_stl::string tryPath;
  1790. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1791. p != path.end(); ++p)
  1792. {
  1793. tryPath = *p;
  1794. tryPath += "/";
  1795. tryPath += name;
  1796. if(SystemTools::FileExists(tryPath.c_str()))
  1797. {
  1798. return tryPath;
  1799. }
  1800. }
  1801. // Couldn't find the file.
  1802. return "";
  1803. }
  1804. /**
  1805. * Find the file the given name. Searches the given path and then
  1806. * the system search path. Returns the full path to the file if it is
  1807. * found. Otherwise, the empty string is returned.
  1808. */
  1809. kwsys_stl::string SystemTools
  1810. ::FindFile(const char* name,
  1811. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1812. bool no_system_path)
  1813. {
  1814. kwsys_stl::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
  1815. if(tryPath != "" && !SystemTools::FileIsDirectory(tryPath.c_str()))
  1816. {
  1817. return SystemTools::CollapseFullPath(tryPath.c_str());
  1818. }
  1819. // Couldn't find the file.
  1820. return "";
  1821. }
  1822. /**
  1823. * Find the directory the given name. Searches the given path and then
  1824. * the system search path. Returns the full path to the directory if it is
  1825. * found. Otherwise, the empty string is returned.
  1826. */
  1827. kwsys_stl::string SystemTools
  1828. ::FindDirectory(const char* name,
  1829. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1830. bool no_system_path)
  1831. {
  1832. kwsys_stl::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
  1833. if(tryPath != "" && SystemTools::FileIsDirectory(tryPath.c_str()))
  1834. {
  1835. return SystemTools::CollapseFullPath(tryPath.c_str());
  1836. }
  1837. // Couldn't find the file.
  1838. return "";
  1839. }
  1840. /**
  1841. * Find the executable with the given name. Searches the given path and then
  1842. * the system search path. Returns the full path to the executable if it is
  1843. * found. Otherwise, the empty string is returned.
  1844. */
  1845. kwsys_stl::string SystemTools::FindProgram(
  1846. const char* nameIn,
  1847. const kwsys_stl::vector<kwsys_stl::string>& userPaths,
  1848. bool no_system_path)
  1849. {
  1850. if(!nameIn || !*nameIn)
  1851. {
  1852. return "";
  1853. }
  1854. kwsys_stl::string name = nameIn;
  1855. kwsys_stl::vector<kwsys_stl::string> extensions;
  1856. #if defined (_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
  1857. bool hasExtension = false;
  1858. // check to see if the name already has a .xxx at
  1859. // the end of it
  1860. if(name.size() > 3 && name[name.size()-4] == '.')
  1861. {
  1862. hasExtension = true;
  1863. }
  1864. // on windows try .com then .exe
  1865. if(!hasExtension)
  1866. {
  1867. extensions.push_back(".com");
  1868. extensions.push_back(".exe");
  1869. }
  1870. #endif
  1871. kwsys_stl::string tryPath;
  1872. // first try with extensions if the os supports them
  1873. if(extensions.size())
  1874. {
  1875. for(kwsys_stl::vector<kwsys_stl::string>::iterator i =
  1876. extensions.begin(); i != extensions.end(); ++i)
  1877. {
  1878. tryPath = name;
  1879. tryPath += *i;
  1880. if(SystemTools::FileExists(tryPath.c_str()) &&
  1881. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1882. {
  1883. return SystemTools::CollapseFullPath(tryPath.c_str());
  1884. }
  1885. }
  1886. }
  1887. // now try just the name
  1888. tryPath = name;
  1889. if(SystemTools::FileExists(tryPath.c_str()) &&
  1890. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1891. {
  1892. return SystemTools::CollapseFullPath(tryPath.c_str());
  1893. }
  1894. // now construct the path
  1895. kwsys_stl::vector<kwsys_stl::string> path;
  1896. // Add the system search path to our path.
  1897. if (!no_system_path)
  1898. {
  1899. SystemTools::GetPath(path);
  1900. }
  1901. // now add the additional paths
  1902. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i =
  1903. userPaths.begin(); i != userPaths.end(); ++i)
  1904. {
  1905. path.push_back(*i);
  1906. }
  1907. // Try each path
  1908. for(kwsys_stl::vector<kwsys_stl::string>::iterator p = path.begin();
  1909. p != path.end(); ++p)
  1910. {
  1911. #ifdef _WIN32
  1912. // Remove double quotes from the path on windows
  1913. SystemTools::ReplaceString(*p, "\"", "");
  1914. #endif
  1915. // first try with extensions
  1916. if(extensions.size())
  1917. {
  1918. for(kwsys_stl::vector<kwsys_stl::string>::iterator ext
  1919. = extensions.begin(); ext != extensions.end(); ++ext)
  1920. {
  1921. tryPath = *p;
  1922. tryPath += "/";
  1923. tryPath += name;
  1924. tryPath += *ext;
  1925. if(SystemTools::FileExists(tryPath.c_str()) &&
  1926. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1927. {
  1928. return SystemTools::CollapseFullPath(tryPath.c_str());
  1929. }
  1930. }
  1931. }
  1932. // now try it without them
  1933. tryPath = *p;
  1934. tryPath += "/";
  1935. tryPath += name;
  1936. if(SystemTools::FileExists(tryPath.c_str()) &&
  1937. !SystemTools::FileIsDirectory(tryPath.c_str()))
  1938. {
  1939. return SystemTools::CollapseFullPath(tryPath.c_str());
  1940. }
  1941. }
  1942. // Couldn't find the program.
  1943. return "";
  1944. }
  1945. kwsys_stl::string SystemTools::FindProgram(
  1946. const kwsys_stl::vector<kwsys_stl::string>& names,
  1947. const kwsys_stl::vector<kwsys_stl::string>& path,
  1948. bool noSystemPath)
  1949. {
  1950. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator it = names.begin();
  1951. it != names.end() ; ++it)
  1952. {
  1953. // Try to find the program.
  1954. kwsys_stl::string result = SystemTools::FindProgram(it->c_str(),
  1955. path,
  1956. noSystemPath);
  1957. if ( !result.empty() )
  1958. {
  1959. return result;
  1960. }
  1961. }
  1962. return "";
  1963. }
  1964. /**
  1965. * Find the library with the given name. Searches the given path and then
  1966. * the system search path. Returns the full path to the library if it is
  1967. * found. Otherwise, the empty string is returned.
  1968. */
  1969. kwsys_stl::string SystemTools
  1970. ::FindLibrary(const char* name,
  1971. const kwsys_stl::vector<kwsys_stl::string>& userPaths)
  1972. {
  1973. // See if the executable exists as written.
  1974. if(SystemTools::FileExists(name) &&
  1975. !SystemTools::FileIsDirectory(name))
  1976. {
  1977. return SystemTools::CollapseFullPath(name);
  1978. }
  1979. // Add the system search path to our path.
  1980. kwsys_stl::vector<kwsys_stl::string> path;
  1981. SystemTools::GetPath(path);
  1982. // now add the additional paths
  1983. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = userPaths.begin();
  1984. i != userPaths.end(); ++i)
  1985. {
  1986. path.push_back(*i);
  1987. }
  1988. kwsys_stl::string tryPath;
  1989. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator p = path.begin();
  1990. p != path.end(); ++p)
  1991. {
  1992. #if defined(__APPLE__)
  1993. tryPath = *p;
  1994. tryPath += "/";
  1995. tryPath += name;
  1996. tryPath += ".framework";
  1997. if(SystemTools::FileExists(tryPath.c_str())
  1998. && SystemTools::FileIsDirectory(tryPath.c_str()))
  1999. {
  2000. return SystemTools::CollapseFullPath(tryPath.c_str());
  2001. }
  2002. #endif
  2003. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
  2004. tryPath = *p;
  2005. tryPath += "/";
  2006. tryPath += name;
  2007. tryPath += ".lib";
  2008. if(SystemTools::FileExists(tryPath.c_str())
  2009. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2010. {
  2011. return SystemTools::CollapseFullPath(tryPath.c_str());
  2012. }
  2013. #else
  2014. tryPath = *p;
  2015. tryPath += "/lib";
  2016. tryPath += name;
  2017. tryPath += ".so";
  2018. if(SystemTools::FileExists(tryPath.c_str())
  2019. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2020. {
  2021. return SystemTools::CollapseFullPath(tryPath.c_str());
  2022. }
  2023. tryPath = *p;
  2024. tryPath += "/lib";
  2025. tryPath += name;
  2026. tryPath += ".a";
  2027. if(SystemTools::FileExists(tryPath.c_str())
  2028. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2029. {
  2030. return SystemTools::CollapseFullPath(tryPath.c_str());
  2031. }
  2032. tryPath = *p;
  2033. tryPath += "/lib";
  2034. tryPath += name;
  2035. tryPath += ".sl";
  2036. if(SystemTools::FileExists(tryPath.c_str())
  2037. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2038. {
  2039. return SystemTools::CollapseFullPath(tryPath.c_str());
  2040. }
  2041. tryPath = *p;
  2042. tryPath += "/lib";
  2043. tryPath += name;
  2044. tryPath += ".dylib";
  2045. if(SystemTools::FileExists(tryPath.c_str())
  2046. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2047. {
  2048. return SystemTools::CollapseFullPath(tryPath.c_str());
  2049. }
  2050. tryPath = *p;
  2051. tryPath += "/lib";
  2052. tryPath += name;
  2053. tryPath += ".dll";
  2054. if(SystemTools::FileExists(tryPath.c_str())
  2055. && !SystemTools::FileIsDirectory(tryPath.c_str()))
  2056. {
  2057. return SystemTools::CollapseFullPath(tryPath.c_str());
  2058. }
  2059. #endif
  2060. }
  2061. // Couldn't find the library.
  2062. return "";
  2063. }
  2064. bool SystemTools::FileIsDirectory(const char* name)
  2065. {
  2066. // Remove any trailing slash from the name.
  2067. char buffer[KWSYS_SYSTEMTOOLS_MAXPATH];
  2068. int last = static_cast<int>(strlen(name))-1;
  2069. if(last >= 0 && (name[last] == '/' || name[last] == '\\'))
  2070. {
  2071. memcpy(buffer, name, last);
  2072. buffer[last] = 0;
  2073. name = buffer;
  2074. }
  2075. // Now check the file node type.
  2076. struct stat fs;
  2077. if(stat(name, &fs) == 0)
  2078. {
  2079. #if defined( _WIN32 )
  2080. return ((fs.st_mode & _S_IFDIR) != 0);
  2081. #else
  2082. return S_ISDIR(fs.st_mode);
  2083. #endif
  2084. }
  2085. else
  2086. {
  2087. return false;
  2088. }
  2089. }
  2090. bool SystemTools::FileIsSymlink(const char* name)
  2091. {
  2092. #if defined( _WIN32 )
  2093. (void)name;
  2094. return false;
  2095. #else
  2096. struct stat fs;
  2097. if(lstat(name, &fs) == 0)
  2098. {
  2099. return S_ISLNK(fs.st_mode);
  2100. }
  2101. else
  2102. {
  2103. return false;
  2104. }
  2105. #endif
  2106. }
  2107. int SystemTools::ChangeDirectory(const char *dir)
  2108. {
  2109. return Chdir(dir);
  2110. }
  2111. kwsys_stl::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
  2112. {
  2113. char buf[2048];
  2114. const char* cwd = Getcwd(buf, 2048);
  2115. kwsys_stl::string path;
  2116. if ( cwd )
  2117. {
  2118. path = cwd;
  2119. }
  2120. if(collapse)
  2121. {
  2122. return SystemTools::CollapseFullPath(path.c_str());
  2123. }
  2124. return path;
  2125. }
  2126. kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
  2127. {
  2128. kwsys_stl::string dir, file;
  2129. SystemTools::SplitProgramPath(in_name, dir, file);
  2130. return dir;
  2131. }
  2132. bool SystemTools::SplitProgramPath(const char* in_name,
  2133. kwsys_stl::string& dir,
  2134. kwsys_stl::string& file,
  2135. bool)
  2136. {
  2137. dir = in_name;
  2138. file = "";
  2139. SystemTools::ConvertToUnixSlashes(dir);
  2140. if(!SystemTools::FileIsDirectory(dir.c_str()))
  2141. {
  2142. kwsys_stl::string::size_type slashPos = dir.rfind("/");
  2143. if(slashPos != kwsys_stl::string::npos)
  2144. {
  2145. file = dir.substr(slashPos+1);
  2146. dir = dir.substr(0, slashPos);
  2147. }
  2148. else
  2149. {
  2150. file = dir;
  2151. dir = "";
  2152. }
  2153. }
  2154. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  2155. {
  2156. kwsys_stl::string oldDir = in_name;
  2157. SystemTools::ConvertToUnixSlashes(oldDir);
  2158. dir = in_name;
  2159. return false;
  2160. }
  2161. return true;
  2162. }
  2163. bool SystemTools::FindProgramPath(const char* argv0,
  2164. kwsys_stl::string& pathOut,
  2165. kwsys_stl::string& errorMsg,
  2166. const char* exeName,
  2167. const char* buildDir,
  2168. const char* installPrefix )
  2169. {
  2170. kwsys_stl::vector<kwsys_stl::string> failures;
  2171. kwsys_stl::string self = argv0 ? argv0 : "";
  2172. failures.push_back(self);
  2173. SystemTools::ConvertToUnixSlashes(self);
  2174. self = SystemTools::FindProgram(self.c_str());
  2175. if(!SystemTools::FileExists(self.c_str()))
  2176. {
  2177. if(buildDir)
  2178. {
  2179. kwsys_stl::string intdir = ".";
  2180. #ifdef CMAKE_INTDIR
  2181. intdir = CMAKE_INTDIR;
  2182. #endif
  2183. self = buildDir;
  2184. self += "/bin/";
  2185. self += intdir;
  2186. self += "/";
  2187. self += exeName;
  2188. self += SystemTools::GetExecutableExtension();
  2189. }
  2190. }
  2191. if(installPrefix)
  2192. {
  2193. if(!SystemTools::FileExists(self.c_str()))
  2194. {
  2195. failures.push_back(self);
  2196. self = installPrefix;
  2197. self += "/bin/";
  2198. self += exeName;
  2199. }
  2200. }
  2201. if(!SystemTools::FileExists(self.c_str()))
  2202. {
  2203. failures.push_back(self);
  2204. kwsys_ios::ostringstream msg;
  2205. msg << "Can not find the command line program ";
  2206. if (exeName)
  2207. {
  2208. msg << exeName;
  2209. }
  2210. msg << "\n";
  2211. if (argv0)
  2212. {
  2213. msg << " argv[0] = \"" << argv0 << "\"\n";
  2214. }
  2215. msg << " Attempted paths:\n";
  2216. kwsys_stl::vector<kwsys_stl::string>::iterator i;
  2217. for(i=failures.begin(); i != failures.end(); ++i)
  2218. {
  2219. msg << " \"" << i->c_str() << "\"\n";
  2220. }
  2221. errorMsg = msg.str();
  2222. return false;
  2223. }
  2224. pathOut = self;
  2225. return true;
  2226. }
  2227. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
  2228. {
  2229. return SystemTools::CollapseFullPath(in_relative, 0);
  2230. }
  2231. void SystemTools::AddTranslationPath(const char * a, const char * b)
  2232. {
  2233. kwsys_stl::string path_a = a;
  2234. kwsys_stl::string path_b = b;
  2235. SystemTools::ConvertToUnixSlashes(path_a);
  2236. SystemTools::ConvertToUnixSlashes(path_b);
  2237. // First check this is a directory path, since we don't want the table to
  2238. // grow too fat
  2239. if( SystemTools::FileIsDirectory( path_a.c_str() ) )
  2240. {
  2241. // Make sure the path is a full path and does not contain no '..'
  2242. if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
  2243. == kwsys_stl::string::npos )
  2244. {
  2245. // Before inserting make sure path ends with '/'
  2246. if(path_a.size() && path_a[path_a.size() -1] != '/')
  2247. {
  2248. path_a += '/';
  2249. }
  2250. if(path_b.size() && path_b[path_b.size() -1] != '/')
  2251. {
  2252. path_b += '/';
  2253. }
  2254. if( !(path_a == path_b) )
  2255. {
  2256. SystemTools::TranslationMap->insert(
  2257. SystemToolsTranslationMap::value_type(path_a, path_b));
  2258. }
  2259. }
  2260. }
  2261. }
  2262. void SystemTools::AddKeepPath(const char* dir)
  2263. {
  2264. kwsys_stl::string cdir;
  2265. Realpath(SystemTools::CollapseFullPath(dir).c_str(), cdir);
  2266. SystemTools::AddTranslationPath(cdir.c_str(), dir);
  2267. }
  2268. void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
  2269. {
  2270. // Do not translate paths that are too short to have meaningful
  2271. // translations.
  2272. if(path.size() < 2)
  2273. {
  2274. return;
  2275. }
  2276. // Always add a trailing slash before translation. It does not
  2277. // matter if this adds an extra slash, but we do not want to
  2278. // translate part of a directory (like the foo part of foo-dir).
  2279. path += "/";
  2280. // In case a file was specified we still have to go through this:
  2281. // Now convert any path found in the table back to the one desired:
  2282. kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
  2283. for(it = SystemTools::TranslationMap->begin();
  2284. it != SystemTools::TranslationMap->end();
  2285. ++it )
  2286. {
  2287. // We need to check of the path is a substring of the other path
  2288. if(path.find( it->first ) == 0)
  2289. {
  2290. path = path.replace( 0, it->first.size(), it->second);
  2291. }
  2292. }
  2293. // Remove the trailing slash we added before.
  2294. path.erase(path.end()-1, path.end());
  2295. }
  2296. void
  2297. SystemToolsAppendComponents(
  2298. kwsys_stl::vector<kwsys_stl::string>& out_components,
  2299. kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
  2300. kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
  2301. {
  2302. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = first;
  2303. i != last; ++i)
  2304. {
  2305. if(*i == "..")
  2306. {
  2307. if(out_components.begin() != out_components.end())
  2308. {
  2309. out_components.erase(out_components.end()-1, out_components.end());
  2310. }
  2311. }
  2312. else if(!(*i == ".") && !(*i == ""))
  2313. {
  2314. out_components.push_back(*i);
  2315. }
  2316. }
  2317. }
  2318. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_path,
  2319. const char* in_base)
  2320. {
  2321. // Collect the output path components.
  2322. kwsys_stl::vector<kwsys_stl::string> out_components;
  2323. // Split the input path components.
  2324. kwsys_stl::vector<kwsys_stl::string> path_components;
  2325. SystemTools::SplitPath(in_path, path_components);
  2326. // If the input path is relative, start with a base path.
  2327. if(path_components[0].length() == 0)
  2328. {
  2329. kwsys_stl::vector<kwsys_stl::string> base_components;
  2330. if(in_base)
  2331. {
  2332. // Use the given base path.
  2333. SystemTools::SplitPath(in_base, base_components);
  2334. }
  2335. else
  2336. {
  2337. // Use the current working directory as a base path.
  2338. char buf[2048];
  2339. if(const char* cwd = Getcwd(buf, 2048))
  2340. {
  2341. SystemTools::SplitPath(cwd, base_components);
  2342. }
  2343. else
  2344. {
  2345. // ??
  2346. }
  2347. }
  2348. // Append base path components to the output path.
  2349. out_components.push_back(base_components[0]);
  2350. SystemToolsAppendComponents(out_components,
  2351. base_components.begin()+1,
  2352. base_components.end());
  2353. }
  2354. // Append input path components to the output path.
  2355. SystemToolsAppendComponents(out_components,
  2356. path_components.begin(),
  2357. path_components.end());
  2358. // Transform the path back to a string.
  2359. kwsys_stl::string newPath = SystemTools::JoinPath(out_components);
  2360. // Update the translation table with this potentially new path.
  2361. SystemTools::AddTranslationPath(newPath.c_str(), in_path);
  2362. SystemTools::CheckTranslationPath(newPath);
  2363. #ifdef _WIN32
  2364. newPath = SystemTools::GetActualCaseForPath(newPath.c_str());
  2365. SystemTools::ConvertToUnixSlashes(newPath);
  2366. #endif
  2367. // Return the reconstructed path.
  2368. return newPath;
  2369. }
  2370. // compute the relative path from here to there
  2371. kwsys_stl::string SystemTools::RelativePath(const char* local, const char* remote)
  2372. {
  2373. if(!SystemTools::FileIsFullPath(local))
  2374. {
  2375. return "";
  2376. }
  2377. if(!SystemTools::FileIsFullPath(remote))
  2378. {
  2379. return "";
  2380. }
  2381. // split up both paths into arrays of strings using / as a separator
  2382. kwsys_stl::vector<kwsys::String> localSplit = SystemTools::SplitString(local, '/', true);
  2383. kwsys_stl::vector<kwsys::String> remoteSplit = SystemTools::SplitString(remote, '/', true);
  2384. kwsys_stl::vector<kwsys::String> commonPath; // store shared parts of path in this array
  2385. kwsys_stl::vector<kwsys::String> finalPath; // store the final relative path here
  2386. // count up how many matching directory names there are from the start
  2387. unsigned int sameCount = 0;
  2388. while(
  2389. ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1)))
  2390. &&
  2391. // for windows and apple do a case insensitive string compare
  2392. #if defined(_WIN32) || defined(__APPLE__)
  2393. SystemTools::Strucmp(localSplit[sameCount].c_str(),
  2394. remoteSplit[sameCount].c_str()) == 0
  2395. #else
  2396. localSplit[sameCount] == remoteSplit[sameCount]
  2397. #endif
  2398. )
  2399. {
  2400. // put the common parts of the path into the commonPath array
  2401. commonPath.push_back(localSplit[sameCount]);
  2402. // erase the common parts of the path from the original path arrays
  2403. localSplit[sameCount] = "";
  2404. remoteSplit[sameCount] = "";
  2405. sameCount++;
  2406. }
  2407. // If there is nothing in common but the root directory, then just
  2408. // return the full path.
  2409. if(sameCount <= 1)
  2410. {
  2411. return remote;
  2412. }
  2413. // for each entry that is not common in the local path
  2414. // add a ../ to the finalpath array, this gets us out of the local
  2415. // path into the remote dir
  2416. for(unsigned int i = 0; i < localSplit.size(); ++i)
  2417. {
  2418. if(localSplit[i].size())
  2419. {
  2420. finalPath.push_back("../");
  2421. }
  2422. }
  2423. // for each entry that is not common in the remote path add it
  2424. // to the final path.
  2425. for(kwsys_stl::vector<String>::iterator vit = remoteSplit.begin();
  2426. vit != remoteSplit.end(); ++vit)
  2427. {
  2428. if(vit->size())
  2429. {
  2430. finalPath.push_back(*vit);
  2431. }
  2432. }
  2433. kwsys_stl::string relativePath; // result string
  2434. // now turn the array of directories into a unix path by puttint /
  2435. // between each entry that does not already have one
  2436. for(kwsys_stl::vector<String>::iterator vit1 = finalPath.begin();
  2437. vit1 != finalPath.end(); ++vit1)
  2438. {
  2439. if(relativePath.size() && relativePath[relativePath.size()-1] != '/')
  2440. {
  2441. relativePath += "/";
  2442. }
  2443. relativePath += *vit1;
  2444. }
  2445. return relativePath;
  2446. }
  2447. // OK, some fun stuff to get the actual case of a given path.
  2448. // Basically, you just need to call ShortPath, then GetLongPathName,
  2449. // However, GetLongPathName is not implemented on windows NT and 95,
  2450. // so we have to simulate it on those versions
  2451. #ifdef _WIN32
  2452. int OldWindowsGetLongPath(kwsys_stl::string const& shortPath,
  2453. kwsys_stl::string& longPath )
  2454. {
  2455. kwsys_stl::string::size_type iFound = shortPath.rfind('/');
  2456. if (iFound > 1 && iFound != shortPath.npos)
  2457. {
  2458. // recurse to peel off components
  2459. //
  2460. if (OldWindowsGetLongPath(shortPath.substr(0, iFound), longPath) > 0)
  2461. {
  2462. longPath += '/';
  2463. if (shortPath[1] != '/')
  2464. {
  2465. WIN32_FIND_DATA findData;
  2466. // append the long component name to the path
  2467. //
  2468. if (INVALID_HANDLE_VALUE != ::FindFirstFile
  2469. (shortPath.c_str(), &findData))
  2470. {
  2471. longPath += findData.cFileName;
  2472. }
  2473. else
  2474. {
  2475. // if FindFirstFile fails, return the error code
  2476. //
  2477. longPath = "";
  2478. return 0;
  2479. }
  2480. }
  2481. }
  2482. }
  2483. else
  2484. {
  2485. longPath = shortPath;
  2486. }
  2487. return (int)longPath.size();
  2488. }
  2489. int PortableGetLongPathName(const char* pathIn,
  2490. kwsys_stl::string & longPath)
  2491. {
  2492. HMODULE lh = LoadLibrary("Kernel32.dll");
  2493. if(lh)
  2494. {
  2495. FARPROC proc = GetProcAddress(lh, "GetLongPathNameA");
  2496. if(proc)
  2497. {
  2498. typedef DWORD (WINAPI * GetLongFunctionPtr) (LPCSTR,LPSTR,DWORD);
  2499. GetLongFunctionPtr func = (GetLongFunctionPtr)proc;
  2500. char buffer[MAX_PATH+1];
  2501. int len = (*func)(pathIn, buffer, MAX_PATH+1);
  2502. if(len == 0 || len > MAX_PATH+1)
  2503. {
  2504. FreeLibrary(lh);
  2505. return 0;
  2506. }
  2507. longPath = buffer;
  2508. FreeLibrary(lh);
  2509. return len;
  2510. }
  2511. FreeLibrary(lh);
  2512. }
  2513. return OldWindowsGetLongPath(pathIn, longPath);
  2514. }
  2515. #endif
  2516. //----------------------------------------------------------------------------
  2517. kwsys_stl::string SystemTools::GetActualCaseForPath(const char* p)
  2518. {
  2519. #ifndef _WIN32
  2520. return p;
  2521. #else
  2522. kwsys_stl::string shortPath;
  2523. if(!SystemTools::GetShortPath(p, shortPath))
  2524. {
  2525. return p;
  2526. }
  2527. kwsys_stl::string longPath;
  2528. int len = PortableGetLongPathName(shortPath.c_str(), longPath);
  2529. if(len == 0 || len > MAX_PATH+1)
  2530. {
  2531. return p;
  2532. }
  2533. return longPath;
  2534. #endif
  2535. }
  2536. //----------------------------------------------------------------------------
  2537. void SystemTools::SplitPath(const char* p,
  2538. kwsys_stl::vector<kwsys_stl::string>& components)
  2539. {
  2540. components.clear();
  2541. // Identify the root component.
  2542. const char* c = p;
  2543. if((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\'))
  2544. {
  2545. // Network path.
  2546. components.push_back("//");
  2547. c += 2;
  2548. }
  2549. else if(c[0] == '/')
  2550. {
  2551. // Unix path.
  2552. components.push_back("/");
  2553. c += 1;
  2554. }
  2555. else if(c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\'))
  2556. {
  2557. // Windows path.
  2558. kwsys_stl::string root = "_:/";
  2559. root[0] = c[0];
  2560. components.push_back(root);
  2561. c += 3;
  2562. }
  2563. else if(c[0] && c[1] == ':')
  2564. {
  2565. // Path relative to a windows drive working directory.
  2566. kwsys_stl::string root = "_:";
  2567. root[0] = c[0];
  2568. components.push_back(root);
  2569. c += 2;
  2570. }
  2571. else
  2572. {
  2573. // Relative path.
  2574. components.push_back("");
  2575. }
  2576. // Parse the remaining components.
  2577. const char* first = c;
  2578. const char* last = first;
  2579. for(;*last; ++last)
  2580. {
  2581. if(*last == '/' || *last == '\\')
  2582. {
  2583. // End of a component. Save it.
  2584. components.push_back(kwsys_stl::string(first, last-first));
  2585. first = last+1;
  2586. }
  2587. }
  2588. // Save the last component unless there were no components.
  2589. if(last != c)
  2590. {
  2591. components.push_back(kwsys_stl::string(first, last-first));
  2592. }
  2593. }
  2594. //----------------------------------------------------------------------------
  2595. kwsys_stl::string
  2596. SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components)
  2597. {
  2598. return SystemTools::JoinPath(components.begin(), components.end());
  2599. }
  2600. //----------------------------------------------------------------------------
  2601. kwsys_stl::string
  2602. SystemTools
  2603. ::JoinPath(kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
  2604. kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
  2605. {
  2606. // Construct result in a single string.
  2607. kwsys_stl::string result;
  2608. // The first two components do not add a slash.
  2609. if(first != last)
  2610. {
  2611. result += *first++;
  2612. }
  2613. if(first != last)
  2614. {
  2615. result += *first++;
  2616. }
  2617. // All remaining components are always separated with a slash.
  2618. while(first != last)
  2619. {
  2620. result += "/";
  2621. result += *first++;
  2622. }
  2623. // Return the concatenated result.
  2624. return result;
  2625. }
  2626. //----------------------------------------------------------------------------
  2627. bool SystemTools::ComparePath(const char* c1, const char* c2)
  2628. {
  2629. #if defined(_WIN32) || defined(__APPLE__)
  2630. # ifdef _MSC_VER
  2631. return _stricmp(c1, c2) == 0;
  2632. # elif defined(__APPLE__) || defined(__GNUC__)
  2633. return strcasecmp(c1, c2) == 0;
  2634. #else
  2635. return SystemTools::Strucmp(c1, c2) == 0;
  2636. # endif
  2637. #else
  2638. return strcmp(c1, c2) == 0;
  2639. #endif
  2640. }
  2641. //----------------------------------------------------------------------------
  2642. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines, char separator)
  2643. {
  2644. kwsys_stl::string data(str);
  2645. kwsys_stl::string::size_type lpos = 0;
  2646. while(lpos < data.length())
  2647. {
  2648. kwsys_stl::string::size_type rpos = data.find_first_of(separator, lpos);
  2649. if(rpos == kwsys_stl::string::npos)
  2650. {
  2651. // Line ends at end of string without a newline.
  2652. lines.push_back(data.substr(lpos));
  2653. return false;
  2654. }
  2655. else
  2656. {
  2657. // Line ends in a "\n", remove the character.
  2658. lines.push_back(data.substr(lpos, rpos-lpos));
  2659. }
  2660. lpos = rpos+1;
  2661. }
  2662. return true;
  2663. }
  2664. //----------------------------------------------------------------------------
  2665. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
  2666. {
  2667. kwsys_stl::string data(str);
  2668. kwsys_stl::string::size_type lpos = 0;
  2669. while(lpos < data.length())
  2670. {
  2671. kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
  2672. if(rpos == kwsys_stl::string::npos)
  2673. {
  2674. // Line ends at end of string without a newline.
  2675. lines.push_back(data.substr(lpos));
  2676. return false;
  2677. }
  2678. if((rpos > lpos) && (data[rpos-1] == '\r'))
  2679. {
  2680. // Line ends in a "\r\n" pair, remove both characters.
  2681. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  2682. }
  2683. else
  2684. {
  2685. // Line ends in a "\n", remove the character.
  2686. lines.push_back(data.substr(lpos, rpos-lpos));
  2687. }
  2688. lpos = rpos+1;
  2689. }
  2690. return true;
  2691. }
  2692. /**
  2693. * Return path of a full filename (no trailing slashes).
  2694. * Warning: returned path is converted to Unix slashes format.
  2695. */
  2696. kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
  2697. {
  2698. kwsys_stl::string fn = filename;
  2699. SystemTools::ConvertToUnixSlashes(fn);
  2700. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  2701. if(slash_pos != kwsys_stl::string::npos)
  2702. {
  2703. kwsys_stl::string ret = fn.substr(0, slash_pos);
  2704. if(ret.size() == 2 && ret[1] == ':')
  2705. {
  2706. return ret + '/';
  2707. }
  2708. if(ret.size() == 0)
  2709. {
  2710. return "/";
  2711. }
  2712. return ret;
  2713. }
  2714. else
  2715. {
  2716. return "";
  2717. }
  2718. }
  2719. /**
  2720. * Return file name of a full filename (i.e. file name without path).
  2721. */
  2722. kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
  2723. {
  2724. #if defined(_WIN32)
  2725. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/\\");
  2726. #else
  2727. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/");
  2728. #endif
  2729. if(slash_pos != kwsys_stl::string::npos)
  2730. {
  2731. return filename.substr(slash_pos + 1);
  2732. }
  2733. else
  2734. {
  2735. return filename;
  2736. }
  2737. }
  2738. /**
  2739. * Return file extension of a full filename (dot included).
  2740. * Warning: this is the longest extension (for example: .tar.gz)
  2741. */
  2742. kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
  2743. {
  2744. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2745. kwsys_stl::string::size_type dot_pos = name.find(".");
  2746. if(dot_pos != kwsys_stl::string::npos)
  2747. {
  2748. return name.substr(dot_pos);
  2749. }
  2750. else
  2751. {
  2752. return "";
  2753. }
  2754. }
  2755. /**
  2756. * Return file extension of a full filename (dot included).
  2757. * Warning: this is the shortest extension (for example: .tar.gz)
  2758. */
  2759. kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
  2760. {
  2761. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2762. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2763. if(dot_pos != kwsys_stl::string::npos)
  2764. {
  2765. return name.substr(dot_pos);
  2766. }
  2767. else
  2768. {
  2769. return "";
  2770. }
  2771. }
  2772. /**
  2773. * Return file name without extension of a full filename (i.e. without path).
  2774. * Warning: it considers the longest extension (for example: .tar.gz)
  2775. */
  2776. kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
  2777. {
  2778. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2779. kwsys_stl::string::size_type dot_pos = name.find(".");
  2780. if(dot_pos != kwsys_stl::string::npos)
  2781. {
  2782. return name.substr(0, dot_pos);
  2783. }
  2784. else
  2785. {
  2786. return name;
  2787. }
  2788. }
  2789. /**
  2790. * Return file name without extension of a full filename (i.e. without path).
  2791. * Warning: it considers the last extension (for example: removes .gz
  2792. * from .tar.gz)
  2793. */
  2794. kwsys_stl::string
  2795. SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
  2796. {
  2797. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2798. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2799. if(dot_pos != kwsys_stl::string::npos)
  2800. {
  2801. return name.substr(0, dot_pos);
  2802. }
  2803. else
  2804. {
  2805. return name;
  2806. }
  2807. }
  2808. bool SystemTools::FileHasSignature(const char *filename,
  2809. const char *signature,
  2810. long offset)
  2811. {
  2812. if (!filename || !signature)
  2813. {
  2814. return false;
  2815. }
  2816. FILE *fp;
  2817. fp = fopen(filename, "rb");
  2818. if (!fp)
  2819. {
  2820. return false;
  2821. }
  2822. fseek(fp, offset, SEEK_SET);
  2823. bool res = false;
  2824. size_t signature_len = strlen(signature);
  2825. char *buffer = new char [signature_len];
  2826. if (fread(buffer, 1, signature_len, fp) == signature_len)
  2827. {
  2828. res = (!strncmp(buffer, signature, signature_len) ? true : false);
  2829. }
  2830. delete [] buffer;
  2831. fclose(fp);
  2832. return res;
  2833. }
  2834. SystemTools::FileTypeEnum
  2835. SystemTools::DetectFileType(const char *filename,
  2836. unsigned long length,
  2837. double percent_bin)
  2838. {
  2839. if (!filename || percent_bin < 0)
  2840. {
  2841. return SystemTools::FileTypeUnknown;
  2842. }
  2843. FILE *fp;
  2844. fp = fopen(filename, "rb");
  2845. if (!fp)
  2846. {
  2847. return SystemTools::FileTypeUnknown;
  2848. }
  2849. // Allocate buffer and read bytes
  2850. unsigned char *buffer = new unsigned char [length];
  2851. size_t read_length = fread(buffer, 1, length, fp);
  2852. fclose(fp);
  2853. if (read_length == 0)
  2854. {
  2855. return SystemTools::FileTypeUnknown;
  2856. }
  2857. // Loop over contents and count
  2858. size_t text_count = 0;
  2859. const unsigned char *ptr = buffer;
  2860. const unsigned char *buffer_end = buffer + read_length;
  2861. while (ptr != buffer_end)
  2862. {
  2863. if ((*ptr >= 0x20 && *ptr <= 0x7F) ||
  2864. *ptr == '\n' ||
  2865. *ptr == '\r' ||
  2866. *ptr == '\t')
  2867. {
  2868. text_count++;
  2869. }
  2870. ptr++;
  2871. }
  2872. delete [] buffer;
  2873. double current_percent_bin =
  2874. (static_cast<double>(read_length - text_count) /
  2875. static_cast<double>(read_length));
  2876. if (current_percent_bin >= percent_bin)
  2877. {
  2878. return SystemTools::FileTypeBinary;
  2879. }
  2880. return SystemTools::FileTypeText;
  2881. }
  2882. bool SystemTools::LocateFileInDir(const char *filename,
  2883. const char *dir,
  2884. kwsys_stl::string& filename_found,
  2885. int try_filename_dirs)
  2886. {
  2887. if (!filename || !dir)
  2888. {
  2889. return false;
  2890. }
  2891. // Get the basename of 'filename'
  2892. kwsys_stl::string filename_base = SystemTools::GetFilenameName(filename);
  2893. // Check if 'dir' is really a directory
  2894. // If win32 and matches something like C:, accept it as a dir
  2895. kwsys_stl::string real_dir;
  2896. if (!SystemTools::FileIsDirectory(dir))
  2897. {
  2898. #if defined( _WIN32 )
  2899. size_t dir_len = strlen(dir);
  2900. if (dir_len < 2 || dir[dir_len - 1] != ':')
  2901. {
  2902. #endif
  2903. real_dir = SystemTools::GetFilenamePath(dir);
  2904. dir = real_dir.c_str();
  2905. #if defined( _WIN32 )
  2906. }
  2907. #endif
  2908. }
  2909. // Try to find the file in 'dir'
  2910. bool res = false;
  2911. if (filename_base.size() && dir)
  2912. {
  2913. size_t dir_len = strlen(dir);
  2914. int need_slash =
  2915. (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
  2916. kwsys_stl::string temp = dir;
  2917. if (need_slash)
  2918. {
  2919. temp += "/";
  2920. }
  2921. temp += filename_base;
  2922. if (SystemTools::FileExists(filename_found.c_str()))
  2923. {
  2924. res = true;
  2925. filename_found = temp;
  2926. }
  2927. // If not found, we can try harder by appending part of the file to
  2928. // to the directory to look inside.
  2929. // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
  2930. // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
  2931. else if (try_filename_dirs)
  2932. {
  2933. kwsys_stl::string filename_dir(filename);
  2934. kwsys_stl::string filename_dir_base;
  2935. kwsys_stl::string filename_dir_bases;
  2936. do
  2937. {
  2938. filename_dir = SystemTools::GetFilenamePath(filename_dir);
  2939. filename_dir_base = SystemTools::GetFilenameName(filename_dir);
  2940. #if defined( _WIN32 )
  2941. if (!filename_dir_base.size() ||
  2942. filename_dir_base[filename_dir_base.size() - 1] == ':')
  2943. #else
  2944. if (!filename_dir_base.size())
  2945. #endif
  2946. {
  2947. break;
  2948. }
  2949. filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
  2950. temp = dir;
  2951. if (need_slash)
  2952. {
  2953. temp += "/";
  2954. }
  2955. temp += filename_dir_bases;
  2956. res = SystemTools::LocateFileInDir(
  2957. filename_base.c_str(), temp.c_str(), filename_found, 0);
  2958. } while (!res && filename_dir_base.size());
  2959. }
  2960. }
  2961. return res;
  2962. }
  2963. bool SystemTools::FileIsFullPath(const char* in_name)
  2964. {
  2965. kwsys_stl::string name = in_name;
  2966. #if defined(_WIN32) || defined(__CYGWIN__)
  2967. // On Windows, the name must be at least two characters long.
  2968. if(name.length() < 2)
  2969. {
  2970. return false;
  2971. }
  2972. if(name[1] == ':')
  2973. {
  2974. return true;
  2975. }
  2976. if(name[0] == '\\')
  2977. {
  2978. return true;
  2979. }
  2980. #else
  2981. // On UNIX, the name must be at least one character long.
  2982. if(name.length() < 1)
  2983. {
  2984. return false;
  2985. }
  2986. #endif
  2987. // On UNIX, the name must begin in a '/'.
  2988. // On Windows, if the name begins in a '/', then it is a full
  2989. // network path.
  2990. if(name[0] == '/')
  2991. {
  2992. return true;
  2993. }
  2994. return false;
  2995. }
  2996. bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
  2997. {
  2998. #if defined(WIN32) && !defined(__CYGWIN__)
  2999. const int size = int(strlen(path)) +1; // size of return
  3000. char *buffer = new char[size]; // create a buffer
  3001. char *tempPath = new char[size]; // create a buffer
  3002. int ret;
  3003. // if the path passed in has quotes around it, first remove the quotes
  3004. if (path[0] == '"' && path[strlen(path)-1] == '"')
  3005. {
  3006. strcpy(tempPath,path+1);
  3007. tempPath[strlen(tempPath)-1] = '\0';
  3008. }
  3009. else
  3010. {
  3011. strcpy(tempPath,path);
  3012. }
  3013. buffer[0] = 0;
  3014. ret = GetShortPathName(tempPath, buffer, size);
  3015. if(buffer[0] == 0 || ret > size)
  3016. {
  3017. delete [] buffer;
  3018. delete [] tempPath;
  3019. return false;
  3020. }
  3021. else
  3022. {
  3023. shortPath = buffer;
  3024. delete [] buffer;
  3025. delete [] tempPath;
  3026. return true;
  3027. }
  3028. #else
  3029. shortPath = path;
  3030. return true;
  3031. #endif
  3032. }
  3033. void SystemTools::SplitProgramFromArgs(const char* path,
  3034. kwsys_stl::string& program, kwsys_stl::string& args)
  3035. {
  3036. // see if this is a full path to a program
  3037. // if so then set program to path and args to nothing
  3038. if(SystemTools::FileExists(path))
  3039. {
  3040. program = path;
  3041. args = "";
  3042. return;
  3043. }
  3044. // Try to find the program in the path, note the program
  3045. // may have spaces in its name so we have to look for it
  3046. kwsys_stl::vector<kwsys_stl::string> e;
  3047. kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
  3048. if(findProg.size())
  3049. {
  3050. program = findProg;
  3051. args = "";
  3052. return;
  3053. }
  3054. // Now try and peel off space separated chunks from the end of the string
  3055. // so the largest path possible is found allowing for spaces in the path
  3056. kwsys_stl::string dir = path;
  3057. kwsys_stl::string::size_type spacePos = dir.rfind(' ');
  3058. while(spacePos != kwsys_stl::string::npos)
  3059. {
  3060. kwsys_stl::string tryProg = dir.substr(0, spacePos);
  3061. // See if the file exists
  3062. if(SystemTools::FileExists(tryProg.c_str()))
  3063. {
  3064. program = tryProg;
  3065. // remove trailing spaces from program
  3066. kwsys_stl::string::size_type pos = program.size()-1;
  3067. while(program[pos] == ' ')
  3068. {
  3069. program.erase(pos);
  3070. pos--;
  3071. }
  3072. args = dir.substr(spacePos, dir.size()-spacePos);
  3073. return;
  3074. }
  3075. // Now try and find the the program in the path
  3076. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  3077. if(findProg.size())
  3078. {
  3079. program = findProg;
  3080. // remove trailing spaces from program
  3081. kwsys_stl::string::size_type pos = program.size()-1;
  3082. while(program[pos] == ' ')
  3083. {
  3084. program.erase(pos);
  3085. pos--;
  3086. }
  3087. args = dir.substr(spacePos, dir.size()-spacePos);
  3088. return;
  3089. }
  3090. // move past the space for the next search
  3091. spacePos--;
  3092. spacePos = dir.rfind(' ', spacePos);
  3093. }
  3094. program = "";
  3095. args = "";
  3096. }
  3097. kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
  3098. {
  3099. char buf[1024];
  3100. time_t t;
  3101. time(&t);
  3102. strftime(buf, sizeof(buf), format, localtime(&t));
  3103. return kwsys_stl::string(buf);
  3104. }
  3105. kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
  3106. {
  3107. kwsys_stl::string str(s);
  3108. if (str.find_first_of("0123456789") == 0)
  3109. {
  3110. str = "_" + str;
  3111. }
  3112. kwsys_stl::string permited_chars("_"
  3113. "abcdefghijklmnopqrstuvwxyz"
  3114. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3115. "0123456789");
  3116. kwsys_stl::string::size_type pos = 0;
  3117. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
  3118. {
  3119. str[pos] = '_';
  3120. }
  3121. return str;
  3122. }
  3123. // Due to a buggy stream library on the HP and another on Mac OSX, we
  3124. // need this very carefully written version of getline. Returns true
  3125. // if any data were read before the end-of-file was reached.
  3126. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, kwsys_stl::string& line,
  3127. bool *has_newline /* = 0 */)
  3128. {
  3129. const int bufferSize = 1024;
  3130. char buffer[bufferSize];
  3131. line = "";
  3132. bool haveData = false;
  3133. if ( has_newline )
  3134. {
  3135. *has_newline = false;
  3136. }
  3137. // If no characters are read from the stream, the end of file has
  3138. // been reached.
  3139. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  3140. {
  3141. haveData = true;
  3142. line.append(buffer);
  3143. // If newline character was read, the gcount includes the
  3144. // character, but the buffer does not. The end of line has been
  3145. // reached.
  3146. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  3147. {
  3148. if ( has_newline )
  3149. {
  3150. *has_newline = true;
  3151. }
  3152. break;
  3153. }
  3154. // The fail bit may be set. Clear it.
  3155. is.clear(is.rdstate() & ~kwsys_ios::ios::failbit);
  3156. }
  3157. return haveData;
  3158. }
  3159. int SystemTools::GetTerminalWidth()
  3160. {
  3161. int width = -1;
  3162. #ifndef _WIN32
  3163. struct winsize ws;
  3164. char *columns; /* Unix98 environment variable */
  3165. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  3166. {
  3167. width = ws.ws_col;
  3168. }
  3169. if(!isatty(STDOUT_FILENO))
  3170. {
  3171. width = -1;
  3172. }
  3173. columns = getenv("COLUMNS");
  3174. if(columns && *columns)
  3175. {
  3176. long t;
  3177. char *endptr;
  3178. t = strtol(columns, &endptr, 0);
  3179. if(endptr && !*endptr && (t>0) && (t<1000))
  3180. {
  3181. width = static_cast<int>(t);
  3182. }
  3183. }
  3184. if ( width < 9 )
  3185. {
  3186. width = -1;
  3187. }
  3188. #endif
  3189. return width;
  3190. }
  3191. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  3192. {
  3193. if ( !file )
  3194. {
  3195. return false;
  3196. }
  3197. struct stat st;
  3198. if ( stat(file, &st) < 0 )
  3199. {
  3200. return false;
  3201. }
  3202. mode = st.st_mode;
  3203. return true;
  3204. }
  3205. bool SystemTools::SetPermissions(const char* file, mode_t mode)
  3206. {
  3207. if ( !file )
  3208. {
  3209. return false;
  3210. }
  3211. if ( !SystemTools::FileExists(file) )
  3212. {
  3213. return false;
  3214. }
  3215. if ( chmod(file, mode) < 0 )
  3216. {
  3217. return false;
  3218. }
  3219. return true;
  3220. }
  3221. kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
  3222. {
  3223. if ( !fileOrDir || !*fileOrDir )
  3224. {
  3225. return "";
  3226. }
  3227. kwsys_stl::string res = fileOrDir;
  3228. SystemTools::ConvertToUnixSlashes(res);
  3229. kwsys_stl::string::size_type cc = res.size()-1;
  3230. if ( res[cc] == '/' )
  3231. {
  3232. cc --;
  3233. }
  3234. for ( ; cc > 0; cc -- )
  3235. {
  3236. if ( res[cc] == '/' )
  3237. {
  3238. break;
  3239. }
  3240. }
  3241. return res.substr(0, cc);
  3242. }
  3243. bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
  3244. {
  3245. kwsys_stl::string subdir = cSubdir;
  3246. kwsys_stl::string dir = cDir;
  3247. SystemTools::ConvertToUnixSlashes(dir);
  3248. kwsys_stl::string path = subdir;
  3249. do
  3250. {
  3251. path = SystemTools::GetParentDirectory(path.c_str());
  3252. if(SystemTools::ComparePath(dir.c_str(), path.c_str()))
  3253. {
  3254. return true;
  3255. }
  3256. }
  3257. while ( path.size() > dir.size() );
  3258. return false;
  3259. }
  3260. kwsys_stl::string SystemTools::FileExistsInParentDirectories(const char* fname,
  3261. const char* directory, const char* toplevel)
  3262. {
  3263. kwsys_stl::string file = fname;
  3264. SystemTools::ConvertToUnixSlashes(file);
  3265. kwsys_stl::string dir = directory;
  3266. SystemTools::ConvertToUnixSlashes(dir);
  3267. while ( !dir.empty() )
  3268. {
  3269. kwsys_stl::string path = dir + "/" + file;
  3270. if ( SystemTools::FileExists(path.c_str()) )
  3271. {
  3272. return path;
  3273. }
  3274. if ( dir.size() < strlen(toplevel) )
  3275. {
  3276. break;
  3277. }
  3278. dir = SystemTools::GetParentDirectory(dir.c_str());
  3279. }
  3280. return "";
  3281. }
  3282. void SystemTools::Delay(unsigned int msec)
  3283. {
  3284. #ifdef _WIN32
  3285. Sleep(msec);
  3286. #else
  3287. // The sleep function gives 1 second resolution and the usleep
  3288. // function gives 1e-6 second resolution but on some platforms has a
  3289. // maximum sleep time of 1 second. This could be re-implemented to
  3290. // use select with masked signals or pselect to mask signals
  3291. // atomically. If select is given empty sets and zero as the max
  3292. // file descriptor but a non-zero timeout it can be used to block
  3293. // for a precise amount of time.
  3294. if(msec >= 1000)
  3295. {
  3296. sleep(msec / 1000);
  3297. usleep((msec % 1000) * 1000);
  3298. }
  3299. else
  3300. {
  3301. usleep(msec * 1000);
  3302. }
  3303. #endif
  3304. }
  3305. void SystemTools::ConvertWindowsCommandLineToUnixArguments(
  3306. const char *cmd_line, int *argc, char ***argv)
  3307. {
  3308. if (!cmd_line || !argc || !argv)
  3309. {
  3310. return;
  3311. }
  3312. // A space delimites an argument except when it is inside a quote
  3313. (*argc) = 1;
  3314. size_t cmd_line_len = strlen(cmd_line);
  3315. size_t i;
  3316. for (i = 0; i < cmd_line_len; i++)
  3317. {
  3318. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3319. {
  3320. i++;
  3321. }
  3322. if (i < cmd_line_len)
  3323. {
  3324. if (cmd_line[i] == '\"')
  3325. {
  3326. i++;
  3327. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3328. {
  3329. i++;
  3330. }
  3331. (*argc)++;
  3332. }
  3333. else
  3334. {
  3335. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3336. {
  3337. i++;
  3338. }
  3339. (*argc)++;
  3340. }
  3341. }
  3342. }
  3343. (*argv) = new char* [(*argc) + 1];
  3344. (*argv)[(*argc)] = NULL;
  3345. // Set the first arg to be the exec name
  3346. (*argv)[0] = new char [1024];
  3347. #ifdef _WIN32
  3348. ::GetModuleFileName(0, (*argv)[0], 1024);
  3349. #else
  3350. (*argv)[0][0] = '\0';
  3351. #endif
  3352. // Allocate the others
  3353. int j;
  3354. for (j = 1; j < (*argc); j++)
  3355. {
  3356. (*argv)[j] = new char [cmd_line_len + 10];
  3357. }
  3358. // Grab the args
  3359. size_t pos;
  3360. int argc_idx = 1;
  3361. for (i = 0; i < cmd_line_len; i++)
  3362. {
  3363. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3364. {
  3365. i++;
  3366. }
  3367. if (i < cmd_line_len)
  3368. {
  3369. if (cmd_line[i] == '\"')
  3370. {
  3371. i++;
  3372. pos = i;
  3373. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3374. {
  3375. i++;
  3376. }
  3377. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3378. (*argv)[argc_idx][i - pos] = '\0';
  3379. argc_idx++;
  3380. }
  3381. else
  3382. {
  3383. pos = i;
  3384. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3385. {
  3386. i++;
  3387. }
  3388. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3389. (*argv)[argc_idx][i - pos] = '\0';
  3390. argc_idx++;
  3391. }
  3392. }
  3393. }
  3394. }
  3395. kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
  3396. {
  3397. kwsys_stl::string res;
  3398. #ifdef _WIN32
  3399. char buffer[256];
  3400. OSVERSIONINFOEX osvi;
  3401. BOOL bOsVersionInfoEx;
  3402. // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
  3403. // If that fails, try using the OSVERSIONINFO structure.
  3404. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  3405. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  3406. bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi);
  3407. if (!bOsVersionInfoEx)
  3408. {
  3409. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  3410. if (!GetVersionEx((OSVERSIONINFO *)&osvi))
  3411. {
  3412. return 0;
  3413. }
  3414. }
  3415. switch (osvi.dwPlatformId)
  3416. {
  3417. // Test for the Windows NT product family.
  3418. case VER_PLATFORM_WIN32_NT:
  3419. // Test for the specific product family.
  3420. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  3421. {
  3422. res += "Microsoft Windows Server 2003 family";
  3423. }
  3424. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  3425. {
  3426. res += "Microsoft Windows XP";
  3427. }
  3428. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  3429. {
  3430. res += "Microsoft Windows 2000";
  3431. }
  3432. if (osvi.dwMajorVersion <= 4)
  3433. {
  3434. res += "Microsoft Windows NT";
  3435. }
  3436. // Test for specific product on Windows NT 4.0 SP6 and later.
  3437. if (bOsVersionInfoEx)
  3438. {
  3439. // Test for the workstation type.
  3440. #if (_MSC_VER >= 1300)
  3441. if (osvi.wProductType == VER_NT_WORKSTATION)
  3442. {
  3443. if (osvi.dwMajorVersion == 4)
  3444. {
  3445. res += " Workstation 4.0";
  3446. }
  3447. else if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
  3448. {
  3449. res += " Home Edition";
  3450. }
  3451. else
  3452. {
  3453. res += " Professional";
  3454. }
  3455. }
  3456. // Test for the server type.
  3457. else if (osvi.wProductType == VER_NT_SERVER)
  3458. {
  3459. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  3460. {
  3461. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  3462. {
  3463. res += " Datacenter Edition";
  3464. }
  3465. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3466. {
  3467. res += " Enterprise Edition";
  3468. }
  3469. else if (osvi.wSuiteMask == VER_SUITE_BLADE)
  3470. {
  3471. res += " Web Edition";
  3472. }
  3473. else
  3474. {
  3475. res += " Standard Edition";
  3476. }
  3477. }
  3478. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  3479. {
  3480. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  3481. {
  3482. res += " Datacenter Server";
  3483. }
  3484. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3485. {
  3486. res += " Advanced Server";
  3487. }
  3488. else
  3489. {
  3490. res += " Server";
  3491. }
  3492. }
  3493. else // Windows NT 4.0
  3494. {
  3495. if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3496. {
  3497. res += " Server 4.0, Enterprise Edition";
  3498. }
  3499. else
  3500. {
  3501. res += " Server 4.0";
  3502. }
  3503. }
  3504. }
  3505. #endif // Visual Studio 7 and up
  3506. }
  3507. // Test for specific product on Windows NT 4.0 SP5 and earlier
  3508. else
  3509. {
  3510. HKEY hKey;
  3511. #define BUFSIZE 80
  3512. char szProductType[BUFSIZE];
  3513. DWORD dwBufLen=BUFSIZE;
  3514. LONG lRet;
  3515. lRet = RegOpenKeyEx(
  3516. HKEY_LOCAL_MACHINE,
  3517. "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
  3518. 0, KEY_QUERY_VALUE, &hKey);
  3519. if (lRet != ERROR_SUCCESS)
  3520. {
  3521. return 0;
  3522. }
  3523. lRet = RegQueryValueEx(hKey, "ProductType", NULL, NULL,
  3524. (LPBYTE) szProductType, &dwBufLen);
  3525. if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))
  3526. {
  3527. return 0;
  3528. }
  3529. RegCloseKey(hKey);
  3530. if (lstrcmpi("WINNT", szProductType) == 0)
  3531. {
  3532. res += " Workstation";
  3533. }
  3534. if (lstrcmpi("LANMANNT", szProductType) == 0)
  3535. {
  3536. res += " Server";
  3537. }
  3538. if (lstrcmpi("SERVERNT", szProductType) == 0)
  3539. {
  3540. res += " Advanced Server";
  3541. }
  3542. res += " ";
  3543. sprintf(buffer, "%d", osvi.dwMajorVersion);
  3544. res += buffer;
  3545. res += ".";
  3546. sprintf(buffer, "%d", osvi.dwMinorVersion);
  3547. res += buffer;
  3548. }
  3549. // Display service pack (if any) and build number.
  3550. if (osvi.dwMajorVersion == 4 &&
  3551. lstrcmpi(osvi.szCSDVersion, "Service Pack 6") == 0)
  3552. {
  3553. HKEY hKey;
  3554. LONG lRet;
  3555. // Test for SP6 versus SP6a.
  3556. lRet = RegOpenKeyEx(
  3557. HKEY_LOCAL_MACHINE,
  3558. "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
  3559. 0, KEY_QUERY_VALUE, &hKey);
  3560. if (lRet == ERROR_SUCCESS)
  3561. {
  3562. res += " Service Pack 6a (Build ";
  3563. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3564. res += buffer;
  3565. res += ")";
  3566. }
  3567. else // Windows NT 4.0 prior to SP6a
  3568. {
  3569. res += " ";
  3570. res += osvi.szCSDVersion;
  3571. res += " (Build ";
  3572. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3573. res += buffer;
  3574. res += ")";
  3575. }
  3576. RegCloseKey(hKey);
  3577. }
  3578. else // Windows NT 3.51 and earlier or Windows 2000 and later
  3579. {
  3580. res += " ";
  3581. res += osvi.szCSDVersion;
  3582. res += " (Build ";
  3583. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3584. res += buffer;
  3585. res += ")";
  3586. }
  3587. break;
  3588. // Test for the Windows 95 product family.
  3589. case VER_PLATFORM_WIN32_WINDOWS:
  3590. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
  3591. {
  3592. res += "Microsoft Windows 95";
  3593. if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
  3594. {
  3595. res += " OSR2";
  3596. }
  3597. }
  3598. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
  3599. {
  3600. res += "Microsoft Windows 98";
  3601. if (osvi.szCSDVersion[1] == 'A')
  3602. {
  3603. res += " SE";
  3604. }
  3605. }
  3606. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
  3607. {
  3608. res += "Microsoft Windows Millennium Edition";
  3609. }
  3610. break;
  3611. case VER_PLATFORM_WIN32s:
  3612. res += "Microsoft Win32s";
  3613. break;
  3614. }
  3615. #endif
  3616. return res;
  3617. }
  3618. // These must NOT be initialized. Default initialization to zero is
  3619. // necessary.
  3620. unsigned int SystemToolsManagerCount;
  3621. SystemToolsTranslationMap *SystemTools::TranslationMap;
  3622. // SystemToolsManager manages the SystemTools singleton.
  3623. // SystemToolsManager should be included in any translation unit
  3624. // that will use SystemTools or that implements the singleton
  3625. // pattern. It makes sure that the SystemTools singleton is created
  3626. // before and destroyed after all other singletons in CMake.
  3627. SystemToolsManager::SystemToolsManager()
  3628. {
  3629. if(++SystemToolsManagerCount == 1)
  3630. {
  3631. SystemTools::ClassInitialize();
  3632. }
  3633. }
  3634. SystemToolsManager::~SystemToolsManager()
  3635. {
  3636. if(--SystemToolsManagerCount == 0)
  3637. {
  3638. SystemTools::ClassFinalize();
  3639. }
  3640. }
  3641. void SystemTools::ClassInitialize()
  3642. {
  3643. // Allocate the translation map first.
  3644. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  3645. // Add some special translation paths for unix. These are not added
  3646. // for windows because drive letters need to be maintained. Also,
  3647. // there are not sym-links and mount points on windows anyway.
  3648. #if !defined(_WIN32) || defined(__CYGWIN__)
  3649. // Work-around an SGI problem by always adding this mapping:
  3650. SystemTools::AddTranslationPath("/tmp_mnt/", "/");
  3651. // The tmp path is frequently a logical path so always keep it:
  3652. SystemTools::AddKeepPath("/tmp/");
  3653. // If the current working directory is a logical path then keep the
  3654. // logical name.
  3655. if(const char* pwd = getenv("PWD"))
  3656. {
  3657. char buf[2048];
  3658. if(const char* cwd = Getcwd(buf, 2048))
  3659. {
  3660. // The current working directory may be a logical path. Find
  3661. // the shortest logical path that still produces the correct
  3662. // physical path.
  3663. kwsys_stl::string cwd_changed;
  3664. kwsys_stl::string pwd_changed;
  3665. // Test progressively shorter logical-to-physical mappings.
  3666. kwsys_stl::string pwd_str = pwd;
  3667. kwsys_stl::string cwd_str = cwd;
  3668. kwsys_stl::string pwd_path;
  3669. Realpath(pwd, pwd_path);
  3670. while(cwd_str == pwd_path && cwd_str != pwd_str)
  3671. {
  3672. // The current pair of paths is a working logical mapping.
  3673. cwd_changed = cwd_str;
  3674. pwd_changed = pwd_str;
  3675. // Strip off one directory level and see if the logical
  3676. // mapping still works.
  3677. pwd_str = SystemTools::GetFilenamePath(pwd_str.c_str());
  3678. cwd_str = SystemTools::GetFilenamePath(cwd_str.c_str());
  3679. Realpath(pwd_str.c_str(), pwd_path);
  3680. }
  3681. // Add the translation to keep the logical path name.
  3682. if(!cwd_changed.empty() && !pwd_changed.empty())
  3683. {
  3684. SystemTools::AddTranslationPath(cwd_changed.c_str(),
  3685. pwd_changed.c_str());
  3686. }
  3687. }
  3688. }
  3689. #endif
  3690. }
  3691. void SystemTools::ClassFinalize()
  3692. {
  3693. delete SystemTools::TranslationMap;
  3694. }
  3695. } // namespace KWSYS_NAMESPACE
  3696. #if defined(_MSC_VER) && defined(_DEBUG)
  3697. # include <crtdbg.h>
  3698. # include <stdio.h>
  3699. # include <stdlib.h>
  3700. namespace KWSYS_NAMESPACE
  3701. {
  3702. static int SystemToolsDebugReport(int, char* message, int*)
  3703. {
  3704. fprintf(stderr, message);
  3705. exit(1);
  3706. }
  3707. void SystemTools::EnableMSVCDebugHook()
  3708. {
  3709. if(getenv("DART_TEST_FROM_DART"))
  3710. {
  3711. _CrtSetReportHook(SystemToolsDebugReport);
  3712. }
  3713. }
  3714. } // namespace KWSYS_NAMESPACE
  3715. #else
  3716. namespace KWSYS_NAMESPACE
  3717. {
  3718. void SystemTools::EnableMSVCDebugHook() {}
  3719. } // namespace KWSYS_NAMESPACE
  3720. #endif