SystemTools.cxx 111 KB

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