1
0

SystemTools.cxx 96 KB

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