SystemTools.cxx 114 KB

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