cmSystemTools.cxx 46 KB

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