SystemTools.cxx 117 KB

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