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