SystemTools.cxx 118 KB

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