SystemTools.cxx 110 KB

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