SystemTools.cxx 109 KB

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