SystemTools.cxx 116 KB

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