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