cmSystemTools.cxx 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956
  1. /*=========================================================================
  2. Program: Insight Segmentation & Registration Toolkit
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2002 Insight Consortium. All rights reserved.
  8. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
  9. This software is distributed WITHOUT ANY WARRANTY; without even
  10. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  11. PURPOSE. See the above copyright notices for more information.
  12. =========================================================================*/
  13. #include "cmSystemTools.h"
  14. #include "errno.h"
  15. #include "stdio.h"
  16. #include <sys/stat.h>
  17. #include "cmRegularExpression.h"
  18. #include <ctype.h>
  19. #include "cmDirectory.h"
  20. // support for realpath call
  21. #ifndef _WIN32
  22. #include <limits.h>
  23. #include <stdlib.h>
  24. #include <sys/param.h>
  25. #include <sys/wait.h>
  26. #endif
  27. #if defined(_MSC_VER) || defined(__BORLANDC__)
  28. #include <string.h>
  29. #include <windows.h>
  30. #include <direct.h>
  31. #define _unlink unlink
  32. inline int Mkdir(const char* dir)
  33. {
  34. return _mkdir(dir);
  35. }
  36. inline const char* Getcwd(char* buf, unsigned int len)
  37. {
  38. return _getcwd(buf, len);
  39. }
  40. inline int Chdir(const char* dir)
  41. {
  42. #if defined(__BORLANDC__)
  43. return chdir(dir);
  44. #else
  45. return _chdir(dir);
  46. #endif
  47. }
  48. #else
  49. #include <sys/types.h>
  50. #include <fcntl.h>
  51. #include <unistd.h>
  52. inline int Mkdir(const char* dir)
  53. {
  54. return mkdir(dir, 00777);
  55. }
  56. inline const char* Getcwd(char* buf, unsigned int len)
  57. {
  58. return getcwd(buf, len);
  59. }
  60. inline int Chdir(const char* dir)
  61. {
  62. return chdir(dir);
  63. }
  64. #endif
  65. bool cmSystemTools::s_DisableRunCommandOutput = false;
  66. bool cmSystemTools::s_ErrorOccured = false;
  67. bool cmSystemTools::s_DisableMessages = false;
  68. void (*cmSystemTools::s_ErrorCallback)(const char*, const char*, bool&);
  69. // adds the elements of the env variable path to the arg passed in
  70. void cmSystemTools::GetPath(std::vector<std::string>& path)
  71. {
  72. #if defined(_WIN32) && !defined(__CYGWIN__)
  73. const char* pathSep = ";";
  74. #else
  75. const char* pathSep = ":";
  76. #endif
  77. std::string pathEnv = getenv("PATH");
  78. // A hack to make the below algorithm work.
  79. if(pathEnv[pathEnv.length()-1] != ':')
  80. {
  81. pathEnv += pathSep;
  82. }
  83. std::string::size_type start =0;
  84. bool done = false;
  85. while(!done)
  86. {
  87. std::string::size_type endpos = pathEnv.find(pathSep, start);
  88. if(endpos != std::string::npos)
  89. {
  90. path.push_back(pathEnv.substr(start, endpos-start));
  91. start = endpos+1;
  92. }
  93. else
  94. {
  95. done = true;
  96. }
  97. }
  98. for(std::vector<std::string>::iterator i = path.begin();
  99. i != path.end(); ++i)
  100. {
  101. cmSystemTools::ConvertToUnixSlashes(*i);
  102. }
  103. }
  104. const char* cmSystemTools::GetExecutableExtension()
  105. {
  106. #if defined(_WIN32) || defined(__CYGWIN__)
  107. return ".exe";
  108. #else
  109. return "";
  110. #endif
  111. }
  112. bool cmSystemTools::MakeDirectory(const char* path)
  113. {
  114. if(cmSystemTools::FileExists(path))
  115. {
  116. return true;
  117. }
  118. std::string dir = path;
  119. if(dir.size() == 0)
  120. {
  121. return false;
  122. }
  123. cmSystemTools::ConvertToUnixSlashes(dir);
  124. std::string::size_type pos = dir.find(':');
  125. if(pos == std::string::npos)
  126. {
  127. pos = 0;
  128. }
  129. std::string topdir;
  130. while((pos = dir.find('/', pos)) != std::string::npos)
  131. {
  132. topdir = dir.substr(0, pos);
  133. Mkdir(topdir.c_str());
  134. pos++;
  135. }
  136. if(dir[dir.size()-1] == '/')
  137. {
  138. topdir = dir.substr(0, dir.size());
  139. }
  140. else
  141. {
  142. topdir = dir;
  143. }
  144. if(Mkdir(topdir.c_str()) != 0)
  145. {
  146. // There is a bug in the Borland Run time library which makes MKDIR
  147. // return EACCES when it should return EEXISTS
  148. // if it is some other error besides directory exists
  149. // then return false
  150. if( (errno != EEXIST)
  151. #ifdef __BORLANDC__
  152. && (errno != EACCES)
  153. #endif
  154. )
  155. {
  156. cmSystemTools::Error("Faild to create directory:", path);
  157. return false;
  158. }
  159. }
  160. return true;
  161. }
  162. // replace replace with with as many times as it shows up in source.
  163. // write the result into source.
  164. void cmSystemTools::ReplaceString(std::string& source,
  165. const char* replace,
  166. const char* with)
  167. {
  168. std::string::size_type lengthReplace = strlen(replace);
  169. std::string::size_type lengthWith = strlen(with);
  170. std::string rest;
  171. std::string::size_type start = source.find(replace);
  172. while(start != std::string::npos)
  173. {
  174. rest = source.substr(start+lengthReplace);
  175. source = source.substr(0, start);
  176. source += with;
  177. source += rest;
  178. start = source.find(replace, start + lengthWith );
  179. }
  180. }
  181. // Read a registry value.
  182. // Example :
  183. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  184. // => will return the data of the "default" value of the key
  185. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  186. // => will return the data of the "Root" value of the key
  187. bool cmSystemTools::ReadRegistryValue(const char *key, std::string &value)
  188. {
  189. #if defined(_WIN32) && !defined(__CYGWIN__)
  190. std::string primary = key;
  191. std::string second;
  192. std::string valuename;
  193. size_t start = primary.find("\\");
  194. if (start == std::string::npos)
  195. {
  196. return false;
  197. }
  198. size_t valuenamepos = primary.find(";");
  199. if (valuenamepos != std::string::npos)
  200. {
  201. valuename = primary.substr(valuenamepos+1);
  202. }
  203. second = primary.substr(start+1, valuenamepos-start-1);
  204. primary = primary.substr(0, start);
  205. HKEY primaryKey;
  206. if (primary == "HKEY_CURRENT_USER")
  207. {
  208. primaryKey = HKEY_CURRENT_USER;
  209. }
  210. if (primary == "HKEY_CURRENT_CONFIG")
  211. {
  212. primaryKey = HKEY_CURRENT_CONFIG;
  213. }
  214. if (primary == "HKEY_CLASSES_ROOT")
  215. {
  216. primaryKey = HKEY_CLASSES_ROOT;
  217. }
  218. if (primary == "HKEY_LOCAL_MACHINE")
  219. {
  220. primaryKey = HKEY_LOCAL_MACHINE;
  221. }
  222. if (primary == "HKEY_USERS")
  223. {
  224. primaryKey = HKEY_USERS;
  225. }
  226. HKEY hKey;
  227. if(RegOpenKeyEx(primaryKey,
  228. second.c_str(),
  229. 0,
  230. KEY_READ,
  231. &hKey) != ERROR_SUCCESS)
  232. {
  233. return false;
  234. }
  235. else
  236. {
  237. DWORD dwType, dwSize;
  238. dwSize = 1023;
  239. char data[1024];
  240. if(RegQueryValueEx(hKey,
  241. (LPTSTR)valuename.c_str(),
  242. NULL,
  243. &dwType,
  244. (BYTE *)data,
  245. &dwSize) == ERROR_SUCCESS)
  246. {
  247. if (dwType == REG_SZ)
  248. {
  249. value = data;
  250. return true;
  251. }
  252. }
  253. }
  254. #endif
  255. return false;
  256. }
  257. // Write a registry value.
  258. // Example :
  259. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  260. // => will set the data of the "default" value of the key
  261. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  262. // => will set the data of the "Root" value of the key
  263. bool cmSystemTools::WriteRegistryValue(const char *key, const char *value)
  264. {
  265. #if defined(_WIN32) && !defined(__CYGWIN__)
  266. std::string primary = key;
  267. std::string second;
  268. std::string valuename;
  269. size_t start = primary.find("\\");
  270. if (start == std::string::npos)
  271. {
  272. return false;
  273. }
  274. size_t valuenamepos = primary.find(";");
  275. if (valuenamepos != std::string::npos)
  276. {
  277. valuename = primary.substr(valuenamepos+1);
  278. }
  279. second = primary.substr(start+1, valuenamepos-start-1);
  280. primary = primary.substr(0, start);
  281. HKEY primaryKey;
  282. if (primary == "HKEY_CURRENT_USER")
  283. {
  284. primaryKey = HKEY_CURRENT_USER;
  285. }
  286. if (primary == "HKEY_CURRENT_CONFIG")
  287. {
  288. primaryKey = HKEY_CURRENT_CONFIG;
  289. }
  290. if (primary == "HKEY_CLASSES_ROOT")
  291. {
  292. primaryKey = HKEY_CLASSES_ROOT;
  293. }
  294. if (primary == "HKEY_LOCAL_MACHINE")
  295. {
  296. primaryKey = HKEY_LOCAL_MACHINE;
  297. }
  298. if (primary == "HKEY_USERS")
  299. {
  300. primaryKey = HKEY_USERS;
  301. }
  302. HKEY hKey;
  303. DWORD dwDummy;
  304. if(RegCreateKeyEx(primaryKey,
  305. second.c_str(),
  306. 0,
  307. "",
  308. REG_OPTION_NON_VOLATILE,
  309. KEY_WRITE,
  310. NULL,
  311. &hKey,
  312. &dwDummy) != ERROR_SUCCESS)
  313. {
  314. return false;
  315. }
  316. if(RegSetValueEx(hKey,
  317. (LPTSTR)valuename.c_str(),
  318. 0,
  319. REG_SZ,
  320. (CONST BYTE *)value,
  321. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  322. {
  323. return true;
  324. }
  325. #endif
  326. return false;
  327. }
  328. // Delete a registry value.
  329. // Example :
  330. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  331. // => will delete the data of the "default" value of the key
  332. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  333. // => will delete the data of the "Root" value of the key
  334. bool cmSystemTools::DeleteRegistryValue(const char *key)
  335. {
  336. #if defined(_WIN32) && !defined(__CYGWIN__)
  337. std::string primary = key;
  338. std::string second;
  339. std::string valuename;
  340. size_t start = primary.find("\\");
  341. if (start == std::string::npos)
  342. {
  343. return false;
  344. }
  345. size_t valuenamepos = primary.find(";");
  346. if (valuenamepos != std::string::npos)
  347. {
  348. valuename = primary.substr(valuenamepos+1);
  349. }
  350. second = primary.substr(start+1, valuenamepos-start-1);
  351. primary = primary.substr(0, start);
  352. HKEY primaryKey;
  353. if (primary == "HKEY_CURRENT_USER")
  354. {
  355. primaryKey = HKEY_CURRENT_USER;
  356. }
  357. if (primary == "HKEY_CURRENT_CONFIG")
  358. {
  359. primaryKey = HKEY_CURRENT_CONFIG;
  360. }
  361. if (primary == "HKEY_CLASSES_ROOT")
  362. {
  363. primaryKey = HKEY_CLASSES_ROOT;
  364. }
  365. if (primary == "HKEY_LOCAL_MACHINE")
  366. {
  367. primaryKey = HKEY_LOCAL_MACHINE;
  368. }
  369. if (primary == "HKEY_USERS")
  370. {
  371. primaryKey = HKEY_USERS;
  372. }
  373. HKEY hKey;
  374. if(RegOpenKeyEx(primaryKey,
  375. second.c_str(),
  376. 0,
  377. KEY_WRITE,
  378. &hKey) != ERROR_SUCCESS)
  379. {
  380. return false;
  381. }
  382. else
  383. {
  384. if(RegDeleteValue(hKey,
  385. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  386. {
  387. return true;
  388. }
  389. }
  390. #endif
  391. return false;
  392. }
  393. // replace replace with with as many times as it shows up in source.
  394. // write the result into source.
  395. void cmSystemTools::ExpandRegistryValues(std::string& source)
  396. {
  397. #if defined(_WIN32) && !defined(__CYGWIN__)
  398. // Regular expression to match anything inside [...] that begins in HKEY.
  399. // Note that there is a special rule for regular expressions to match a
  400. // close square-bracket inside a list delimited by square brackets.
  401. // The "[^]]" part of this expression will match any character except
  402. // a close square-bracket. The ']' character must be the first in the
  403. // list of characters inside the [^...] block of the expression.
  404. cmRegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  405. // check for black line or comment
  406. while (regEntry.find(source))
  407. {
  408. // the arguments are the second match
  409. std::string key = regEntry.match(1);
  410. std::string val;
  411. if (ReadRegistryValue(key.c_str(), val))
  412. {
  413. std::string reg = "[";
  414. reg += key + "]";
  415. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  416. }
  417. else
  418. {
  419. std::string reg = "[";
  420. reg += key + "]";
  421. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  422. }
  423. }
  424. #endif
  425. }
  426. std::string cmSystemTools::EscapeQuotes(const char* str)
  427. {
  428. std::string result = "";
  429. for(const char* ch = str; *ch != '\0'; ++ch)
  430. {
  431. if(*ch == '"')
  432. {
  433. result += '\\';
  434. }
  435. result += *ch;
  436. }
  437. return result;
  438. }
  439. bool cmSystemTools::SameFile(const char* file1, const char* file2)
  440. {
  441. #ifdef _WIN32
  442. HANDLE hFile1, hFile2;
  443. hFile1 = CreateFile( file1,
  444. GENERIC_READ,
  445. FILE_SHARE_READ ,
  446. NULL,
  447. OPEN_EXISTING,
  448. FILE_FLAG_BACKUP_SEMANTICS,
  449. NULL
  450. );
  451. hFile2 = CreateFile( file2,
  452. GENERIC_READ,
  453. FILE_SHARE_READ,
  454. NULL,
  455. OPEN_EXISTING,
  456. FILE_FLAG_BACKUP_SEMANTICS,
  457. NULL
  458. );
  459. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  460. {
  461. if(hFile1 != INVALID_HANDLE_VALUE)
  462. {
  463. CloseHandle(hFile1);
  464. }
  465. if(hFile2 != INVALID_HANDLE_VALUE)
  466. {
  467. CloseHandle(hFile2);
  468. }
  469. return false;
  470. }
  471. BY_HANDLE_FILE_INFORMATION fiBuf1;
  472. BY_HANDLE_FILE_INFORMATION fiBuf2;
  473. GetFileInformationByHandle( hFile1, &fiBuf1 );
  474. GetFileInformationByHandle( hFile2, &fiBuf2 );
  475. CloseHandle(hFile1);
  476. CloseHandle(hFile2);
  477. return (fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  478. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  479. #else
  480. struct stat fileStat1, fileStat2;
  481. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  482. {
  483. // see if the files are the same file
  484. // check the device inode and size
  485. if(fileStat2.st_dev == fileStat1.st_dev &&
  486. fileStat2.st_ino == fileStat1.st_ino &&
  487. fileStat2.st_size == fileStat1.st_size
  488. )
  489. {
  490. return true;
  491. }
  492. }
  493. return false;
  494. #endif
  495. }
  496. // return true if the file exists
  497. bool cmSystemTools::FileExists(const char* filename)
  498. {
  499. struct stat fs;
  500. if (stat(filename, &fs) != 0)
  501. {
  502. return false;
  503. }
  504. else
  505. {
  506. return true;
  507. }
  508. }
  509. // Return a capitalized string (i.e the first letter is uppercased, all other
  510. // are lowercased)
  511. std::string cmSystemTools::Capitalized(const std::string& s)
  512. {
  513. std::string n;
  514. n.resize(s.size());
  515. n[0] = toupper(s[0]);
  516. for (size_t i = 1; i < s.size(); i++)
  517. {
  518. n[i] = tolower(s[i]);
  519. }
  520. return n;
  521. }
  522. // Return a lower case string
  523. std::string cmSystemTools::LowerCase(const std::string& s)
  524. {
  525. std::string n;
  526. n.resize(s.size());
  527. for (size_t i = 0; i < s.size(); i++)
  528. {
  529. n[i] = tolower(s[i]);
  530. }
  531. return n;
  532. }
  533. // Return a lower case string
  534. std::string cmSystemTools::UpperCase(const std::string& s)
  535. {
  536. std::string n;
  537. n.resize(s.size());
  538. for (size_t i = 0; i < s.size(); i++)
  539. {
  540. n[i] = toupper(s[i]);
  541. }
  542. return n;
  543. }
  544. // convert windows slashes to unix slashes
  545. void cmSystemTools::ConvertToUnixSlashes(std::string& path)
  546. {
  547. std::string::size_type pos = 0;
  548. while((pos = path.find('\\', pos)) != std::string::npos)
  549. {
  550. path[pos] = '/';
  551. pos++;
  552. }
  553. // remove any trailing slash
  554. if(path.size() && path[path.size()-1] == '/')
  555. {
  556. path = path.substr(0, path.size()-1);
  557. }
  558. // if there is a tilda ~ then replace it with HOME
  559. if(path.find("~") == 0)
  560. {
  561. if (getenv("HOME"))
  562. {
  563. path = std::string(getenv("HOME")) + path.substr(1);
  564. }
  565. }
  566. // if there is a /tmp_mnt in a path get rid of it!
  567. // stupid sgi's
  568. if(path.find("/tmp_mnt") == 0)
  569. {
  570. path = path.substr(8);
  571. }
  572. }
  573. // change // to /, and escape any spaces in the path
  574. std::string cmSystemTools::ConvertToUnixOutputPath(const char* path)
  575. {
  576. std::string ret = path;
  577. // remove // except at the beginning might be a cygwin drive
  578. std::string::size_type pos = 1;
  579. while((pos = ret.find("//", pos)) != std::string::npos)
  580. {
  581. ret.erase(pos, 1);
  582. }
  583. // now escape spaces if there is a space in the path
  584. if(ret.find(" ") != std::string::npos)
  585. {
  586. std::string result = "";
  587. char lastch = 1;
  588. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  589. {
  590. // if it is already escaped then don't try to escape it again
  591. if(*ch == ' ' && lastch != '\\')
  592. {
  593. result += '\\';
  594. }
  595. result += *ch;
  596. lastch = *ch;
  597. }
  598. ret = result;
  599. }
  600. return ret;
  601. }
  602. std::string cmSystemTools::EscapeSpaces(const char* str)
  603. {
  604. #if defined(_WIN32) && !defined(__CYGWIN__)
  605. std::string result;
  606. // if there are spaces
  607. std::string temp = str;
  608. if (temp.find(" ") != std::string::npos &&
  609. temp.find("\"")==std::string::npos)
  610. {
  611. result = "\"";
  612. result += str;
  613. result += "\"";
  614. return result;
  615. }
  616. return str;
  617. #else
  618. std::string result = "";
  619. for(const char* ch = str; *ch != '\0'; ++ch)
  620. {
  621. if(*ch == ' ')
  622. {
  623. result += '\\';
  624. }
  625. result += *ch;
  626. }
  627. return result;
  628. #endif
  629. }
  630. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  631. {
  632. #if defined(_WIN32) && !defined(__CYGWIN__)
  633. return cmSystemTools::ConvertToWindowsOutputPath(path);
  634. #else
  635. return cmSystemTools::ConvertToUnixOutputPath(path);
  636. #endif
  637. }
  638. // remove double slashes not at the start
  639. std::string cmSystemTools::ConvertToWindowsOutputPath(const char* path)
  640. {
  641. std::string ret = path;
  642. std::string::size_type pos = 0;
  643. // first convert all of the slashes
  644. while((pos = ret.find('/', pos)) != std::string::npos)
  645. {
  646. ret[pos] = '\\';
  647. pos++;
  648. }
  649. // check for really small paths
  650. if(ret.size() < 2)
  651. {
  652. return ret;
  653. }
  654. // now clean up a bit and remove double slashes
  655. // Only if it is not the first position in the path which is a network
  656. // path on windows
  657. pos = 1; // start at position 1
  658. while((pos = ret.find("\\\\", pos)) != std::string::npos)
  659. {
  660. ret.erase(pos, 1);
  661. }
  662. // now double quote the path if it has spaces in it
  663. // and is not already double quoted
  664. if(ret.find(" ") != std::string::npos
  665. && ret[0] != '\"')
  666. {
  667. std::string result;
  668. result = "\"" + ret + "\"";
  669. ret = result;
  670. }
  671. return ret;
  672. }
  673. bool cmSystemTools::ParseFunction(std::ifstream& fin,
  674. std::string& name,
  675. std::vector<std::string>& arguments,
  676. const char* filename,
  677. bool& parseError)
  678. {
  679. parseError = false;
  680. name = "";
  681. arguments = std::vector<std::string>();
  682. const int BUFFER_SIZE = 4096;
  683. char inbuffer[BUFFER_SIZE];
  684. if(!fin)
  685. {
  686. return false;
  687. }
  688. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  689. {
  690. cmRegularExpression blankLine("^[ \t\r]*$");
  691. cmRegularExpression comment("^[ \t]*#.*$");
  692. cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t\r]*$");
  693. cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
  694. cmRegularExpression lastLine("^(.*)\\)[ \t\r]*$");
  695. // check for black line or comment
  696. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  697. {
  698. return false;
  699. }
  700. // look for a oneline fun(arg arg2)
  701. else if(oneLiner.find(inbuffer))
  702. {
  703. // the arguments are the second match
  704. std::string args = oneLiner.match(2);
  705. name = oneLiner.match(1);
  706. // break up the arguments
  707. cmSystemTools::GetArguments(args, arguments);
  708. return true;
  709. }
  710. // look for a start of a multiline with no trailing ")" fun(arg arg2
  711. else if(multiLine.find(inbuffer))
  712. {
  713. name = multiLine.match(1);
  714. std::string args = multiLine.match(2);
  715. cmSystemTools::GetArguments(args, arguments);
  716. // Read lines until the closing paren is hit
  717. bool done = false;
  718. while(!done)
  719. {
  720. // read lines until the end paren is found
  721. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  722. {
  723. // Check for comment lines and ignore them.
  724. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  725. { continue; }
  726. // Is this the last line?
  727. if(lastLine.find(inbuffer))
  728. {
  729. done = true;
  730. std::string args = lastLine.match(1);
  731. cmSystemTools::GetArguments(args, arguments);
  732. }
  733. else
  734. {
  735. std::string line = inbuffer;
  736. cmSystemTools::GetArguments(line, arguments);
  737. }
  738. }
  739. else
  740. {
  741. parseError = true;
  742. cmSystemTools::Error("Parse error in read function missing end )\nIn File: ",
  743. filename, "\nCurrent line:", inbuffer);
  744. return false;
  745. }
  746. }
  747. return true;
  748. }
  749. else
  750. {
  751. parseError = true;
  752. cmSystemTools::Error("Parse error in read function\nIn file:",
  753. filename, "\nCurrent line:", inbuffer);
  754. return false;
  755. }
  756. }
  757. return false;
  758. }
  759. void cmSystemTools::GetArguments(std::string& line,
  760. std::vector<std::string>& arguments)
  761. {
  762. // Match a normal argument (not quoted, no spaces).
  763. cmRegularExpression normalArgument("[ \t]*(([^ \t\r\\]|[\\].)+)[ \t\r]*");
  764. // Match a quoted argument (surrounded by double quotes, spaces allowed).
  765. cmRegularExpression quotedArgument("[ \t]*(\"([^\"\\]|[\\].)*\")[ \t\r]*");
  766. bool done = false;
  767. while(!done)
  768. {
  769. std::string arg;
  770. std::string::size_type endpos;
  771. bool foundQuoted = quotedArgument.find(line.c_str());
  772. bool foundNormal = normalArgument.find(line.c_str());
  773. if(foundQuoted && foundNormal)
  774. {
  775. // Both matches were found. Take the earlier one.
  776. // Favor double-quoted version if there is a tie.
  777. if(normalArgument.start(1) < quotedArgument.start(1))
  778. {
  779. arg = normalArgument.match(1);
  780. endpos = normalArgument.end(1);
  781. }
  782. else
  783. {
  784. arg = quotedArgument.match(1);
  785. endpos = quotedArgument.end(1);
  786. // Strip off the double quotes on the ends.
  787. arg = arg.substr(1, arg.length()-2);
  788. }
  789. }
  790. else if (foundQuoted)
  791. {
  792. arg = quotedArgument.match(1);
  793. endpos = quotedArgument.end(1);
  794. // Strip off the double quotes on the ends.
  795. arg = arg.substr(1, arg.length()-2);
  796. }
  797. else if(foundNormal)
  798. {
  799. arg = normalArgument.match(1);
  800. endpos = normalArgument.end(1);
  801. }
  802. else
  803. {
  804. done = true;
  805. }
  806. if(!done)
  807. {
  808. arguments.push_back(cmSystemTools::RemoveEscapes(arg.c_str()));
  809. line = line.substr(endpos, line.length() - endpos);
  810. }
  811. }
  812. }
  813. std::string cmSystemTools::RemoveEscapes(const char* s)
  814. {
  815. std::string result = "";
  816. for(const char* ch = s; *ch; ++ch)
  817. {
  818. if(*ch == '\\' && *(ch+1) != ';')
  819. {
  820. ++ch;
  821. switch (*ch)
  822. {
  823. case '\\': result.insert(result.end(), '\\'); break;
  824. case '"': result.insert(result.end(), '"'); break;
  825. case ' ': result.insert(result.end(), ' '); break;
  826. case 't': result.insert(result.end(), '\t'); break;
  827. case 'n': result.insert(result.end(), '\n'); break;
  828. case 'r': result.insert(result.end(), '\r'); break;
  829. case '0': result.insert(result.end(), '\0'); break;
  830. case '\0':
  831. {
  832. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  833. return result;
  834. }
  835. default:
  836. {
  837. std::string chStr(1, *ch);
  838. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  839. "\nin argument ", s);
  840. }
  841. }
  842. }
  843. else
  844. {
  845. result.insert(result.end(), *ch);
  846. }
  847. }
  848. return result;
  849. }
  850. void cmSystemTools::Error(const char* m1, const char* m2,
  851. const char* m3, const char* m4)
  852. {
  853. std::string message = "CMake Error: ";
  854. if(m1)
  855. {
  856. message += m1;
  857. }
  858. if(m2)
  859. {
  860. message += m2;
  861. }
  862. if(m3)
  863. {
  864. message += m3;
  865. }
  866. if(m4)
  867. {
  868. message += m4;
  869. }
  870. cmSystemTools::s_ErrorOccured = true;
  871. cmSystemTools::Message(message.c_str(),"Error");
  872. }
  873. void cmSystemTools::SetErrorCallback(ErrorCallback f)
  874. {
  875. s_ErrorCallback = f;
  876. }
  877. void cmSystemTools::Message(const char* m1, const char *title)
  878. {
  879. if(s_DisableMessages)
  880. {
  881. return;
  882. }
  883. if(s_ErrorCallback)
  884. {
  885. (*s_ErrorCallback)(m1, title, s_DisableMessages);
  886. return;
  887. }
  888. else
  889. {
  890. std::cerr << m1 << std::endl;
  891. }
  892. }
  893. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  894. const char* destination)
  895. {
  896. if(cmSystemTools::FilesDiffer(source, destination))
  897. {
  898. cmSystemTools::cmCopyFile(source, destination);
  899. return true;
  900. }
  901. return false;
  902. }
  903. bool cmSystemTools::FilesDiffer(const char* source,
  904. const char* destination)
  905. {
  906. struct stat statSource;
  907. if (stat(source, &statSource) != 0)
  908. {
  909. return true;
  910. }
  911. struct stat statDestination;
  912. if (stat(destination, &statDestination) != 0)
  913. {
  914. return true;
  915. }
  916. if(statSource.st_size != statDestination.st_size)
  917. {
  918. return true;
  919. }
  920. if(statSource.st_size == 0)
  921. {
  922. return false;
  923. }
  924. #if defined(_WIN32) || defined(__CYGWIN__)
  925. std::ifstream finSource(source,
  926. std::ios::binary | std::ios::in);
  927. std::ifstream finDestination(destination,
  928. std::ios::binary | std::ios::in);
  929. #else
  930. std::ifstream finSource(source);
  931. std::ifstream finDestination(destination);
  932. #endif
  933. if(!finSource || !finDestination)
  934. {
  935. return true;
  936. }
  937. char* source_buf = new char[statSource.st_size];
  938. char* dest_buf = new char[statSource.st_size];
  939. finSource.read(source_buf, statSource.st_size);
  940. finDestination.read(dest_buf, statSource.st_size);
  941. if(statSource.st_size != finSource.gcount() ||
  942. statSource.st_size != finDestination.gcount())
  943. {
  944. std::strstream msg;
  945. msg << "FilesDiffer failed to read files (allocated: "
  946. << statSource.st_size << ", read source: " << finSource.gcount()
  947. << ", read dest: " << finDestination.gcount() << std::ends;
  948. cmSystemTools::Error(msg.str());
  949. delete [] msg.str();
  950. delete [] source_buf;
  951. delete [] dest_buf;
  952. return false;
  953. }
  954. int ret = memcmp((const void*)source_buf,
  955. (const void*)dest_buf,
  956. statSource.st_size);
  957. delete [] dest_buf;
  958. delete [] source_buf;
  959. return ret != 0;
  960. }
  961. /**
  962. * Copy a file named by "source" to the file named by "destination".
  963. */
  964. void cmSystemTools::cmCopyFile(const char* source,
  965. const char* destination)
  966. {
  967. const int bufferSize = 4096;
  968. char buffer[bufferSize];
  969. // If destination is a directory, try to create a file with the same
  970. // name as the source in that directory.
  971. std::string new_destination;
  972. if(cmSystemTools::FileExists(destination) &&
  973. cmSystemTools::FileIsDirectory(destination))
  974. {
  975. new_destination = destination;
  976. cmSystemTools::ConvertToUnixSlashes(new_destination);
  977. new_destination += '/';
  978. std::string source_name = source;
  979. new_destination += cmSystemTools::GetFilenameName(source_name);
  980. destination = new_destination.c_str();
  981. }
  982. // Create destination directory
  983. std::string destination_dir = destination;
  984. destination_dir = cmSystemTools::GetFilenamePath(destination_dir);
  985. cmSystemTools::MakeDirectory(destination_dir.c_str());
  986. // Open files
  987. #if defined(_WIN32) || defined(__CYGWIN__)
  988. std::ifstream fin(source,
  989. std::ios::binary | std::ios::in);
  990. #else
  991. std::ifstream fin(source);
  992. #endif
  993. if(!fin)
  994. {
  995. cmSystemTools::Error("CopyFile failed to open input file \"",
  996. source, "\"");
  997. return;
  998. }
  999. #if defined(_WIN32) || defined(__CYGWIN__)
  1000. std::ofstream fout(destination,
  1001. std::ios::binary | std::ios::out | std::ios::trunc);
  1002. #else
  1003. std::ofstream fout(destination,
  1004. std::ios::out | std::ios::trunc);
  1005. #endif
  1006. if(!fout)
  1007. {
  1008. cmSystemTools::Error("CopyFile failed to open output file \"",
  1009. destination, "\"");
  1010. return;
  1011. }
  1012. // This copy loop is very sensitive on certain platforms with
  1013. // slightly broken stream libraries (like HPUX). Normally, it is
  1014. // incorrect to not check the error condition on the fin.read()
  1015. // before using the data, but the fin.gcount() will be zero if an
  1016. // error occurred. Therefore, the loop should be safe everywhere.
  1017. while(fin)
  1018. {
  1019. fin.read(buffer, bufferSize);
  1020. if(fin.gcount())
  1021. {
  1022. fout.write(buffer, fin.gcount());
  1023. }
  1024. }
  1025. fin.close();
  1026. fout.close();
  1027. // More checks
  1028. struct stat statSource, statDestination;
  1029. if (stat(source, &statSource) != 0 ||
  1030. stat(destination, &statDestination) != 0)
  1031. {
  1032. cmSystemTools::Error("CopyFile failed to copy files!");
  1033. }
  1034. if (statSource.st_size != statDestination.st_size)
  1035. {
  1036. std::strstream msg;
  1037. msg << "CopyFile failed to copy files (sizes differ, source: "
  1038. << statSource.st_size << " , dest: " << statDestination.st_size
  1039. << std::ends;
  1040. cmSystemTools::Error(msg.str());
  1041. delete [] msg.str();
  1042. }
  1043. }
  1044. // return true if the file exists
  1045. long int cmSystemTools::ModifiedTime(const char* filename)
  1046. {
  1047. struct stat fs;
  1048. if (stat(filename, &fs) != 0)
  1049. {
  1050. return 0;
  1051. }
  1052. else
  1053. {
  1054. return (long int)fs.st_mtime;
  1055. }
  1056. }
  1057. bool cmSystemTools::RemoveFile(const char* source)
  1058. {
  1059. return unlink(source) != 0 ? false : true;
  1060. }
  1061. bool cmSystemTools::IsOn(const char* val)
  1062. {
  1063. if (!val)
  1064. {
  1065. return false;
  1066. }
  1067. std::basic_string<char> v = val;
  1068. for(std::basic_string<char>::iterator c = v.begin();
  1069. c != v.end(); c++)
  1070. {
  1071. *c = toupper(*c);
  1072. }
  1073. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  1074. }
  1075. bool cmSystemTools::IsOff(const char* val)
  1076. {
  1077. if (!val || strlen(val) == 0)
  1078. {
  1079. return true;
  1080. }
  1081. std::basic_string<char> v = val;
  1082. for(std::basic_string<char>::iterator c = v.begin();
  1083. c != v.end(); c++)
  1084. {
  1085. *c = toupper(*c);
  1086. }
  1087. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  1088. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  1089. }
  1090. bool cmSystemTools::RunCommand(const char* command,
  1091. std::string& output,
  1092. const char* dir,
  1093. bool verbose)
  1094. {
  1095. int foo;
  1096. return cmSystemTools::RunCommand(command, output, foo, dir, verbose);
  1097. }
  1098. #if defined(WIN32) && !defined(__CYGWIN__)
  1099. // use this for shell commands like echo and dir
  1100. bool RunCommandViaSystem(const char* command,
  1101. const char* dir,
  1102. std::string& output,
  1103. int& retVal,
  1104. bool verbose)
  1105. {
  1106. const int BUFFER_SIZE = 4096;
  1107. char buffer[BUFFER_SIZE];
  1108. std::string commandInDir;
  1109. if(dir)
  1110. {
  1111. commandInDir = "cd ";
  1112. commandInDir += dir;
  1113. commandInDir += " && ";
  1114. commandInDir += command;
  1115. }
  1116. else
  1117. {
  1118. commandInDir = command;
  1119. }
  1120. command = commandInDir.c_str();
  1121. std::string commandToFile = command;
  1122. commandToFile += " > ";
  1123. std::string tempFile;
  1124. tempFile += _tempnam(0, "cmake");
  1125. commandToFile += tempFile;
  1126. retVal = system(commandToFile.c_str());
  1127. std::ifstream fin(tempFile.c_str());
  1128. if(!fin)
  1129. {
  1130. if(verbose)
  1131. {
  1132. std::string errormsg = "RunCommand produced no output: command: \"";
  1133. errormsg += command;
  1134. errormsg += "\"";
  1135. errormsg += "\nOutput file: ";
  1136. errormsg += tempFile;
  1137. cmSystemTools::Error(errormsg.c_str());
  1138. }
  1139. fin.close();
  1140. cmSystemTools::RemoveFile(tempFile.c_str());
  1141. return false;
  1142. }
  1143. bool multiLine = false;
  1144. while(fin)
  1145. {
  1146. fin.getline(buffer, BUFFER_SIZE);
  1147. output += buffer;
  1148. if(multiLine)
  1149. {
  1150. output += "\n";
  1151. }
  1152. multiLine = true;
  1153. }
  1154. fin.close();
  1155. cmSystemTools::RemoveFile(tempFile.c_str());
  1156. return true;
  1157. }
  1158. #endif // endif WIN32 not CYGWIN
  1159. // run a command unix uses popen (easy)
  1160. // windows uses system and ShortPath
  1161. bool cmSystemTools::RunCommand(const char* command,
  1162. std::string& output,
  1163. int &retVal,
  1164. const char* dir,
  1165. bool verbose)
  1166. {
  1167. if(s_DisableRunCommandOutput)
  1168. {
  1169. verbose = false;
  1170. }
  1171. #if defined(WIN32) && !defined(__CYGWIN__)
  1172. // if the command does not start with a quote, then
  1173. // try to find the program, and if the program can not be
  1174. // found use system to run the command as it must be a built in
  1175. // shell command like echo or dir
  1176. int count = 0;
  1177. if(command[0] == '\"')
  1178. {
  1179. // count the number of quotes
  1180. for(const char* s = command; *s != 0; ++s)
  1181. {
  1182. if(*s == '\"')
  1183. {
  1184. count++;
  1185. if(count > 2)
  1186. {
  1187. break;
  1188. }
  1189. }
  1190. }
  1191. // if there are more than two double quotes use
  1192. // GetShortPathName, the cmd.exe program in windows which
  1193. // is used by system fails to execute if there are more than
  1194. // one set of quotes in the arguments
  1195. if(count > 2)
  1196. {
  1197. cmRegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  1198. if(quoted.find(command))
  1199. {
  1200. std::string shortCmd;
  1201. std::string cmd = quoted.match(1);
  1202. std::string args = quoted.match(2);
  1203. if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  1204. {
  1205. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  1206. return false;
  1207. }
  1208. shortCmd += " ";
  1209. shortCmd += args;
  1210. return RunCommandViaSystem(shortCmd.c_str(), dir,
  1211. output, retVal, verbose);
  1212. }
  1213. else
  1214. {
  1215. cmSystemTools::Error("Could not parse command line with quotes ",
  1216. command);
  1217. }
  1218. }
  1219. }
  1220. // if there is only one set of quotes or no quotes then just run the command
  1221. return RunCommandViaSystem(command, dir, output, retVal, verbose);
  1222. #else
  1223. // if only popen worked on windows.....
  1224. std::string commandInDir;
  1225. if(dir)
  1226. {
  1227. commandInDir = "cd ";
  1228. commandInDir += dir;
  1229. commandInDir += " && ";
  1230. commandInDir += command;
  1231. }
  1232. else
  1233. {
  1234. commandInDir = command;
  1235. }
  1236. command = commandInDir.c_str();
  1237. const int BUFFER_SIZE = 4096;
  1238. char buffer[BUFFER_SIZE];
  1239. if(verbose)
  1240. {
  1241. std::cout << "running " << command << std::endl;
  1242. }
  1243. fflush(stdout);
  1244. fflush(stderr);
  1245. FILE* cpipe = popen(command, "r");
  1246. if(!cpipe)
  1247. {
  1248. return false;
  1249. }
  1250. fgets(buffer, BUFFER_SIZE, cpipe);
  1251. while(!feof(cpipe))
  1252. {
  1253. if(verbose)
  1254. {
  1255. std::cout << buffer << std::flush;
  1256. }
  1257. output += buffer;
  1258. fgets(buffer, BUFFER_SIZE, cpipe);
  1259. }
  1260. retVal = pclose(cpipe);
  1261. retVal = WEXITSTATUS(retVal);
  1262. return true;
  1263. #endif
  1264. }
  1265. /**
  1266. * Find the file the given name. Searches the given path and then
  1267. * the system search path. Returns the full path to the file if it is
  1268. * found. Otherwise, the empty string is returned.
  1269. */
  1270. std::string cmSystemTools::FindFile(const char* name,
  1271. const std::vector<std::string>& userPaths)
  1272. {
  1273. // Add the system search path to our path.
  1274. std::vector<std::string> path = userPaths;
  1275. cmSystemTools::GetPath(path);
  1276. std::string tryPath;
  1277. for(std::vector<std::string>::const_iterator p = path.begin();
  1278. p != path.end(); ++p)
  1279. {
  1280. tryPath = *p;
  1281. tryPath += "/";
  1282. tryPath += name;
  1283. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1284. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1285. {
  1286. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1287. }
  1288. }
  1289. // Couldn't find the file.
  1290. return "";
  1291. }
  1292. /**
  1293. * Find the executable with the given name. Searches the given path and then
  1294. * the system search path. Returns the full path to the executable if it is
  1295. * found. Otherwise, the empty string is returned.
  1296. */
  1297. std::string cmSystemTools::FindProgram(const char* name,
  1298. const std::vector<std::string>& userPaths)
  1299. {
  1300. // See if the executable exists as written.
  1301. if(cmSystemTools::FileExists(name) &&
  1302. !cmSystemTools::FileIsDirectory(name))
  1303. {
  1304. return cmSystemTools::CollapseFullPath(name);
  1305. }
  1306. std::string tryPath = name;
  1307. tryPath += cmSystemTools::GetExecutableExtension();
  1308. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1309. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1310. {
  1311. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1312. }
  1313. // Add the system search path to our path.
  1314. std::vector<std::string> path = userPaths;
  1315. cmSystemTools::GetPath(path);
  1316. for(std::vector<std::string>::const_iterator p = path.begin();
  1317. p != path.end(); ++p)
  1318. {
  1319. tryPath = *p;
  1320. tryPath += "/";
  1321. tryPath += name;
  1322. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1323. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1324. {
  1325. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1326. }
  1327. #ifdef _WIN32
  1328. tryPath += ".com";
  1329. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1330. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1331. {
  1332. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1333. }
  1334. tryPath = *p;
  1335. tryPath += "/";
  1336. tryPath += name;
  1337. #endif
  1338. tryPath += cmSystemTools::GetExecutableExtension();
  1339. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1340. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1341. {
  1342. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1343. }
  1344. }
  1345. // Couldn't find the program.
  1346. return "";
  1347. }
  1348. /**
  1349. * Find the library with the given name. Searches the given path and then
  1350. * the system search path. Returns the full path to the library if it is
  1351. * found. Otherwise, the empty string is returned.
  1352. */
  1353. std::string cmSystemTools::FindLibrary(const char* name,
  1354. const std::vector<std::string>& userPaths)
  1355. {
  1356. // See if the executable exists as written.
  1357. if(cmSystemTools::FileExists(name))
  1358. {
  1359. return cmSystemTools::CollapseFullPath(name);
  1360. }
  1361. // Add the system search path to our path.
  1362. std::vector<std::string> path = userPaths;
  1363. cmSystemTools::GetPath(path);
  1364. std::string tryPath;
  1365. for(std::vector<std::string>::const_iterator p = path.begin();
  1366. p != path.end(); ++p)
  1367. {
  1368. #if defined(_WIN32) && !defined(__CYGWIN__)
  1369. tryPath = *p;
  1370. tryPath += "/";
  1371. tryPath += name;
  1372. tryPath += ".lib";
  1373. if(cmSystemTools::FileExists(tryPath.c_str()))
  1374. {
  1375. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1376. }
  1377. #else
  1378. tryPath = *p;
  1379. tryPath += "/lib";
  1380. tryPath += name;
  1381. tryPath += ".so";
  1382. if(cmSystemTools::FileExists(tryPath.c_str()))
  1383. {
  1384. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1385. }
  1386. tryPath = *p;
  1387. tryPath += "/lib";
  1388. tryPath += name;
  1389. tryPath += ".a";
  1390. if(cmSystemTools::FileExists(tryPath.c_str()))
  1391. {
  1392. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1393. }
  1394. tryPath = *p;
  1395. tryPath += "/lib";
  1396. tryPath += name;
  1397. tryPath += ".sl";
  1398. if(cmSystemTools::FileExists(tryPath.c_str()))
  1399. {
  1400. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1401. }
  1402. #endif
  1403. }
  1404. // Couldn't find the library.
  1405. return "";
  1406. }
  1407. bool cmSystemTools::FileIsDirectory(const char* name)
  1408. {
  1409. struct stat fs;
  1410. if(stat(name, &fs) == 0)
  1411. {
  1412. #if _WIN32
  1413. return ((fs.st_mode & _S_IFDIR) != 0);
  1414. #else
  1415. return S_ISDIR(fs.st_mode);
  1416. #endif
  1417. }
  1418. else
  1419. {
  1420. return false;
  1421. }
  1422. }
  1423. int cmSystemTools::ChangeDirectory(const char *dir)
  1424. {
  1425. return Chdir(dir);
  1426. }
  1427. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1428. {
  1429. char buf[2048];
  1430. std::string path = Getcwd(buf, 2048);
  1431. return path;
  1432. }
  1433. /**
  1434. * Given the path to a program executable, get the directory part of the path with the
  1435. * file stripped off. If there is no directory part, the empty string is returned.
  1436. */
  1437. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1438. {
  1439. std::string dir, file;
  1440. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1441. return dir;
  1442. }
  1443. /**
  1444. * Given the path to a program executable, get the directory part of the path
  1445. * with the file stripped off. If there is no directory part, the empty
  1446. * string is returned.
  1447. */
  1448. void cmSystemTools::SplitProgramPath(const char* in_name,
  1449. std::string& dir,
  1450. std::string& file)
  1451. {
  1452. dir = in_name;
  1453. file = "";
  1454. cmSystemTools::ConvertToUnixSlashes(dir);
  1455. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1456. {
  1457. std::string::size_type slashPos = dir.rfind("/");
  1458. if(slashPos != std::string::npos)
  1459. {
  1460. file = dir.substr(slashPos+1);
  1461. dir = dir.substr(0, slashPos);
  1462. }
  1463. else
  1464. {
  1465. file = dir;
  1466. dir = "";
  1467. }
  1468. }
  1469. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1470. {
  1471. std::string oldDir = in_name;
  1472. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1473. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1474. oldDir.c_str(), "\nDirectory not found: ",
  1475. dir.c_str());
  1476. dir = in_name;
  1477. return;
  1478. }
  1479. }
  1480. /**
  1481. * Given a path to a file or directory, convert it to a full path.
  1482. * This collapses away relative paths. The full path is returned.
  1483. */
  1484. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1485. {
  1486. std::string dir, file;
  1487. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1488. #ifdef _WIN32
  1489. // Ultra-hack warning:
  1490. // This changes to the target directory, saves the working directory,
  1491. // and then changes back to the original working directory.
  1492. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1493. if(dir != "") { Chdir(dir.c_str()); }
  1494. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1495. Chdir(cwd.c_str());
  1496. cmSystemTools::ConvertToUnixSlashes(newDir);
  1497. std::string newPath = newDir+"/"+file;
  1498. return newPath;
  1499. #else
  1500. # ifdef MAXPATHLEN
  1501. char resolved_name[MAXPATHLEN];
  1502. # else
  1503. # ifdef PATH_MAX
  1504. char resolved_name[PATH_MAX];
  1505. # else
  1506. char resolved_name[5024];
  1507. # endif
  1508. # endif
  1509. if(dir != "")
  1510. {
  1511. realpath(dir.c_str(), resolved_name);
  1512. dir = resolved_name;
  1513. }
  1514. else
  1515. {
  1516. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1517. }
  1518. if(file == "")
  1519. {
  1520. return dir;
  1521. }
  1522. return dir + "/" + file;
  1523. #endif
  1524. }
  1525. /**
  1526. * Return path of a full filename (no trailing slashes).
  1527. * Warning: returned path is converted to Unix slashes format.
  1528. */
  1529. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1530. {
  1531. std::string fn = filename;
  1532. cmSystemTools::ConvertToUnixSlashes(fn);
  1533. std::string::size_type slash_pos = fn.rfind("/");
  1534. if(slash_pos != std::string::npos)
  1535. {
  1536. return fn.substr(0, slash_pos);
  1537. }
  1538. else
  1539. {
  1540. return "";
  1541. }
  1542. }
  1543. /**
  1544. * Return file name of a full filename (i.e. file name without path).
  1545. */
  1546. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1547. {
  1548. std::string fn = filename;
  1549. cmSystemTools::ConvertToUnixSlashes(fn);
  1550. std::string::size_type slash_pos = fn.rfind("/");
  1551. if(slash_pos != std::string::npos)
  1552. {
  1553. return fn.substr(slash_pos + 1);
  1554. }
  1555. else
  1556. {
  1557. return filename;
  1558. }
  1559. }
  1560. /**
  1561. * Return file extension of a full filename (dot included).
  1562. * Warning: this is the longest extension (for example: .tar.gz)
  1563. */
  1564. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1565. {
  1566. std::string name = cmSystemTools::GetFilenameName(filename);
  1567. std::string::size_type dot_pos = name.find(".");
  1568. if(dot_pos != std::string::npos)
  1569. {
  1570. return name.substr(dot_pos);
  1571. }
  1572. else
  1573. {
  1574. return "";
  1575. }
  1576. }
  1577. /**
  1578. * Return file extension of a full filename (dot included).
  1579. */
  1580. std::string cmSystemTools::GetFilenameShortestExtension(const std::string& filename)
  1581. {
  1582. std::string name = cmSystemTools::GetFilenameName(filename);
  1583. std::string::size_type dot_pos = name.rfind(".");
  1584. if(dot_pos != std::string::npos)
  1585. {
  1586. return name.substr(dot_pos);
  1587. }
  1588. else
  1589. {
  1590. return "";
  1591. }
  1592. }
  1593. /**
  1594. * Return file name without extension of a full filename (i.e. without path).
  1595. * Warning: it considers the longest extension (for example: .tar.gz)
  1596. */
  1597. std::string cmSystemTools::GetFilenameNameWithoutExtension(const std::string& filename)
  1598. {
  1599. std::string name = cmSystemTools::GetFilenameName(filename);
  1600. std::string::size_type dot_pos = name.find(".");
  1601. if(dot_pos != std::string::npos)
  1602. {
  1603. return name.substr(0, dot_pos);
  1604. }
  1605. else
  1606. {
  1607. return name;
  1608. }
  1609. }
  1610. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1611. std::vector<std::string>& files)
  1612. {
  1613. cmDirectory d;
  1614. cmRegularExpression reg(regexp);
  1615. if (d.Load(directory))
  1616. {
  1617. size_t numf;
  1618. unsigned int i;
  1619. numf = d.GetNumberOfFiles();
  1620. for (i = 0; i < numf; i++)
  1621. {
  1622. std::string fname = d.GetFile(i);
  1623. if (reg.find(fname))
  1624. {
  1625. files.push_back(fname);
  1626. }
  1627. }
  1628. }
  1629. }
  1630. void cmSystemTools::GlobDirs(const char *fullPath,
  1631. std::vector<std::string>& files)
  1632. {
  1633. std::string path = fullPath;
  1634. std::string::size_type pos = path.find("/*");
  1635. if(pos == std::string::npos)
  1636. {
  1637. files.push_back(fullPath);
  1638. return;
  1639. }
  1640. std::string startPath = path.substr(0, pos);
  1641. std::string finishPath = path.substr(pos+2);
  1642. cmDirectory d;
  1643. if (d.Load(startPath.c_str()))
  1644. {
  1645. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1646. {
  1647. if((std::string(d.GetFile(i)) != ".")
  1648. && (std::string(d.GetFile(i)) != ".."))
  1649. {
  1650. std::string fname = startPath;
  1651. fname +="/";
  1652. fname += d.GetFile(i);
  1653. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1654. {
  1655. fname += finishPath;
  1656. cmSystemTools::GlobDirs(fname.c_str(), files);
  1657. }
  1658. }
  1659. }
  1660. }
  1661. }
  1662. void cmSystemTools::ExpandListArguments(std::vector<std::string> const& arguments,
  1663. std::vector<std::string>& newargs)
  1664. {
  1665. std::vector<std::string>::const_iterator i;
  1666. std::string newarg;
  1667. for(i = arguments.begin();i != arguments.end(); ++i)
  1668. {
  1669. // if there are no ; in the name then just copy the current string
  1670. if(i->find(';') == std::string::npos)
  1671. {
  1672. newargs.push_back(*i);
  1673. }
  1674. else
  1675. {
  1676. std::string::size_type start = 0;
  1677. std::string::size_type endpos = 0;
  1678. const std::string::size_type size = i->size();
  1679. // break up ; separated sections of the string into separate strings
  1680. while(endpos != size)
  1681. {
  1682. endpos = i->find(';', start);
  1683. if(endpos == std::string::npos)
  1684. {
  1685. endpos = i->size();
  1686. }
  1687. else
  1688. {
  1689. // skip right over escaped ; ( \; )
  1690. while((endpos != std::string::npos)
  1691. && (endpos > 0)
  1692. && ((*i)[endpos-1] == '\\') )
  1693. {
  1694. endpos = i->find(';', endpos+1);
  1695. }
  1696. if(endpos == std::string::npos)
  1697. {
  1698. endpos = i->size();
  1699. }
  1700. }
  1701. std::string::size_type len = endpos - start;
  1702. if (len > 0)
  1703. {
  1704. // check for a closing ] after the start position
  1705. if(i->find('[', start) == std::string::npos)
  1706. {
  1707. // if there is no [ in the string then keep it
  1708. newarg = i->substr(start, len);
  1709. }
  1710. else
  1711. {
  1712. int opencount = 0;
  1713. int closecount = 0;
  1714. for(std::string::size_type j = start; j < endpos; ++j)
  1715. {
  1716. if(i->at(j) == '[')
  1717. {
  1718. ++opencount;
  1719. }
  1720. else if (i->at(j) == ']')
  1721. {
  1722. ++closecount;
  1723. }
  1724. }
  1725. if(opencount != closecount)
  1726. {
  1727. // skip this one
  1728. endpos = i->find(';', endpos+1);
  1729. if(endpos == std::string::npos)
  1730. {
  1731. endpos = i->size();
  1732. }
  1733. len = endpos - start;
  1734. }
  1735. newarg = i->substr(start, len);
  1736. }
  1737. std::string::size_type pos = newarg.find("\\;");
  1738. if(pos != std::string::npos)
  1739. {
  1740. newarg.erase(pos, 1);
  1741. }
  1742. newargs.push_back(newarg);
  1743. }
  1744. start = endpos+1;
  1745. }
  1746. }
  1747. }
  1748. }
  1749. bool cmSystemTools::GetShortPath(const char* path, std::string& shortPath)
  1750. {
  1751. #if defined(WIN32) && !defined(__CYGWIN__)
  1752. const int size = int(strlen(path)) +1; // size of return
  1753. char *buffer = new char[size]; // create a buffer
  1754. buffer[0] = 0;
  1755. int ret = GetShortPathName(path, buffer, size);
  1756. if(buffer[0] == 0 || ret > size)
  1757. {
  1758. if(ret < size)
  1759. {
  1760. LPVOID lpMsgBuf;
  1761. FormatMessage(
  1762. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1763. FORMAT_MESSAGE_FROM_SYSTEM |
  1764. FORMAT_MESSAGE_IGNORE_INSERTS,
  1765. NULL,
  1766. GetLastError(),
  1767. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  1768. (LPTSTR) &lpMsgBuf,
  1769. 0,
  1770. NULL
  1771. );
  1772. cmSystemTools::Error((LPCTSTR)lpMsgBuf);
  1773. LocalFree( lpMsgBuf );
  1774. }
  1775. cmSystemTools::Error("Unable to get a short path: ", path);
  1776. return false;
  1777. }
  1778. else
  1779. {
  1780. shortPath = buffer;
  1781. delete [] buffer;
  1782. return true;
  1783. }
  1784. #else
  1785. shortPath = path;
  1786. return true;
  1787. #endif
  1788. }