SystemTools.cxx 97 KB

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