SystemTools.cxx 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072
  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. struct stat fs;
  2067. if(stat(name, &fs) == 0)
  2068. {
  2069. #if defined( _WIN32 )
  2070. return ((fs.st_mode & _S_IFDIR) != 0);
  2071. #else
  2072. return S_ISDIR(fs.st_mode);
  2073. #endif
  2074. }
  2075. else
  2076. {
  2077. return false;
  2078. }
  2079. }
  2080. bool SystemTools::FileIsSymlink(const char* name)
  2081. {
  2082. #if defined( _WIN32 )
  2083. (void)name;
  2084. return false;
  2085. #else
  2086. struct stat fs;
  2087. if(lstat(name, &fs) == 0)
  2088. {
  2089. return S_ISLNK(fs.st_mode);
  2090. }
  2091. else
  2092. {
  2093. return false;
  2094. }
  2095. #endif
  2096. }
  2097. int SystemTools::ChangeDirectory(const char *dir)
  2098. {
  2099. return Chdir(dir);
  2100. }
  2101. kwsys_stl::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
  2102. {
  2103. char buf[2048];
  2104. const char* cwd = Getcwd(buf, 2048);
  2105. kwsys_stl::string path;
  2106. if ( cwd )
  2107. {
  2108. path = cwd;
  2109. }
  2110. if(collapse)
  2111. {
  2112. return SystemTools::CollapseFullPath(path.c_str());
  2113. }
  2114. return path;
  2115. }
  2116. kwsys_stl::string SystemTools::GetProgramPath(const char* in_name)
  2117. {
  2118. kwsys_stl::string dir, file;
  2119. SystemTools::SplitProgramPath(in_name, dir, file);
  2120. return dir;
  2121. }
  2122. bool SystemTools::SplitProgramPath(const char* in_name,
  2123. kwsys_stl::string& dir,
  2124. kwsys_stl::string& file,
  2125. bool)
  2126. {
  2127. dir = in_name;
  2128. file = "";
  2129. SystemTools::ConvertToUnixSlashes(dir);
  2130. if(!SystemTools::FileIsDirectory(dir.c_str()))
  2131. {
  2132. kwsys_stl::string::size_type slashPos = dir.rfind("/");
  2133. if(slashPos != kwsys_stl::string::npos)
  2134. {
  2135. file = dir.substr(slashPos+1);
  2136. dir = dir.substr(0, slashPos);
  2137. }
  2138. else
  2139. {
  2140. file = dir;
  2141. dir = "";
  2142. }
  2143. }
  2144. if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
  2145. {
  2146. kwsys_stl::string oldDir = in_name;
  2147. SystemTools::ConvertToUnixSlashes(oldDir);
  2148. dir = in_name;
  2149. return false;
  2150. }
  2151. return true;
  2152. }
  2153. bool SystemTools::FindProgramPath(const char* argv0,
  2154. kwsys_stl::string& pathOut,
  2155. kwsys_stl::string& errorMsg,
  2156. const char* exeName,
  2157. const char* buildDir,
  2158. const char* installPrefix )
  2159. {
  2160. kwsys_stl::vector<kwsys_stl::string> failures;
  2161. kwsys_stl::string self = argv0 ? argv0 : "";
  2162. failures.push_back(self);
  2163. SystemTools::ConvertToUnixSlashes(self);
  2164. self = SystemTools::FindProgram(self.c_str());
  2165. if(!SystemTools::FileExists(self.c_str()))
  2166. {
  2167. if(buildDir)
  2168. {
  2169. kwsys_stl::string intdir = ".";
  2170. #ifdef CMAKE_INTDIR
  2171. intdir = CMAKE_INTDIR;
  2172. #endif
  2173. self = buildDir;
  2174. self += "/bin/";
  2175. self += intdir;
  2176. self += "/";
  2177. self += exeName;
  2178. self += SystemTools::GetExecutableExtension();
  2179. }
  2180. }
  2181. if(installPrefix)
  2182. {
  2183. if(!SystemTools::FileExists(self.c_str()))
  2184. {
  2185. failures.push_back(self);
  2186. self = installPrefix;
  2187. self += "/bin/";
  2188. self += exeName;
  2189. }
  2190. }
  2191. if(!SystemTools::FileExists(self.c_str()))
  2192. {
  2193. failures.push_back(self);
  2194. kwsys_ios::ostringstream msg;
  2195. msg << "Can not find the command line program ";
  2196. if (exeName)
  2197. {
  2198. msg << exeName;
  2199. }
  2200. msg << "\n";
  2201. if (argv0)
  2202. {
  2203. msg << " argv[0] = \"" << argv0 << "\"\n";
  2204. }
  2205. msg << " Attempted paths:\n";
  2206. kwsys_stl::vector<kwsys_stl::string>::iterator i;
  2207. for(i=failures.begin(); i != failures.end(); ++i)
  2208. {
  2209. msg << " \"" << i->c_str() << "\"\n";
  2210. }
  2211. errorMsg = msg.str();
  2212. return false;
  2213. }
  2214. pathOut = self;
  2215. return true;
  2216. }
  2217. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_relative)
  2218. {
  2219. return SystemTools::CollapseFullPath(in_relative, 0);
  2220. }
  2221. void SystemTools::AddTranslationPath(const char * a, const char * b)
  2222. {
  2223. kwsys_stl::string path_a = a;
  2224. kwsys_stl::string path_b = b;
  2225. SystemTools::ConvertToUnixSlashes(path_a);
  2226. SystemTools::ConvertToUnixSlashes(path_b);
  2227. // First check this is a directory path, since we don't want the table to
  2228. // grow too fat
  2229. if( SystemTools::FileIsDirectory( path_a.c_str() ) )
  2230. {
  2231. // Make sure the path is a full path and does not contain no '..'
  2232. if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
  2233. == kwsys_stl::string::npos )
  2234. {
  2235. // Before inserting make sure path ends with '/'
  2236. if(path_a.size() && path_a[path_a.size() -1] != '/')
  2237. {
  2238. path_a += '/';
  2239. }
  2240. if(path_b.size() && path_b[path_b.size() -1] != '/')
  2241. {
  2242. path_b += '/';
  2243. }
  2244. if( !(path_a == path_b) )
  2245. {
  2246. SystemTools::TranslationMap->insert(
  2247. SystemToolsTranslationMap::value_type(path_a, path_b));
  2248. }
  2249. }
  2250. }
  2251. }
  2252. void SystemTools::AddKeepPath(const char* dir)
  2253. {
  2254. kwsys_stl::string cdir;
  2255. Realpath(SystemTools::CollapseFullPath(dir).c_str(), cdir);
  2256. SystemTools::AddTranslationPath(cdir.c_str(), dir);
  2257. }
  2258. void SystemTools::CheckTranslationPath(kwsys_stl::string & path)
  2259. {
  2260. // Do not translate paths that are too short to have meaningful
  2261. // translations.
  2262. if(path.size() < 2)
  2263. {
  2264. return;
  2265. }
  2266. // Always add a trailing slash before translation. It does not
  2267. // matter if this adds an extra slash, but we do not want to
  2268. // translate part of a directory (like the foo part of foo-dir).
  2269. path += "/";
  2270. // In case a file was specified we still have to go through this:
  2271. // Now convert any path found in the table back to the one desired:
  2272. kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>::const_iterator it;
  2273. for(it = SystemTools::TranslationMap->begin();
  2274. it != SystemTools::TranslationMap->end();
  2275. ++it )
  2276. {
  2277. // We need to check of the path is a substring of the other path
  2278. if(path.find( it->first ) == 0)
  2279. {
  2280. path = path.replace( 0, it->first.size(), it->second);
  2281. }
  2282. }
  2283. // Remove the trailing slash we added before.
  2284. path.erase(path.end()-1, path.end());
  2285. }
  2286. void
  2287. SystemToolsAppendComponents(
  2288. kwsys_stl::vector<kwsys_stl::string>& out_components,
  2289. kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
  2290. kwsys_stl::vector<kwsys_stl::string>::const_iterator last)
  2291. {
  2292. for(kwsys_stl::vector<kwsys_stl::string>::const_iterator i = first;
  2293. i != last; ++i)
  2294. {
  2295. if(*i == "..")
  2296. {
  2297. if(out_components.begin() != out_components.end())
  2298. {
  2299. out_components.erase(out_components.end()-1, out_components.end());
  2300. }
  2301. }
  2302. else if(!(*i == ".") && !(*i == ""))
  2303. {
  2304. out_components.push_back(*i);
  2305. }
  2306. }
  2307. }
  2308. kwsys_stl::string SystemTools::CollapseFullPath(const char* in_path,
  2309. const char* in_base)
  2310. {
  2311. // Collect the output path components.
  2312. kwsys_stl::vector<kwsys_stl::string> out_components;
  2313. // Split the input path components.
  2314. kwsys_stl::vector<kwsys_stl::string> path_components;
  2315. SystemTools::SplitPath(in_path, path_components);
  2316. // If the input path is relative, start with a base path.
  2317. if(path_components[0].length() == 0)
  2318. {
  2319. kwsys_stl::vector<kwsys_stl::string> base_components;
  2320. if(in_base)
  2321. {
  2322. // Use the given base path.
  2323. SystemTools::SplitPath(in_base, base_components);
  2324. }
  2325. else
  2326. {
  2327. // Use the current working directory as a base path.
  2328. char buf[2048];
  2329. if(const char* cwd = Getcwd(buf, 2048))
  2330. {
  2331. SystemTools::SplitPath(cwd, base_components);
  2332. }
  2333. else
  2334. {
  2335. // ??
  2336. }
  2337. }
  2338. // Append base path components to the output path.
  2339. out_components.push_back(base_components[0]);
  2340. SystemToolsAppendComponents(out_components,
  2341. base_components.begin()+1,
  2342. base_components.end());
  2343. }
  2344. // Append input path components to the output path.
  2345. SystemToolsAppendComponents(out_components,
  2346. path_components.begin(),
  2347. path_components.end());
  2348. // Transform the path back to a string.
  2349. kwsys_stl::string newPath = SystemTools::JoinPath(out_components);
  2350. // Update the translation table with this potentially new path.
  2351. SystemTools::AddTranslationPath(newPath.c_str(), in_path);
  2352. SystemTools::CheckTranslationPath(newPath);
  2353. #ifdef _WIN32
  2354. newPath = SystemTools::GetActualCaseForPath(newPath.c_str());
  2355. SystemTools::ConvertToUnixSlashes(newPath);
  2356. #endif
  2357. // Return the reconstructed path.
  2358. return newPath;
  2359. }
  2360. // compute the relative path from here to there
  2361. kwsys_stl::string SystemTools::RelativePath(const char* local, const char* remote)
  2362. {
  2363. if(!SystemTools::FileIsFullPath(local))
  2364. {
  2365. return "";
  2366. }
  2367. if(!SystemTools::FileIsFullPath(remote))
  2368. {
  2369. return "";
  2370. }
  2371. // split up both paths into arrays of strings using / as a separator
  2372. kwsys_stl::vector<kwsys::String> localSplit = SystemTools::SplitString(local, '/', true);
  2373. kwsys_stl::vector<kwsys::String> remoteSplit = SystemTools::SplitString(remote, '/', true);
  2374. kwsys_stl::vector<kwsys::String> commonPath; // store shared parts of path in this array
  2375. kwsys_stl::vector<kwsys::String> finalPath; // store the final relative path here
  2376. // count up how many matching directory names there are from the start
  2377. unsigned int sameCount = 0;
  2378. while(
  2379. ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1)))
  2380. &&
  2381. // for windows and apple do a case insensitive string compare
  2382. #if defined(_WIN32) || defined(__APPLE__)
  2383. SystemTools::Strucmp(localSplit[sameCount].c_str(),
  2384. remoteSplit[sameCount].c_str()) == 0
  2385. #else
  2386. localSplit[sameCount] == remoteSplit[sameCount]
  2387. #endif
  2388. )
  2389. {
  2390. // put the common parts of the path into the commonPath array
  2391. commonPath.push_back(localSplit[sameCount]);
  2392. // erase the common parts of the path from the original path arrays
  2393. localSplit[sameCount] = "";
  2394. remoteSplit[sameCount] = "";
  2395. sameCount++;
  2396. }
  2397. // If there is nothing in common but the root directory, then just
  2398. // return the full path.
  2399. if(sameCount <= 1)
  2400. {
  2401. return remote;
  2402. }
  2403. // for each entry that is not common in the local path
  2404. // add a ../ to the finalpath array, this gets us out of the local
  2405. // path into the remote dir
  2406. for(unsigned int i = 0; i < localSplit.size(); ++i)
  2407. {
  2408. if(localSplit[i].size())
  2409. {
  2410. finalPath.push_back("../");
  2411. }
  2412. }
  2413. // for each entry that is not common in the remote path add it
  2414. // to the final path.
  2415. for(kwsys_stl::vector<String>::iterator vit = remoteSplit.begin();
  2416. vit != remoteSplit.end(); ++vit)
  2417. {
  2418. if(vit->size())
  2419. {
  2420. finalPath.push_back(*vit);
  2421. }
  2422. }
  2423. kwsys_stl::string relativePath; // result string
  2424. // now turn the array of directories into a unix path by puttint /
  2425. // between each entry that does not already have one
  2426. for(kwsys_stl::vector<String>::iterator vit1 = finalPath.begin();
  2427. vit1 != finalPath.end(); ++vit1)
  2428. {
  2429. if(relativePath.size() && relativePath[relativePath.size()-1] != '/')
  2430. {
  2431. relativePath += "/";
  2432. }
  2433. relativePath += *vit1;
  2434. }
  2435. return relativePath;
  2436. }
  2437. // OK, some fun stuff to get the actual case of a given path.
  2438. // Basically, you just need to call ShortPath, then GetLongPathName,
  2439. // However, GetLongPathName is not implemented on windows NT and 95,
  2440. // so we have to simulate it on those versions
  2441. #ifdef _WIN32
  2442. int OldWindowsGetLongPath(kwsys_stl::string const& shortPath,
  2443. kwsys_stl::string& longPath )
  2444. {
  2445. kwsys_stl::string::size_type iFound = shortPath.rfind('/');
  2446. if (iFound > 1 && iFound != shortPath.npos)
  2447. {
  2448. // recurse to peel off components
  2449. //
  2450. if (OldWindowsGetLongPath(shortPath.substr(0, iFound), longPath) > 0)
  2451. {
  2452. longPath += '/';
  2453. if (shortPath[1] != '/')
  2454. {
  2455. WIN32_FIND_DATA findData;
  2456. // append the long component name to the path
  2457. //
  2458. if (INVALID_HANDLE_VALUE != ::FindFirstFile
  2459. (shortPath.c_str(), &findData))
  2460. {
  2461. longPath += findData.cFileName;
  2462. }
  2463. else
  2464. {
  2465. // if FindFirstFile fails, return the error code
  2466. //
  2467. longPath = "";
  2468. return 0;
  2469. }
  2470. }
  2471. }
  2472. }
  2473. else
  2474. {
  2475. longPath = shortPath;
  2476. }
  2477. return (int)longPath.size();
  2478. }
  2479. int PortableGetLongPathName(const char* pathIn,
  2480. kwsys_stl::string & longPath)
  2481. {
  2482. HMODULE lh = LoadLibrary("Kernel32.dll");
  2483. if(lh)
  2484. {
  2485. FARPROC proc = GetProcAddress(lh, "GetLongPathNameA");
  2486. if(proc)
  2487. {
  2488. typedef DWORD (WINAPI * GetLongFunctionPtr) (LPCSTR,LPSTR,DWORD);
  2489. GetLongFunctionPtr func = (GetLongFunctionPtr)proc;
  2490. char buffer[MAX_PATH+1];
  2491. int len = (*func)(pathIn, buffer, MAX_PATH+1);
  2492. if(len == 0 || len > MAX_PATH+1)
  2493. {
  2494. FreeLibrary(lh);
  2495. return 0;
  2496. }
  2497. longPath = buffer;
  2498. FreeLibrary(lh);
  2499. return len;
  2500. }
  2501. FreeLibrary(lh);
  2502. }
  2503. return OldWindowsGetLongPath(pathIn, longPath);
  2504. }
  2505. #endif
  2506. //----------------------------------------------------------------------------
  2507. kwsys_stl::string SystemTools::GetActualCaseForPath(const char* p)
  2508. {
  2509. #ifndef _WIN32
  2510. return p;
  2511. #else
  2512. kwsys_stl::string shortPath;
  2513. if(!SystemTools::GetShortPath(p, shortPath))
  2514. {
  2515. return p;
  2516. }
  2517. kwsys_stl::string longPath;
  2518. int len = PortableGetLongPathName(shortPath.c_str(), longPath);
  2519. if(len == 0 || len > MAX_PATH+1)
  2520. {
  2521. return p;
  2522. }
  2523. return longPath;
  2524. #endif
  2525. }
  2526. //----------------------------------------------------------------------------
  2527. void SystemTools::SplitPath(const char* p,
  2528. kwsys_stl::vector<kwsys_stl::string>& components)
  2529. {
  2530. components.clear();
  2531. // Identify the root component.
  2532. const char* c = p;
  2533. if((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\'))
  2534. {
  2535. // Network path.
  2536. components.push_back("//");
  2537. c += 2;
  2538. }
  2539. else if(c[0] == '/')
  2540. {
  2541. // Unix path.
  2542. components.push_back("/");
  2543. c += 1;
  2544. }
  2545. else if(c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\'))
  2546. {
  2547. // Windows path.
  2548. kwsys_stl::string root = "_:/";
  2549. root[0] = c[0];
  2550. components.push_back(root);
  2551. c += 3;
  2552. }
  2553. else if(c[0] && c[1] == ':')
  2554. {
  2555. // Path relative to a windows drive working directory.
  2556. kwsys_stl::string root = "_:";
  2557. root[0] = c[0];
  2558. components.push_back(root);
  2559. c += 2;
  2560. }
  2561. else
  2562. {
  2563. // Relative path.
  2564. components.push_back("");
  2565. }
  2566. // Parse the remaining components.
  2567. const char* first = c;
  2568. const char* last = first;
  2569. for(;*last; ++last)
  2570. {
  2571. if(*last == '/' || *last == '\\')
  2572. {
  2573. // End of a component. Save it.
  2574. components.push_back(kwsys_stl::string(first, last-first));
  2575. first = last+1;
  2576. }
  2577. }
  2578. // Save the last component unless there were no components.
  2579. if(last != c)
  2580. {
  2581. components.push_back(kwsys_stl::string(first, last-first));
  2582. }
  2583. }
  2584. //----------------------------------------------------------------------------
  2585. kwsys_stl::string
  2586. SystemTools::JoinPath(const kwsys_stl::vector<kwsys_stl::string>& components)
  2587. {
  2588. kwsys_stl::string result;
  2589. if(components.size() > 0)
  2590. {
  2591. result += components[0];
  2592. }
  2593. if(components.size() > 1)
  2594. {
  2595. result += components[1];
  2596. }
  2597. for(unsigned int i=2; i < components.size(); ++i)
  2598. {
  2599. result += "/";
  2600. result += components[i];
  2601. }
  2602. return result;
  2603. }
  2604. //----------------------------------------------------------------------------
  2605. bool SystemTools::ComparePath(const char* c1, const char* c2)
  2606. {
  2607. #if defined(_WIN32) || defined(__APPLE__)
  2608. # ifdef _MSC_VER
  2609. return _stricmp(c1, c2) == 0;
  2610. # elif defined(__APPLE__) || defined(__GNUC__)
  2611. return strcasecmp(c1, c2) == 0;
  2612. #else
  2613. return SystemTools::Strucmp(c1, c2) == 0;
  2614. # endif
  2615. #else
  2616. return strcmp(c1, c2) == 0;
  2617. #endif
  2618. }
  2619. //----------------------------------------------------------------------------
  2620. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines, char separator)
  2621. {
  2622. kwsys_stl::string data(str);
  2623. kwsys_stl::string::size_type lpos = 0;
  2624. while(lpos < data.length())
  2625. {
  2626. kwsys_stl::string::size_type rpos = data.find_first_of(separator, lpos);
  2627. if(rpos == kwsys_stl::string::npos)
  2628. {
  2629. // Line ends at end of string without a newline.
  2630. lines.push_back(data.substr(lpos));
  2631. return false;
  2632. }
  2633. else
  2634. {
  2635. // Line ends in a "\n", remove the character.
  2636. lines.push_back(data.substr(lpos, rpos-lpos));
  2637. }
  2638. lpos = rpos+1;
  2639. }
  2640. return true;
  2641. }
  2642. //----------------------------------------------------------------------------
  2643. bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
  2644. {
  2645. kwsys_stl::string data(str);
  2646. kwsys_stl::string::size_type lpos = 0;
  2647. while(lpos < data.length())
  2648. {
  2649. kwsys_stl::string::size_type rpos = data.find_first_of("\n", lpos);
  2650. if(rpos == kwsys_stl::string::npos)
  2651. {
  2652. // Line ends at end of string without a newline.
  2653. lines.push_back(data.substr(lpos));
  2654. return false;
  2655. }
  2656. if((rpos > lpos) && (data[rpos-1] == '\r'))
  2657. {
  2658. // Line ends in a "\r\n" pair, remove both characters.
  2659. lines.push_back(data.substr(lpos, (rpos-1)-lpos));
  2660. }
  2661. else
  2662. {
  2663. // Line ends in a "\n", remove the character.
  2664. lines.push_back(data.substr(lpos, rpos-lpos));
  2665. }
  2666. lpos = rpos+1;
  2667. }
  2668. return true;
  2669. }
  2670. /**
  2671. * Return path of a full filename (no trailing slashes).
  2672. * Warning: returned path is converted to Unix slashes format.
  2673. */
  2674. kwsys_stl::string SystemTools::GetFilenamePath(const kwsys_stl::string& filename)
  2675. {
  2676. kwsys_stl::string fn = filename;
  2677. SystemTools::ConvertToUnixSlashes(fn);
  2678. kwsys_stl::string::size_type slash_pos = fn.rfind("/");
  2679. if(slash_pos != kwsys_stl::string::npos)
  2680. {
  2681. kwsys_stl::string ret = fn.substr(0, slash_pos);
  2682. if(ret.size() == 2 && ret[1] == ':')
  2683. {
  2684. return ret + '/';
  2685. }
  2686. if(ret.size() == 0)
  2687. {
  2688. return "/";
  2689. }
  2690. return ret;
  2691. }
  2692. else
  2693. {
  2694. return "";
  2695. }
  2696. }
  2697. /**
  2698. * Return file name of a full filename (i.e. file name without path).
  2699. */
  2700. kwsys_stl::string SystemTools::GetFilenameName(const kwsys_stl::string& filename)
  2701. {
  2702. #if defined(_WIN32)
  2703. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/\\");
  2704. #else
  2705. kwsys_stl::string::size_type slash_pos = filename.find_last_of("/");
  2706. #endif
  2707. if(slash_pos != kwsys_stl::string::npos)
  2708. {
  2709. return filename.substr(slash_pos + 1);
  2710. }
  2711. else
  2712. {
  2713. return filename;
  2714. }
  2715. }
  2716. /**
  2717. * Return file extension of a full filename (dot included).
  2718. * Warning: this is the longest extension (for example: .tar.gz)
  2719. */
  2720. kwsys_stl::string SystemTools::GetFilenameExtension(const kwsys_stl::string& filename)
  2721. {
  2722. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2723. kwsys_stl::string::size_type dot_pos = name.find(".");
  2724. if(dot_pos != kwsys_stl::string::npos)
  2725. {
  2726. return name.substr(dot_pos);
  2727. }
  2728. else
  2729. {
  2730. return "";
  2731. }
  2732. }
  2733. /**
  2734. * Return file extension of a full filename (dot included).
  2735. * Warning: this is the shortest extension (for example: .tar.gz)
  2736. */
  2737. kwsys_stl::string SystemTools::GetFilenameLastExtension(const kwsys_stl::string& filename)
  2738. {
  2739. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2740. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2741. if(dot_pos != kwsys_stl::string::npos)
  2742. {
  2743. return name.substr(dot_pos);
  2744. }
  2745. else
  2746. {
  2747. return "";
  2748. }
  2749. }
  2750. /**
  2751. * Return file name without extension of a full filename (i.e. without path).
  2752. * Warning: it considers the longest extension (for example: .tar.gz)
  2753. */
  2754. kwsys_stl::string SystemTools::GetFilenameWithoutExtension(const kwsys_stl::string& filename)
  2755. {
  2756. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2757. kwsys_stl::string::size_type dot_pos = name.find(".");
  2758. if(dot_pos != kwsys_stl::string::npos)
  2759. {
  2760. return name.substr(0, dot_pos);
  2761. }
  2762. else
  2763. {
  2764. return name;
  2765. }
  2766. }
  2767. /**
  2768. * Return file name without extension of a full filename (i.e. without path).
  2769. * Warning: it considers the last extension (for example: removes .gz
  2770. * from .tar.gz)
  2771. */
  2772. kwsys_stl::string
  2773. SystemTools::GetFilenameWithoutLastExtension(const kwsys_stl::string& filename)
  2774. {
  2775. kwsys_stl::string name = SystemTools::GetFilenameName(filename);
  2776. kwsys_stl::string::size_type dot_pos = name.rfind(".");
  2777. if(dot_pos != kwsys_stl::string::npos)
  2778. {
  2779. return name.substr(0, dot_pos);
  2780. }
  2781. else
  2782. {
  2783. return name;
  2784. }
  2785. }
  2786. bool SystemTools::FileHasSignature(const char *filename,
  2787. const char *signature,
  2788. long offset)
  2789. {
  2790. if (!filename || !signature)
  2791. {
  2792. return false;
  2793. }
  2794. FILE *fp;
  2795. fp = fopen(filename, "rb");
  2796. if (!fp)
  2797. {
  2798. return false;
  2799. }
  2800. fseek(fp, offset, SEEK_SET);
  2801. bool res = false;
  2802. size_t signature_len = strlen(signature);
  2803. char *buffer = new char [signature_len];
  2804. if (fread(buffer, 1, signature_len, fp) == signature_len)
  2805. {
  2806. res = (!strncmp(buffer, signature, signature_len) ? true : false);
  2807. }
  2808. delete [] buffer;
  2809. fclose(fp);
  2810. return res;
  2811. }
  2812. SystemTools::FileTypeEnum
  2813. SystemTools::DetectFileType(const char *filename,
  2814. unsigned long length,
  2815. double percent_bin)
  2816. {
  2817. if (!filename || percent_bin < 0)
  2818. {
  2819. return SystemTools::FileTypeUnknown;
  2820. }
  2821. FILE *fp;
  2822. fp = fopen(filename, "rb");
  2823. if (!fp)
  2824. {
  2825. return SystemTools::FileTypeUnknown;
  2826. }
  2827. // Allocate buffer and read bytes
  2828. unsigned char *buffer = new unsigned char [length];
  2829. size_t read_length = fread(buffer, 1, length, fp);
  2830. fclose(fp);
  2831. if (read_length == 0)
  2832. {
  2833. return SystemTools::FileTypeUnknown;
  2834. }
  2835. // Loop over contents and count
  2836. size_t text_count = 0;
  2837. const unsigned char *ptr = buffer;
  2838. const unsigned char *buffer_end = buffer + read_length;
  2839. while (ptr != buffer_end)
  2840. {
  2841. if ((*ptr >= 0x20 && *ptr <= 0x7F) ||
  2842. *ptr == '\n' ||
  2843. *ptr == '\r' ||
  2844. *ptr == '\t')
  2845. {
  2846. text_count++;
  2847. }
  2848. ptr++;
  2849. }
  2850. delete [] buffer;
  2851. double current_percent_bin =
  2852. (static_cast<double>(read_length - text_count) /
  2853. static_cast<double>(read_length));
  2854. if (current_percent_bin >= percent_bin)
  2855. {
  2856. return SystemTools::FileTypeBinary;
  2857. }
  2858. return SystemTools::FileTypeText;
  2859. }
  2860. bool SystemTools::LocateFileInDir(const char *filename,
  2861. const char *dir,
  2862. kwsys_stl::string& filename_found,
  2863. int try_filename_dirs)
  2864. {
  2865. if (!filename || !dir)
  2866. {
  2867. return false;
  2868. }
  2869. // Get the basename of 'filename'
  2870. kwsys_stl::string filename_base = SystemTools::GetFilenameName(filename);
  2871. // Check if 'dir' is really a directory
  2872. // If win32 and matches something like C:, accept it as a dir
  2873. kwsys_stl::string real_dir;
  2874. if (!SystemTools::FileIsDirectory(dir))
  2875. {
  2876. #if defined( _WIN32 )
  2877. size_t dir_len = strlen(dir);
  2878. if (dir_len < 2 || dir[dir_len - 1] != ':')
  2879. {
  2880. #endif
  2881. real_dir = SystemTools::GetFilenamePath(dir);
  2882. dir = real_dir.c_str();
  2883. #if defined( _WIN32 )
  2884. }
  2885. #endif
  2886. }
  2887. // Try to find the file in 'dir'
  2888. bool res = false;
  2889. if (filename_base.size() && dir)
  2890. {
  2891. size_t dir_len = strlen(dir);
  2892. int need_slash =
  2893. (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
  2894. kwsys_stl::string temp = dir;
  2895. if (need_slash)
  2896. {
  2897. temp += "/";
  2898. }
  2899. temp += filename_base;
  2900. if (SystemTools::FileExists(filename_found.c_str()))
  2901. {
  2902. res = true;
  2903. filename_found = temp;
  2904. }
  2905. // If not found, we can try harder by appending part of the file to
  2906. // to the directory to look inside.
  2907. // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
  2908. // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
  2909. else if (try_filename_dirs)
  2910. {
  2911. kwsys_stl::string filename_dir(filename);
  2912. kwsys_stl::string filename_dir_base;
  2913. kwsys_stl::string filename_dir_bases;
  2914. do
  2915. {
  2916. filename_dir = SystemTools::GetFilenamePath(filename_dir);
  2917. filename_dir_base = SystemTools::GetFilenameName(filename_dir);
  2918. #if defined( _WIN32 )
  2919. if (!filename_dir_base.size() ||
  2920. filename_dir_base[filename_dir_base.size() - 1] == ':')
  2921. #else
  2922. if (!filename_dir_base.size())
  2923. #endif
  2924. {
  2925. break;
  2926. }
  2927. filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
  2928. temp = dir;
  2929. if (need_slash)
  2930. {
  2931. temp += "/";
  2932. }
  2933. temp += filename_dir_bases;
  2934. res = SystemTools::LocateFileInDir(
  2935. filename_base.c_str(), temp.c_str(), filename_found, 0);
  2936. } while (!res && filename_dir_base.size());
  2937. }
  2938. }
  2939. return res;
  2940. }
  2941. bool SystemTools::FileIsFullPath(const char* in_name)
  2942. {
  2943. kwsys_stl::string name = in_name;
  2944. #if defined(_WIN32) || defined(__CYGWIN__)
  2945. // On Windows, the name must be at least two characters long.
  2946. if(name.length() < 2)
  2947. {
  2948. return false;
  2949. }
  2950. if(name[1] == ':')
  2951. {
  2952. return true;
  2953. }
  2954. if(name[0] == '\\')
  2955. {
  2956. return true;
  2957. }
  2958. #else
  2959. // On UNIX, the name must be at least one character long.
  2960. if(name.length() < 1)
  2961. {
  2962. return false;
  2963. }
  2964. #endif
  2965. // On UNIX, the name must begin in a '/'.
  2966. // On Windows, if the name begins in a '/', then it is a full
  2967. // network path.
  2968. if(name[0] == '/')
  2969. {
  2970. return true;
  2971. }
  2972. return false;
  2973. }
  2974. bool SystemTools::GetShortPath(const char* path, kwsys_stl::string& shortPath)
  2975. {
  2976. #if defined(WIN32) && !defined(__CYGWIN__)
  2977. const int size = int(strlen(path)) +1; // size of return
  2978. char *buffer = new char[size]; // create a buffer
  2979. char *tempPath = new char[size]; // create a buffer
  2980. int ret;
  2981. // if the path passed in has quotes around it, first remove the quotes
  2982. if (path[0] == '"' && path[strlen(path)-1] == '"')
  2983. {
  2984. strcpy(tempPath,path+1);
  2985. tempPath[strlen(tempPath)-1] = '\0';
  2986. }
  2987. else
  2988. {
  2989. strcpy(tempPath,path);
  2990. }
  2991. buffer[0] = 0;
  2992. ret = GetShortPathName(tempPath, buffer, size);
  2993. if(buffer[0] == 0 || ret > size)
  2994. {
  2995. delete [] buffer;
  2996. delete [] tempPath;
  2997. return false;
  2998. }
  2999. else
  3000. {
  3001. shortPath = buffer;
  3002. delete [] buffer;
  3003. delete [] tempPath;
  3004. return true;
  3005. }
  3006. #else
  3007. shortPath = path;
  3008. return true;
  3009. #endif
  3010. }
  3011. void SystemTools::SplitProgramFromArgs(const char* path,
  3012. kwsys_stl::string& program, kwsys_stl::string& args)
  3013. {
  3014. // see if this is a full path to a program
  3015. // if so then set program to path and args to nothing
  3016. if(SystemTools::FileExists(path))
  3017. {
  3018. program = path;
  3019. args = "";
  3020. return;
  3021. }
  3022. // Try to find the program in the path, note the program
  3023. // may have spaces in its name so we have to look for it
  3024. kwsys_stl::vector<kwsys_stl::string> e;
  3025. kwsys_stl::string findProg = SystemTools::FindProgram(path, e);
  3026. if(findProg.size())
  3027. {
  3028. program = findProg;
  3029. args = "";
  3030. return;
  3031. }
  3032. // Now try and peel off space separated chunks from the end of the string
  3033. // so the largest path possible is found allowing for spaces in the path
  3034. kwsys_stl::string dir = path;
  3035. kwsys_stl::string::size_type spacePos = dir.rfind(' ');
  3036. while(spacePos != kwsys_stl::string::npos)
  3037. {
  3038. kwsys_stl::string tryProg = dir.substr(0, spacePos);
  3039. // See if the file exists
  3040. if(SystemTools::FileExists(tryProg.c_str()))
  3041. {
  3042. program = tryProg;
  3043. // remove trailing spaces from program
  3044. kwsys_stl::string::size_type pos = program.size()-1;
  3045. while(program[pos] == ' ')
  3046. {
  3047. program.erase(pos);
  3048. pos--;
  3049. }
  3050. args = dir.substr(spacePos, dir.size()-spacePos);
  3051. return;
  3052. }
  3053. // Now try and find the the program in the path
  3054. findProg = SystemTools::FindProgram(tryProg.c_str(), e);
  3055. if(findProg.size())
  3056. {
  3057. program = findProg;
  3058. // remove trailing spaces from program
  3059. kwsys_stl::string::size_type pos = program.size()-1;
  3060. while(program[pos] == ' ')
  3061. {
  3062. program.erase(pos);
  3063. pos--;
  3064. }
  3065. args = dir.substr(spacePos, dir.size()-spacePos);
  3066. return;
  3067. }
  3068. // move past the space for the next search
  3069. spacePos--;
  3070. spacePos = dir.rfind(' ', spacePos);
  3071. }
  3072. program = "";
  3073. args = "";
  3074. }
  3075. kwsys_stl::string SystemTools::GetCurrentDateTime(const char* format)
  3076. {
  3077. char buf[1024];
  3078. time_t t;
  3079. time(&t);
  3080. strftime(buf, sizeof(buf), format, localtime(&t));
  3081. return kwsys_stl::string(buf);
  3082. }
  3083. kwsys_stl::string SystemTools::MakeCindentifier(const char* s)
  3084. {
  3085. kwsys_stl::string str(s);
  3086. if (str.find_first_of("0123456789") == 0)
  3087. {
  3088. str = "_" + str;
  3089. }
  3090. kwsys_stl::string permited_chars("_"
  3091. "abcdefghijklmnopqrstuvwxyz"
  3092. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3093. "0123456789");
  3094. kwsys_stl::string::size_type pos = 0;
  3095. while ((pos = str.find_first_not_of(permited_chars, pos)) != kwsys_stl::string::npos)
  3096. {
  3097. str[pos] = '_';
  3098. }
  3099. return str;
  3100. }
  3101. // Due to a buggy stream library on the HP and another on Mac OSX, we
  3102. // need this very carefully written version of getline. Returns true
  3103. // if any data were read before the end-of-file was reached.
  3104. bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, kwsys_stl::string& line,
  3105. bool *has_newline /* = 0 */)
  3106. {
  3107. const int bufferSize = 1024;
  3108. char buffer[bufferSize];
  3109. line = "";
  3110. bool haveData = false;
  3111. if ( has_newline )
  3112. {
  3113. *has_newline = false;
  3114. }
  3115. // If no characters are read from the stream, the end of file has
  3116. // been reached.
  3117. while((is.getline(buffer, bufferSize), is.gcount() > 0))
  3118. {
  3119. haveData = true;
  3120. line.append(buffer);
  3121. // If newline character was read, the gcount includes the
  3122. // character, but the buffer does not. The end of line has been
  3123. // reached.
  3124. if(strlen(buffer) < static_cast<size_t>(is.gcount()))
  3125. {
  3126. if ( has_newline )
  3127. {
  3128. *has_newline = true;
  3129. }
  3130. break;
  3131. }
  3132. // The fail bit may be set. Clear it.
  3133. is.clear(is.rdstate() & ~kwsys_ios::ios::failbit);
  3134. }
  3135. return haveData;
  3136. }
  3137. int SystemTools::GetTerminalWidth()
  3138. {
  3139. int width = -1;
  3140. #ifndef _WIN32
  3141. struct winsize ws;
  3142. char *columns; /* Unix98 environment variable */
  3143. if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
  3144. {
  3145. width = ws.ws_col;
  3146. }
  3147. if(!isatty(STDOUT_FILENO))
  3148. {
  3149. width = -1;
  3150. }
  3151. columns = getenv("COLUMNS");
  3152. if(columns && *columns)
  3153. {
  3154. long t;
  3155. char *endptr;
  3156. t = strtol(columns, &endptr, 0);
  3157. if(endptr && !*endptr && (t>0) && (t<1000))
  3158. {
  3159. width = static_cast<int>(t);
  3160. }
  3161. }
  3162. if ( width < 9 )
  3163. {
  3164. width = -1;
  3165. }
  3166. #endif
  3167. return width;
  3168. }
  3169. bool SystemTools::GetPermissions(const char* file, mode_t& mode)
  3170. {
  3171. if ( !file )
  3172. {
  3173. return false;
  3174. }
  3175. struct stat st;
  3176. if ( stat(file, &st) < 0 )
  3177. {
  3178. return false;
  3179. }
  3180. mode = st.st_mode;
  3181. return true;
  3182. }
  3183. bool SystemTools::SetPermissions(const char* file, mode_t mode)
  3184. {
  3185. if ( !file )
  3186. {
  3187. return false;
  3188. }
  3189. if ( !SystemTools::FileExists(file) )
  3190. {
  3191. return false;
  3192. }
  3193. if ( chmod(file, mode) < 0 )
  3194. {
  3195. return false;
  3196. }
  3197. return true;
  3198. }
  3199. kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
  3200. {
  3201. if ( !fileOrDir || !*fileOrDir )
  3202. {
  3203. return "";
  3204. }
  3205. kwsys_stl::string res = fileOrDir;
  3206. SystemTools::ConvertToUnixSlashes(res);
  3207. kwsys_stl::string::size_type cc = res.size()-1;
  3208. if ( res[cc] == '/' )
  3209. {
  3210. cc --;
  3211. }
  3212. for ( ; cc > 0; cc -- )
  3213. {
  3214. if ( res[cc] == '/' )
  3215. {
  3216. break;
  3217. }
  3218. }
  3219. return res.substr(0, cc);
  3220. }
  3221. bool SystemTools::IsSubDirectory(const char* cSubdir, const char* cDir)
  3222. {
  3223. kwsys_stl::string subdir = cSubdir;
  3224. kwsys_stl::string dir = cDir;
  3225. SystemTools::ConvertToUnixSlashes(dir);
  3226. kwsys_stl::string path = subdir;
  3227. do
  3228. {
  3229. path = SystemTools::GetParentDirectory(path.c_str());
  3230. if(SystemTools::ComparePath(dir.c_str(), path.c_str()))
  3231. {
  3232. return true;
  3233. }
  3234. }
  3235. while ( path.size() > dir.size() );
  3236. return false;
  3237. }
  3238. kwsys_stl::string SystemTools::FileExistsInParentDirectories(const char* fname,
  3239. const char* directory, const char* toplevel)
  3240. {
  3241. kwsys_stl::string file = fname;
  3242. SystemTools::ConvertToUnixSlashes(file);
  3243. kwsys_stl::string dir = directory;
  3244. SystemTools::ConvertToUnixSlashes(dir);
  3245. while ( !dir.empty() )
  3246. {
  3247. kwsys_stl::string path = dir + "/" + file;
  3248. if ( SystemTools::FileExists(path.c_str()) )
  3249. {
  3250. return path;
  3251. }
  3252. if ( dir.size() < strlen(toplevel) )
  3253. {
  3254. break;
  3255. }
  3256. dir = SystemTools::GetParentDirectory(dir.c_str());
  3257. }
  3258. return "";
  3259. }
  3260. void SystemTools::Delay(unsigned int msec)
  3261. {
  3262. #ifdef _WIN32
  3263. Sleep(msec);
  3264. #else
  3265. // The sleep function gives 1 second resolution and the usleep
  3266. // function gives 1e-6 second resolution but on some platforms has a
  3267. // maximum sleep time of 1 second. This could be re-implemented to
  3268. // use select with masked signals or pselect to mask signals
  3269. // atomically. If select is given empty sets and zero as the max
  3270. // file descriptor but a non-zero timeout it can be used to block
  3271. // for a precise amount of time.
  3272. if(msec >= 1000)
  3273. {
  3274. sleep(msec / 1000);
  3275. usleep((msec % 1000) * 1000);
  3276. }
  3277. else
  3278. {
  3279. usleep(msec * 1000);
  3280. }
  3281. #endif
  3282. }
  3283. void SystemTools::ConvertWindowsCommandLineToUnixArguments(
  3284. const char *cmd_line, int *argc, char ***argv)
  3285. {
  3286. if (!cmd_line || !argc || !argv)
  3287. {
  3288. return;
  3289. }
  3290. // A space delimites an argument except when it is inside a quote
  3291. (*argc) = 1;
  3292. size_t cmd_line_len = strlen(cmd_line);
  3293. size_t i;
  3294. for (i = 0; i < cmd_line_len; i++)
  3295. {
  3296. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3297. {
  3298. i++;
  3299. }
  3300. if (i < cmd_line_len)
  3301. {
  3302. if (cmd_line[i] == '\"')
  3303. {
  3304. i++;
  3305. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3306. {
  3307. i++;
  3308. }
  3309. (*argc)++;
  3310. }
  3311. else
  3312. {
  3313. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3314. {
  3315. i++;
  3316. }
  3317. (*argc)++;
  3318. }
  3319. }
  3320. }
  3321. (*argv) = new char* [(*argc) + 1];
  3322. (*argv)[(*argc)] = NULL;
  3323. // Set the first arg to be the exec name
  3324. (*argv)[0] = new char [1024];
  3325. #ifdef _WIN32
  3326. ::GetModuleFileName(0, (*argv)[0], 1024);
  3327. #else
  3328. (*argv)[0][0] = '\0';
  3329. #endif
  3330. // Allocate the others
  3331. int j;
  3332. for (j = 1; j < (*argc); j++)
  3333. {
  3334. (*argv)[j] = new char [cmd_line_len + 10];
  3335. }
  3336. // Grab the args
  3337. size_t pos;
  3338. int argc_idx = 1;
  3339. for (i = 0; i < cmd_line_len; i++)
  3340. {
  3341. while (isspace(cmd_line[i]) && i < cmd_line_len)
  3342. {
  3343. i++;
  3344. }
  3345. if (i < cmd_line_len)
  3346. {
  3347. if (cmd_line[i] == '\"')
  3348. {
  3349. i++;
  3350. pos = i;
  3351. while (cmd_line[i] != '\"' && i < cmd_line_len)
  3352. {
  3353. i++;
  3354. }
  3355. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3356. (*argv)[argc_idx][i - pos] = '\0';
  3357. argc_idx++;
  3358. }
  3359. else
  3360. {
  3361. pos = i;
  3362. while (!isspace(cmd_line[i]) && i < cmd_line_len)
  3363. {
  3364. i++;
  3365. }
  3366. memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
  3367. (*argv)[argc_idx][i - pos] = '\0';
  3368. argc_idx++;
  3369. }
  3370. }
  3371. }
  3372. }
  3373. kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
  3374. {
  3375. kwsys_stl::string res;
  3376. #ifdef _WIN32
  3377. char buffer[256];
  3378. OSVERSIONINFOEX osvi;
  3379. BOOL bOsVersionInfoEx;
  3380. // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
  3381. // If that fails, try using the OSVERSIONINFO structure.
  3382. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  3383. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  3384. bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi);
  3385. if (!bOsVersionInfoEx)
  3386. {
  3387. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  3388. if (!GetVersionEx((OSVERSIONINFO *)&osvi))
  3389. {
  3390. return 0;
  3391. }
  3392. }
  3393. switch (osvi.dwPlatformId)
  3394. {
  3395. // Test for the Windows NT product family.
  3396. case VER_PLATFORM_WIN32_NT:
  3397. // Test for the specific product family.
  3398. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  3399. {
  3400. res += "Microsoft Windows Server 2003 family";
  3401. }
  3402. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  3403. {
  3404. res += "Microsoft Windows XP";
  3405. }
  3406. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  3407. {
  3408. res += "Microsoft Windows 2000";
  3409. }
  3410. if (osvi.dwMajorVersion <= 4)
  3411. {
  3412. res += "Microsoft Windows NT";
  3413. }
  3414. // Test for specific product on Windows NT 4.0 SP6 and later.
  3415. if (bOsVersionInfoEx)
  3416. {
  3417. // Test for the workstation type.
  3418. #if (_MSC_VER >= 1300)
  3419. if (osvi.wProductType == VER_NT_WORKSTATION)
  3420. {
  3421. if (osvi.dwMajorVersion == 4)
  3422. {
  3423. res += " Workstation 4.0";
  3424. }
  3425. else if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
  3426. {
  3427. res += " Home Edition";
  3428. }
  3429. else
  3430. {
  3431. res += " Professional";
  3432. }
  3433. }
  3434. // Test for the server type.
  3435. else if (osvi.wProductType == VER_NT_SERVER)
  3436. {
  3437. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  3438. {
  3439. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  3440. {
  3441. res += " Datacenter Edition";
  3442. }
  3443. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3444. {
  3445. res += " Enterprise Edition";
  3446. }
  3447. else if (osvi.wSuiteMask == VER_SUITE_BLADE)
  3448. {
  3449. res += " Web Edition";
  3450. }
  3451. else
  3452. {
  3453. res += " Standard Edition";
  3454. }
  3455. }
  3456. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  3457. {
  3458. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  3459. {
  3460. res += " Datacenter Server";
  3461. }
  3462. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3463. {
  3464. res += " Advanced Server";
  3465. }
  3466. else
  3467. {
  3468. res += " Server";
  3469. }
  3470. }
  3471. else // Windows NT 4.0
  3472. {
  3473. if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  3474. {
  3475. res += " Server 4.0, Enterprise Edition";
  3476. }
  3477. else
  3478. {
  3479. res += " Server 4.0";
  3480. }
  3481. }
  3482. }
  3483. #endif // Visual Studio 7 and up
  3484. }
  3485. // Test for specific product on Windows NT 4.0 SP5 and earlier
  3486. else
  3487. {
  3488. HKEY hKey;
  3489. #define BUFSIZE 80
  3490. char szProductType[BUFSIZE];
  3491. DWORD dwBufLen=BUFSIZE;
  3492. LONG lRet;
  3493. lRet = RegOpenKeyEx(
  3494. HKEY_LOCAL_MACHINE,
  3495. "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
  3496. 0, KEY_QUERY_VALUE, &hKey);
  3497. if (lRet != ERROR_SUCCESS)
  3498. {
  3499. return 0;
  3500. }
  3501. lRet = RegQueryValueEx(hKey, "ProductType", NULL, NULL,
  3502. (LPBYTE) szProductType, &dwBufLen);
  3503. if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))
  3504. {
  3505. return 0;
  3506. }
  3507. RegCloseKey(hKey);
  3508. if (lstrcmpi("WINNT", szProductType) == 0)
  3509. {
  3510. res += " Workstation";
  3511. }
  3512. if (lstrcmpi("LANMANNT", szProductType) == 0)
  3513. {
  3514. res += " Server";
  3515. }
  3516. if (lstrcmpi("SERVERNT", szProductType) == 0)
  3517. {
  3518. res += " Advanced Server";
  3519. }
  3520. res += " ";
  3521. sprintf(buffer, "%d", osvi.dwMajorVersion);
  3522. res += buffer;
  3523. res += ".";
  3524. sprintf(buffer, "%d", osvi.dwMinorVersion);
  3525. res += buffer;
  3526. }
  3527. // Display service pack (if any) and build number.
  3528. if (osvi.dwMajorVersion == 4 &&
  3529. lstrcmpi(osvi.szCSDVersion, "Service Pack 6") == 0)
  3530. {
  3531. HKEY hKey;
  3532. LONG lRet;
  3533. // Test for SP6 versus SP6a.
  3534. lRet = RegOpenKeyEx(
  3535. HKEY_LOCAL_MACHINE,
  3536. "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
  3537. 0, KEY_QUERY_VALUE, &hKey);
  3538. if (lRet == ERROR_SUCCESS)
  3539. {
  3540. res += " Service Pack 6a (Build ";
  3541. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3542. res += buffer;
  3543. res += ")";
  3544. }
  3545. else // Windows NT 4.0 prior to SP6a
  3546. {
  3547. res += " ";
  3548. res += osvi.szCSDVersion;
  3549. res += " (Build ";
  3550. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3551. res += buffer;
  3552. res += ")";
  3553. }
  3554. RegCloseKey(hKey);
  3555. }
  3556. else // Windows NT 3.51 and earlier or Windows 2000 and later
  3557. {
  3558. res += " ";
  3559. res += osvi.szCSDVersion;
  3560. res += " (Build ";
  3561. sprintf(buffer, "%d", osvi.dwBuildNumber & 0xFFFF);
  3562. res += buffer;
  3563. res += ")";
  3564. }
  3565. break;
  3566. // Test for the Windows 95 product family.
  3567. case VER_PLATFORM_WIN32_WINDOWS:
  3568. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
  3569. {
  3570. res += "Microsoft Windows 95";
  3571. if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
  3572. {
  3573. res += " OSR2";
  3574. }
  3575. }
  3576. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
  3577. {
  3578. res += "Microsoft Windows 98";
  3579. if (osvi.szCSDVersion[1] == 'A')
  3580. {
  3581. res += " SE";
  3582. }
  3583. }
  3584. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
  3585. {
  3586. res += "Microsoft Windows Millennium Edition";
  3587. }
  3588. break;
  3589. case VER_PLATFORM_WIN32s:
  3590. res += "Microsoft Win32s";
  3591. break;
  3592. }
  3593. #endif
  3594. return res;
  3595. }
  3596. // These must NOT be initialized. Default initialization to zero is
  3597. // necessary.
  3598. unsigned int SystemToolsManagerCount;
  3599. SystemToolsTranslationMap *SystemTools::TranslationMap;
  3600. // SystemToolsManager manages the SystemTools singleton.
  3601. // SystemToolsManager should be included in any translation unit
  3602. // that will use SystemTools or that implements the singleton
  3603. // pattern. It makes sure that the SystemTools singleton is created
  3604. // before and destroyed after all other singletons in CMake.
  3605. SystemToolsManager::SystemToolsManager()
  3606. {
  3607. if(++SystemToolsManagerCount == 1)
  3608. {
  3609. SystemTools::ClassInitialize();
  3610. }
  3611. }
  3612. SystemToolsManager::~SystemToolsManager()
  3613. {
  3614. if(--SystemToolsManagerCount == 0)
  3615. {
  3616. SystemTools::ClassFinalize();
  3617. }
  3618. }
  3619. void SystemTools::ClassInitialize()
  3620. {
  3621. // Allocate the translation map first.
  3622. SystemTools::TranslationMap = new SystemToolsTranslationMap;
  3623. // Add some special translation paths for unix. These are not added
  3624. // for windows because drive letters need to be maintained. Also,
  3625. // there are not sym-links and mount points on windows anyway.
  3626. #if !defined(_WIN32) || defined(__CYGWIN__)
  3627. // Work-around an SGI problem by always adding this mapping:
  3628. SystemTools::AddTranslationPath("/tmp_mnt/", "/");
  3629. // The tmp path is frequently a logical path so always keep it:
  3630. SystemTools::AddKeepPath("/tmp/");
  3631. // If the current working directory is a logical path then keep the
  3632. // logical name.
  3633. if(const char* pwd = getenv("PWD"))
  3634. {
  3635. char buf[2048];
  3636. if(const char* cwd = Getcwd(buf, 2048))
  3637. {
  3638. // The current working directory may be a logical path. Find
  3639. // the shortest logical path that still produces the correct
  3640. // physical path.
  3641. kwsys_stl::string cwd_changed;
  3642. kwsys_stl::string pwd_changed;
  3643. // Test progressively shorter logical-to-physical mappings.
  3644. kwsys_stl::string pwd_str = pwd;
  3645. kwsys_stl::string cwd_str = cwd;
  3646. kwsys_stl::string pwd_path;
  3647. Realpath(pwd, pwd_path);
  3648. while(cwd_str == pwd_path && cwd_str != pwd_str)
  3649. {
  3650. // The current pair of paths is a working logical mapping.
  3651. cwd_changed = cwd_str;
  3652. pwd_changed = pwd_str;
  3653. // Strip off one directory level and see if the logical
  3654. // mapping still works.
  3655. pwd_str = SystemTools::GetFilenamePath(pwd_str.c_str());
  3656. cwd_str = SystemTools::GetFilenamePath(cwd_str.c_str());
  3657. Realpath(pwd_str.c_str(), pwd_path);
  3658. }
  3659. // Add the translation to keep the logical path name.
  3660. if(!cwd_changed.empty() && !pwd_changed.empty())
  3661. {
  3662. SystemTools::AddTranslationPath(cwd_changed.c_str(),
  3663. pwd_changed.c_str());
  3664. }
  3665. }
  3666. }
  3667. #endif
  3668. }
  3669. void SystemTools::ClassFinalize()
  3670. {
  3671. delete SystemTools::TranslationMap;
  3672. }
  3673. } // namespace KWSYS_NAMESPACE
  3674. #if defined(_MSC_VER) && defined(_DEBUG)
  3675. # include <crtdbg.h>
  3676. # include <stdio.h>
  3677. # include <stdlib.h>
  3678. namespace KWSYS_NAMESPACE
  3679. {
  3680. static int SystemToolsDebugReport(int, char* message, int*)
  3681. {
  3682. fprintf(stderr, message);
  3683. exit(1);
  3684. }
  3685. void SystemTools::EnableMSVCDebugHook()
  3686. {
  3687. if(getenv("DART_TEST_FROM_DART"))
  3688. {
  3689. _CrtSetReportHook(SystemToolsDebugReport);
  3690. }
  3691. }
  3692. } // namespace KWSYS_NAMESPACE
  3693. #else
  3694. namespace KWSYS_NAMESPACE
  3695. {
  3696. void SystemTools::EnableMSVCDebugHook() {}
  3697. } // namespace KWSYS_NAMESPACE
  3698. #endif