SystemTools.cxx 115 KB

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