SystemTools.cxx 117 KB

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