SystemTools.cxx 113 KB

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