SystemTools.cxx 114 KB

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