cmSystemTools.cxx 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  1. /*=========================================================================
  2. Program: Insight Segmentation & Registration Toolkit
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2001 Insight Consortium
  8. All rights reserved.
  9. Redistribution and use in source and binary forms, with or without
  10. modification, are permitted provided that the following conditions are met:
  11. * Redistributions of source code must retain the above copyright notice,
  12. this list of conditions and the following disclaimer.
  13. * Redistributions in binary form must reproduce the above copyright notice,
  14. this list of conditions and the following disclaimer in the documentation
  15. and/or other materials provided with the distribution.
  16. * The name of the Insight Consortium, nor the names of any consortium members,
  17. nor of any contributors, may be used to endorse or promote products derived
  18. from this software without specific prior written permission.
  19. * Modified source versions must be plainly marked as such, and must not be
  20. misrepresented as being the original software.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
  22. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24. ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
  25. ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  26. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  27. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  28. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  29. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. =========================================================================*/
  32. #include "cmSystemTools.h"
  33. #include "errno.h"
  34. #include "stdio.h"
  35. #include <sys/stat.h>
  36. #include "cmRegularExpression.h"
  37. #include <ctype.h>
  38. #include "cmDirectory.h"
  39. // support for realpath call
  40. #ifndef _WIN32
  41. #include <limits.h>
  42. #include <stdlib.h>
  43. #include <sys/param.h>
  44. #endif
  45. #if defined(_MSC_VER) || defined(__BORLANDC__)
  46. #include <windows.h>
  47. #include <direct.h>
  48. #define _unlink unlink
  49. inline int Mkdir(const char* dir)
  50. {
  51. return _mkdir(dir);
  52. }
  53. inline const char* Getcwd(char* buf, unsigned int len)
  54. {
  55. return _getcwd(buf, len);
  56. }
  57. inline int Chdir(const char* dir)
  58. {
  59. #if defined(__BORLANDC__)
  60. return chdir(dir);
  61. #else
  62. return _chdir(dir);
  63. #endif
  64. }
  65. #else
  66. #include <sys/types.h>
  67. #include <fcntl.h>
  68. #include <unistd.h>
  69. inline int Mkdir(const char* dir)
  70. {
  71. return mkdir(dir, 00777);
  72. }
  73. inline const char* Getcwd(char* buf, unsigned int len)
  74. {
  75. return getcwd(buf, len);
  76. }
  77. inline int Chdir(const char* dir)
  78. {
  79. return chdir(dir);
  80. }
  81. #endif
  82. bool cmSystemTools::s_ErrorOccured = false;
  83. void (*cmSystemTools::s_ErrorCallback)(const char*, const char*, bool&);
  84. // adds the elements of the env variable path to the arg passed in
  85. void cmSystemTools::GetPath(std::vector<std::string>& path)
  86. {
  87. #if defined(_WIN32) && !defined(__CYGWIN__)
  88. const char* pathSep = ";";
  89. #else
  90. const char* pathSep = ":";
  91. #endif
  92. std::string pathEnv = getenv("PATH");
  93. // A hack to make the below algorithm work.
  94. if(pathEnv[pathEnv.length()-1] != ':')
  95. {
  96. pathEnv += pathSep;
  97. }
  98. std::string::size_type start =0;
  99. bool done = false;
  100. while(!done)
  101. {
  102. std::string::size_type endpos = pathEnv.find(pathSep, start);
  103. if(endpos != std::string::npos)
  104. {
  105. path.push_back(pathEnv.substr(start, endpos-start));
  106. start = endpos+1;
  107. }
  108. else
  109. {
  110. done = true;
  111. }
  112. }
  113. for(std::vector<std::string>::iterator i = path.begin();
  114. i != path.end(); ++i)
  115. {
  116. cmSystemTools::ConvertToUnixSlashes(*i);
  117. }
  118. }
  119. const char* cmSystemTools::GetExecutableExtension()
  120. {
  121. #if defined(_WIN32) || defined(__CYGWIN__)
  122. return ".exe";
  123. #else
  124. return "";
  125. #endif
  126. }
  127. bool cmSystemTools::MakeDirectory(const char* path)
  128. {
  129. if(cmSystemTools::FileExists(path))
  130. {
  131. return true;
  132. }
  133. std::string dir = path;
  134. if(dir.size() == 0)
  135. {
  136. return false;
  137. }
  138. cmSystemTools::ConvertToUnixSlashes(dir);
  139. std::string::size_type pos = dir.find(':');
  140. if(pos == std::string::npos)
  141. {
  142. pos = 0;
  143. }
  144. std::string topdir;
  145. while((pos = dir.find('/', pos)) != std::string::npos)
  146. {
  147. topdir = dir.substr(0, pos);
  148. Mkdir(topdir.c_str());
  149. pos++;
  150. }
  151. if(dir[dir.size()-1] == '/')
  152. {
  153. topdir = dir.substr(0, dir.size());
  154. }
  155. else
  156. {
  157. topdir = dir;
  158. }
  159. if(Mkdir(topdir.c_str()) != 0)
  160. {
  161. // There is a bug in the Borland Run time library which makes MKDIR
  162. // return EACCES when it should return EEXISTS
  163. // if it is some other error besides directory exists
  164. // then return false
  165. if( (errno != EEXIST)
  166. #ifdef __BORLANDC__
  167. && (errno != EACCES)
  168. #endif
  169. )
  170. {
  171. cmSystemTools::Error("Faild to create directory:", path);
  172. return false;
  173. }
  174. }
  175. return true;
  176. }
  177. // replace replace with with as many times as it shows up in source.
  178. // write the result into source.
  179. void cmSystemTools::ReplaceString(std::string& source,
  180. const char* replace,
  181. const char* with)
  182. {
  183. int lengthReplace = strlen(replace);
  184. std::string rest;
  185. size_t start = source.find(replace);
  186. while(start != std::string::npos)
  187. {
  188. rest = source.substr(start+lengthReplace);
  189. source = source.substr(0, start);
  190. source += with;
  191. source += rest;
  192. start = source.find(replace, start + lengthReplace );
  193. }
  194. }
  195. #if defined(_WIN32) && !defined(__CYGWIN__)
  196. // Get the data of key value.
  197. // Example :
  198. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  199. // => will return the data of the "default" value of the key
  200. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  201. // => will return the data of the "Root" value of the key
  202. bool ReadAValue(std::string &res, const char *key)
  203. {
  204. // find the primary key
  205. std::string primary = key;
  206. std::string second;
  207. std::string valuename;
  208. size_t start = primary.find("\\");
  209. if (start == std::string::npos)
  210. {
  211. return false;
  212. }
  213. size_t valuenamepos = primary.find(";");
  214. if (valuenamepos != std::string::npos)
  215. {
  216. valuename = primary.substr(valuenamepos+1);
  217. }
  218. second = primary.substr(start+1, valuenamepos-start-1);
  219. primary = primary.substr(0, start);
  220. HKEY primaryKey;
  221. if (primary == "HKEY_CURRENT_USER")
  222. {
  223. primaryKey = HKEY_CURRENT_USER;
  224. }
  225. if (primary == "HKEY_CURRENT_CONFIG")
  226. {
  227. primaryKey = HKEY_CURRENT_CONFIG;
  228. }
  229. if (primary == "HKEY_CLASSES_ROOT")
  230. {
  231. primaryKey = HKEY_CLASSES_ROOT;
  232. }
  233. if (primary == "HKEY_LOCAL_MACHINE")
  234. {
  235. primaryKey = HKEY_LOCAL_MACHINE;
  236. }
  237. if (primary == "HKEY_USERS")
  238. {
  239. primaryKey = HKEY_USERS;
  240. }
  241. HKEY hKey;
  242. if(RegOpenKeyEx(primaryKey, second.c_str(),
  243. 0, KEY_READ, &hKey) != ERROR_SUCCESS)
  244. {
  245. return false;
  246. }
  247. else
  248. {
  249. DWORD dwType, dwSize;
  250. dwSize = 1023;
  251. char data[1024];
  252. if(RegQueryValueEx(hKey, (LPTSTR)valuename.c_str(), NULL, &dwType,
  253. (BYTE *)data, &dwSize) == ERROR_SUCCESS)
  254. {
  255. if (dwType == REG_SZ)
  256. {
  257. res = data;
  258. return true;
  259. }
  260. }
  261. }
  262. return false;
  263. }
  264. #endif
  265. // replace replace with with as many times as it shows up in source.
  266. // write the result into source.
  267. void cmSystemTools::ExpandRegistryValues(std::string& source)
  268. {
  269. #if defined(_WIN32) && !defined(__CYGWIN__)
  270. // Regular expression to match anything inside [...] that begins in HKEY.
  271. // Note that there is a special rule for regular expressions to match a
  272. // close square-bracket inside a list delimited by square brackets.
  273. // The "[^]]" part of this expression will match any character except
  274. // a close square-bracket. The ']' character must be the first in the
  275. // list of characters inside the [^...] block of the expression.
  276. cmRegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  277. // check for black line or comment
  278. while (regEntry.find(source))
  279. {
  280. // the arguments are the second match
  281. std::string key = regEntry.match(1);
  282. std::string val;
  283. if (ReadAValue(val,key.c_str()))
  284. {
  285. std::string reg = "[";
  286. reg += key + "]";
  287. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  288. }
  289. else
  290. {
  291. std::string reg = "[";
  292. reg += key + "]";
  293. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  294. }
  295. }
  296. #endif
  297. }
  298. std::string cmSystemTools::HandleNetworkPaths(const char* str)
  299. {
  300. #if defined(_WIN32) && !defined(__CYGWIN__)
  301. std::string result;
  302. // watch for network paths, MSVC can't seem to load //
  303. if (strlen(str) > 2 && str[0] == '/' && str[1] == '/')
  304. {
  305. result = "\\\\";
  306. result += (str + 2);
  307. }
  308. else
  309. {
  310. result += str;
  311. }
  312. #else
  313. std::string result = "";
  314. #endif
  315. return result;
  316. }
  317. std::string cmSystemTools::EscapeSpaces(const char* str)
  318. {
  319. #if defined(_WIN32) && !defined(__CYGWIN__)
  320. std::string result;
  321. // if there are spaces
  322. std::string temp = str;
  323. if (temp.find(" ") != std::string::npos)
  324. {
  325. // don't add quotes if they're already there
  326. if (temp.find("\"")==std::string::npos)
  327. {
  328. result = "\"";
  329. }
  330. result += cmSystemTools::HandleNetworkPaths(str);
  331. if (temp.find("\"")==std::string::npos)
  332. {
  333. result += "\"";
  334. }
  335. return result;
  336. }
  337. return cmSystemTools::HandleNetworkPaths(str);
  338. #else
  339. std::string result = "";
  340. for(const char* ch = str; *ch != '\0'; ++ch)
  341. {
  342. if(*ch == ' ')
  343. {
  344. result += '\\';
  345. }
  346. result += *ch;
  347. }
  348. return result;
  349. #endif
  350. }
  351. std::string cmSystemTools::EscapeQuotes(const char* str)
  352. {
  353. std::string result = "";
  354. for(const char* ch = str; *ch != '\0'; ++ch)
  355. {
  356. if(*ch == '"')
  357. {
  358. result += '\\';
  359. }
  360. result += *ch;
  361. }
  362. return result;
  363. }
  364. // return true if the file exists
  365. bool cmSystemTools::FileExists(const char* filename)
  366. {
  367. struct stat fs;
  368. if (stat(filename, &fs) != 0)
  369. {
  370. return false;
  371. }
  372. else
  373. {
  374. return true;
  375. }
  376. }
  377. // Return a capitalized string (i.e the first letter is uppercased, all other
  378. // are lowercased)
  379. std::string cmSystemTools::Capitalized(const std::string& s)
  380. {
  381. std::string n;
  382. n.resize(s.size());
  383. n[0] = toupper(s[0]);
  384. for (size_t i = 1; i < s.size(); i++)
  385. {
  386. n[i] = tolower(s[i]);
  387. }
  388. return n;
  389. }
  390. // Return a lower case string
  391. std::string cmSystemTools::LowerCase(const std::string& s)
  392. {
  393. std::string n;
  394. n.resize(s.size());
  395. for (size_t i = 0; i < s.size(); i++)
  396. {
  397. n[i] = tolower(s[i]);
  398. }
  399. return n;
  400. }
  401. // convert windows slashes to unix slashes \ with /
  402. const char *cmSystemTools::ConvertToUnixSlashes(std::string& path)
  403. {
  404. std::string::size_type pos = 0;
  405. while((pos = path.find('\\', pos)) != std::string::npos)
  406. {
  407. path[pos] = '/';
  408. pos++;
  409. }
  410. // remove any trailing slash
  411. if(path.size() && path[path.size()-1] == '/')
  412. {
  413. path = path.substr(0, path.size()-1);
  414. }
  415. return path.c_str();
  416. }
  417. // convert windows slashes to unix slashes
  418. const char *cmSystemTools::ConvertToWindowsSlashes(std::string& path)
  419. {
  420. std::string::size_type pos = 0;
  421. while((pos = path.find('/', pos)) != std::string::npos)
  422. {
  423. path[pos] = '\\';
  424. pos++;
  425. }
  426. // remove any trailing slash
  427. if(path[path.size()-1] == '\\')
  428. {
  429. path = path.substr(0, path.size()-1);
  430. }
  431. return path.c_str();
  432. }
  433. // convert Unix slashes to Windows slashes and cleanup double slashes
  434. const char *cmSystemTools::ConvertToWindowsSlashesAndCleanUp(std::string& path)
  435. {
  436. cmSystemTools::ConvertToWindowsSlashes(path);
  437. std::string::size_type pos = 0;
  438. pos = 0;
  439. while((pos = path.find("\\\\", pos)) != std::string::npos)
  440. {
  441. path.erase(pos, 1);
  442. }
  443. return path.c_str();
  444. }
  445. bool cmSystemTools::ParseFunction(std::ifstream& fin,
  446. std::string& name,
  447. std::vector<std::string>& arguments,
  448. const char* filename)
  449. {
  450. name = "";
  451. arguments = std::vector<std::string>();
  452. const int BUFFER_SIZE = 4096;
  453. char inbuffer[BUFFER_SIZE];
  454. if(!fin)
  455. {
  456. return false;
  457. }
  458. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  459. {
  460. cmRegularExpression blankLine("^[ \t\r]*$");
  461. cmRegularExpression comment("^[ \t]*#.*$");
  462. cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t\r]*$");
  463. cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
  464. cmRegularExpression lastLine("^(.*)\\)[ \t\r]*$");
  465. // check for black line or comment
  466. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  467. {
  468. return false;
  469. }
  470. // look for a oneline fun(arg arg2)
  471. else if(oneLiner.find(inbuffer))
  472. {
  473. // the arguments are the second match
  474. std::string args = oneLiner.match(2);
  475. name = oneLiner.match(1);
  476. // break up the arguments
  477. cmSystemTools::GetArguments(args, arguments);
  478. return true;
  479. }
  480. // look for a start of a multiline with no trailing ")" fun(arg arg2
  481. else if(multiLine.find(inbuffer))
  482. {
  483. name = multiLine.match(1);
  484. std::string args = multiLine.match(2);
  485. cmSystemTools::GetArguments(args, arguments);
  486. // Read lines until the closing paren is hit
  487. bool done = false;
  488. while(!done)
  489. {
  490. // read lines until the end paren is found
  491. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  492. {
  493. // Check for comment lines and ignore them.
  494. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  495. { continue; }
  496. // Is this the last line?
  497. if(lastLine.find(inbuffer))
  498. {
  499. done = true;
  500. std::string args = lastLine.match(1);
  501. cmSystemTools::GetArguments(args, arguments);
  502. }
  503. else
  504. {
  505. std::string line = inbuffer;
  506. cmSystemTools::GetArguments(line, arguments);
  507. }
  508. }
  509. else
  510. {
  511. cmSystemTools::Error("Parse error in read function missing end )\nIn File: ",
  512. filename, "\nCurrent line:", inbuffer);
  513. return false;
  514. }
  515. }
  516. return true;
  517. }
  518. else
  519. {
  520. cmSystemTools::Error("Parse error in read function\nIn file:",
  521. filename, "\nCurrent line:", inbuffer);
  522. return false;
  523. }
  524. }
  525. return false;
  526. }
  527. void cmSystemTools::GetArguments(std::string& line,
  528. std::vector<std::string>& arguments)
  529. {
  530. // Match a normal argument (not quoted, no spaces).
  531. cmRegularExpression normalArgument("[ \t]*(([^ \t\\]|[\\].)+)[ \t]*");
  532. // Match a quoted argument (surrounded by double quotes, spaces allowed).
  533. cmRegularExpression quotedArgument("[ \t]*(\"([^\"\\]|[\\].)*\")[ \t]*");
  534. bool done = false;
  535. while(!done)
  536. {
  537. std::string arg;
  538. long endpos;
  539. bool foundQuoted = quotedArgument.find(line.c_str());
  540. bool foundNormal = normalArgument.find(line.c_str());
  541. if(foundQuoted && foundNormal)
  542. {
  543. // Both matches were found. Take the earlier one.
  544. // Favor double-quoted version if there is a tie.
  545. if(normalArgument.start(1) < quotedArgument.start(1))
  546. {
  547. arg = normalArgument.match(1);
  548. endpos = normalArgument.end(1);
  549. }
  550. else
  551. {
  552. arg = quotedArgument.match(1);
  553. endpos = quotedArgument.end(1);
  554. // Strip off the double quotes on the ends.
  555. arg = arg.substr(1, arg.length()-2);
  556. }
  557. }
  558. else if (foundQuoted)
  559. {
  560. arg = quotedArgument.match(1);
  561. endpos = quotedArgument.end(1);
  562. // Strip off the double quotes on the ends.
  563. arg = arg.substr(1, arg.length()-2);
  564. }
  565. else if(foundNormal)
  566. {
  567. arg = normalArgument.match(1);
  568. endpos = normalArgument.end(1);
  569. }
  570. else
  571. {
  572. done = true;
  573. }
  574. if(!done)
  575. {
  576. arguments.push_back(cmSystemTools::RemoveEscapes(arg.c_str()));
  577. line = line.substr(endpos, line.length() - endpos);
  578. }
  579. }
  580. }
  581. std::string cmSystemTools::RemoveEscapes(const char* s)
  582. {
  583. std::string result = "";
  584. for(const char* ch = s; *ch; ++ch)
  585. {
  586. if(*ch == '\\')
  587. {
  588. ++ch;
  589. switch (*ch)
  590. {
  591. case '\\': result.insert(result.end(), '\\'); break;
  592. case '"': result.insert(result.end(), '"'); break;
  593. case ' ': result.insert(result.end(), ' '); break;
  594. case 't': result.insert(result.end(), '\t'); break;
  595. case 'n': result.insert(result.end(), '\n'); break;
  596. case 'r': result.insert(result.end(), '\r'); break;
  597. case '0': result.insert(result.end(), '\0'); break;
  598. case '\0':
  599. {
  600. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  601. return result;
  602. }
  603. default:
  604. {
  605. std::string chStr(1, *ch);
  606. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  607. "\nin argument ", s);
  608. }
  609. }
  610. }
  611. else
  612. {
  613. result.insert(result.end(), *ch);
  614. }
  615. }
  616. return result;
  617. }
  618. void cmSystemTools::Error(const char* m1, const char* m2,
  619. const char* m3, const char* m4)
  620. {
  621. std::string message = "CMake Error: ";
  622. if(m1)
  623. {
  624. message += m1;
  625. }
  626. if(m2)
  627. {
  628. message += m2;
  629. }
  630. if(m3)
  631. {
  632. message += m3;
  633. }
  634. if(m4)
  635. {
  636. message += m4;
  637. }
  638. cmSystemTools::s_ErrorOccured = true;
  639. cmSystemTools::Message(message.c_str(),"Error");
  640. }
  641. void cmSystemTools::SetErrorCallback(ErrorCallback f)
  642. {
  643. s_ErrorCallback = f;
  644. }
  645. void cmSystemTools::Message(const char* m1, const char *title)
  646. {
  647. static bool disableMessages = false;
  648. if(disableMessages)
  649. {
  650. return;
  651. }
  652. if(s_ErrorCallback)
  653. {
  654. (*s_ErrorCallback)(m1, title, disableMessages);
  655. return;
  656. }
  657. else
  658. {
  659. std::cerr << m1 << std::endl;
  660. }
  661. }
  662. void cmSystemTools::CopyFileIfDifferent(const char* source,
  663. const char* destination)
  664. {
  665. if(cmSystemTools::FilesDiffer(source, destination))
  666. {
  667. cmSystemTools::cmCopyFile(source, destination);
  668. }
  669. }
  670. bool cmSystemTools::FilesDiffer(const char* source,
  671. const char* destination)
  672. {
  673. struct stat statSource;
  674. if (stat(source, &statSource) != 0)
  675. {
  676. return true;
  677. }
  678. struct stat statDestination;
  679. if (stat(destination, &statDestination) != 0)
  680. {
  681. return true;
  682. }
  683. if(statSource.st_size != statDestination.st_size)
  684. {
  685. return true;
  686. }
  687. std::ifstream finSource(source);
  688. std::ifstream finDestination(destination);
  689. if(!finSource || !finDestination)
  690. {
  691. return true;
  692. }
  693. while(finSource && finDestination)
  694. {
  695. char s, d;
  696. finSource >> s;
  697. finDestination >> d;
  698. if(s != d)
  699. {
  700. return true;
  701. }
  702. }
  703. return false;
  704. }
  705. /**
  706. * Copy a file named by "source" to the file named by "destination". This
  707. * implementation makes correct use of the C++ standard file streams to
  708. * perfectly copy any file with lines of any length (even binary files).
  709. */
  710. void cmSystemTools::cmCopyFile(const char* source,
  711. const char* destination)
  712. {
  713. // Buffer length is only for block size. Any file would still be copied
  714. // correctly if this were as small as 2.
  715. const int buffer_length = 4096;
  716. char buffer[buffer_length];
  717. std::ifstream fin(source,
  718. #ifdef _WIN32
  719. std::ios::binary |
  720. #endif
  721. std::ios::in);
  722. if(!fin)
  723. {
  724. cmSystemTools::Error("CopyFile failed to open input file \"",
  725. source, "\"");
  726. return;
  727. }
  728. std::ofstream fout(destination,
  729. #ifdef _WIN32
  730. std::ios::binary |
  731. #endif
  732. std::ios::out | std::ios::trunc);
  733. if(!fout)
  734. {
  735. cmSystemTools::Error("CopyFile failed to open output file \"",
  736. destination, "\"");
  737. return;
  738. }
  739. while(fin.getline(buffer, buffer_length, '\n') || fin.gcount())
  740. {
  741. unsigned long count = fin.gcount();
  742. if(fin.eof())
  743. {
  744. // Final line, but with no newline.
  745. fout.write(buffer, count);
  746. }
  747. else if(fin.fail())
  748. {
  749. // Part of a line longer than our buffer, clear the fail bit of
  750. // the stream so that we can continue.
  751. fin.clear(fin.rdstate() & ~std::ios::failbit);
  752. fout.write(buffer, count);
  753. }
  754. else
  755. {
  756. // Line on which a newline was encountered. It was read from
  757. // the stream, but not stored.
  758. --count;
  759. fout.write(buffer, count);
  760. fout << '\n';
  761. }
  762. }
  763. }
  764. // return true if the file exists
  765. long int cmSystemTools::ModifiedTime(const char* filename)
  766. {
  767. struct stat fs;
  768. if (stat(filename, &fs) != 0)
  769. {
  770. return 0;
  771. }
  772. else
  773. {
  774. return (long int)fs.st_mtime;
  775. }
  776. }
  777. void cmSystemTools::RemoveFile(const char* source)
  778. {
  779. unlink(source);
  780. }
  781. bool cmSystemTools::IsOn(const char* val)
  782. {
  783. if (!val)
  784. {
  785. return false;
  786. }
  787. std::basic_string<char> v = val;
  788. for(std::basic_string<char>::iterator c = v.begin();
  789. c != v.end(); c++)
  790. {
  791. *c = toupper(*c);
  792. }
  793. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  794. }
  795. bool cmSystemTools::IsOff(const char* val)
  796. {
  797. if (!val || strlen(val) == 0)
  798. {
  799. return true;
  800. }
  801. std::basic_string<char> v = val;
  802. for(std::basic_string<char>::iterator c = v.begin();
  803. c != v.end(); c++)
  804. {
  805. *c = toupper(*c);
  806. }
  807. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  808. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  809. }
  810. bool cmSystemTools::RunCommand(const char* command,
  811. std::string& output,
  812. bool verbose)
  813. {
  814. int foo;
  815. return cmSystemTools::RunCommand(command, output, foo, verbose);
  816. }
  817. bool cmSystemTools::RunCommand(const char* command,
  818. std::string& output,
  819. int &retVal, bool verbose)
  820. {
  821. const int BUFFER_SIZE = 4096;
  822. char buffer[BUFFER_SIZE];
  823. #if defined(WIN32) && !defined(__CYGWIN__)
  824. std::string commandToFile = command;
  825. commandToFile += " > ";
  826. std::string tempFile;
  827. tempFile += cmSystemTools::TemporaryFileName();
  828. commandToFile += tempFile;
  829. retVal = system(commandToFile.c_str());
  830. std::ifstream fin(tempFile.c_str());
  831. if(!fin)
  832. {
  833. if(verbose)
  834. {
  835. std::string errormsg = "RunCommand produced no output: command: \"";
  836. errormsg += command;
  837. errormsg += "\"";
  838. errormsg += "\nOutput file: ";
  839. errormsg += tempFile;
  840. cmSystemTools::Error(errormsg.c_str());
  841. }
  842. fin.close();
  843. cmSystemTools::RemoveFile(tempFile.c_str());
  844. return false;
  845. }
  846. while(fin)
  847. {
  848. fin.getline(buffer, BUFFER_SIZE);
  849. output += buffer;
  850. }
  851. fin.close();
  852. cmSystemTools::RemoveFile(tempFile.c_str());
  853. return true;
  854. #else
  855. if(verbose)
  856. {
  857. std::cout << "running " << command << std::endl;
  858. }
  859. FILE* cpipe = popen(command, "r");
  860. if(!cpipe)
  861. {
  862. return false;
  863. }
  864. fgets(buffer, BUFFER_SIZE, cpipe);
  865. while(!feof(cpipe))
  866. {
  867. if(verbose)
  868. {
  869. std::cout << buffer << std::flush;
  870. }
  871. output += buffer;
  872. fgets(buffer, BUFFER_SIZE, cpipe);
  873. }
  874. retVal = pclose(cpipe);
  875. return true;
  876. #endif
  877. }
  878. #ifdef _MSC_VER
  879. #define tempnam _tempnam
  880. #endif
  881. std::string cmSystemTools::TemporaryFileName()
  882. {
  883. /** \warning in Unix is recomended to use mkstemp( char * )
  884. instead of tempnam in order to avoid the security
  885. risk of setting rights with 0666 */
  886. return tempnam(0, "cmake");
  887. }
  888. /**
  889. * Find the file the given name. Searches the given path and then
  890. * the system search path. Returns the full path to the file if it is
  891. * found. Otherwise, the empty string is returned.
  892. */
  893. std::string cmSystemTools::FindFile(const char* name,
  894. const std::vector<std::string>& userPaths)
  895. {
  896. // Add the system search path to our path.
  897. std::vector<std::string> path = userPaths;
  898. cmSystemTools::GetPath(path);
  899. std::string tryPath;
  900. for(std::vector<std::string>::const_iterator p = path.begin();
  901. p != path.end(); ++p)
  902. {
  903. tryPath = *p;
  904. tryPath += "/";
  905. tryPath += name;
  906. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  907. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  908. {
  909. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  910. }
  911. }
  912. // Couldn't find the file.
  913. return "";
  914. }
  915. /**
  916. * Find the executable with the given name. Searches the given path and then
  917. * the system search path. Returns the full path to the executable if it is
  918. * found. Otherwise, the empty string is returned.
  919. */
  920. std::string cmSystemTools::FindProgram(const char* name,
  921. const std::vector<std::string>& userPaths)
  922. {
  923. // See if the executable exists as written.
  924. if(cmSystemTools::FileExists(name) &&
  925. !cmSystemTools::FileIsDirectory(name))
  926. {
  927. return cmSystemTools::CollapseFullPath(name);
  928. }
  929. std::string tryPath = name;
  930. tryPath += cmSystemTools::GetExecutableExtension();
  931. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  932. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  933. {
  934. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  935. }
  936. // Add the system search path to our path.
  937. std::vector<std::string> path = userPaths;
  938. cmSystemTools::GetPath(path);
  939. for(std::vector<std::string>::const_iterator p = path.begin();
  940. p != path.end(); ++p)
  941. {
  942. tryPath = *p;
  943. tryPath += "/";
  944. tryPath += name;
  945. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  946. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  947. {
  948. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  949. }
  950. tryPath += cmSystemTools::GetExecutableExtension();
  951. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  952. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  953. {
  954. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  955. }
  956. }
  957. // Couldn't find the program.
  958. return "";
  959. }
  960. /**
  961. * Find the library with the given name. Searches the given path and then
  962. * the system search path. Returns the full path to the library if it is
  963. * found. Otherwise, the empty string is returned.
  964. */
  965. std::string cmSystemTools::FindLibrary(const char* name,
  966. const std::vector<std::string>& userPaths)
  967. {
  968. // See if the executable exists as written.
  969. if(cmSystemTools::FileExists(name))
  970. {
  971. return cmSystemTools::CollapseFullPath(name);
  972. }
  973. // Add the system search path to our path.
  974. std::vector<std::string> path = userPaths;
  975. cmSystemTools::GetPath(path);
  976. std::string tryPath;
  977. for(std::vector<std::string>::const_iterator p = path.begin();
  978. p != path.end(); ++p)
  979. {
  980. #if defined(_WIN32) && !defined(__CYGWIN__)
  981. tryPath = *p;
  982. tryPath += "/";
  983. tryPath += name;
  984. tryPath += ".lib";
  985. if(cmSystemTools::FileExists(tryPath.c_str()))
  986. {
  987. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  988. }
  989. #else
  990. tryPath = *p;
  991. tryPath += "/lib";
  992. tryPath += name;
  993. tryPath += ".so";
  994. if(cmSystemTools::FileExists(tryPath.c_str()))
  995. {
  996. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  997. }
  998. tryPath = *p;
  999. tryPath += "/lib";
  1000. tryPath += name;
  1001. tryPath += ".a";
  1002. if(cmSystemTools::FileExists(tryPath.c_str()))
  1003. {
  1004. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1005. }
  1006. tryPath = *p;
  1007. tryPath += "/lib";
  1008. tryPath += name;
  1009. tryPath += ".sl";
  1010. if(cmSystemTools::FileExists(tryPath.c_str()))
  1011. {
  1012. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1013. }
  1014. #endif
  1015. }
  1016. // Couldn't find the library.
  1017. return "";
  1018. }
  1019. bool cmSystemTools::FileIsDirectory(const char* name)
  1020. {
  1021. struct stat fs;
  1022. if(stat(name, &fs) == 0)
  1023. {
  1024. #if _WIN32
  1025. return ((fs.st_mode & _S_IFDIR) != 0);
  1026. #else
  1027. return S_ISDIR(fs.st_mode);
  1028. #endif
  1029. }
  1030. else
  1031. {
  1032. return false;
  1033. }
  1034. }
  1035. int cmSystemTools::ChangeDirectory(const char *dir)
  1036. {
  1037. return Chdir(dir);
  1038. }
  1039. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1040. {
  1041. char buf[2048];
  1042. std::string path = Getcwd(buf, 2048);
  1043. return path;
  1044. }
  1045. /**
  1046. * Given the path to a program executable, get the directory part of the path with the
  1047. * file stripped off. If there is no directory part, the empty string is returned.
  1048. */
  1049. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1050. {
  1051. std::string dir, file;
  1052. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1053. return dir;
  1054. }
  1055. /**
  1056. * Given the path to a program executable, get the directory part of the path
  1057. * with the file stripped off. If there is no directory part, the empty
  1058. * string is returned.
  1059. */
  1060. void cmSystemTools::SplitProgramPath(const char* in_name,
  1061. std::string& dir,
  1062. std::string& file)
  1063. {
  1064. dir = in_name;
  1065. file = "";
  1066. cmSystemTools::ConvertToUnixSlashes(dir);
  1067. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1068. {
  1069. std::string::size_type slashPos = dir.rfind("/");
  1070. if(slashPos != std::string::npos)
  1071. {
  1072. file = dir.substr(slashPos+1);
  1073. dir = dir.substr(0, slashPos);
  1074. }
  1075. else
  1076. {
  1077. file = dir;
  1078. dir = "";
  1079. }
  1080. }
  1081. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1082. {
  1083. std::string oldDir = in_name;
  1084. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1085. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1086. oldDir.c_str(), "\nDirectory not found: ",
  1087. dir.c_str());
  1088. dir = in_name;
  1089. return;
  1090. }
  1091. }
  1092. /**
  1093. * Given a path to a file or directory, convert it to a full path.
  1094. * This collapses away relative paths. The full path is returned.
  1095. */
  1096. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1097. {
  1098. std::string dir, file;
  1099. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1100. #ifdef _WIN32
  1101. // Ultra-hack warning:
  1102. // This changes to the target directory, saves the working directory,
  1103. // and then changes back to the original working directory.
  1104. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1105. if(dir != "") { Chdir(dir.c_str()); }
  1106. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1107. Chdir(cwd.c_str());
  1108. cmSystemTools::ConvertToUnixSlashes(newDir);
  1109. std::string newPath = newDir+"/"+file;
  1110. return newPath;
  1111. #else
  1112. # ifdef MAXPATHLEN
  1113. char resolved_name[MAXPATHLEN];
  1114. # else
  1115. # ifdef PATH_MAX
  1116. char resolved_name[PATH_MAX];
  1117. # else
  1118. char resolved_name[5024];
  1119. # endif
  1120. # endif
  1121. if(dir != "")
  1122. {
  1123. realpath(dir.c_str(), resolved_name);
  1124. dir = resolved_name;
  1125. }
  1126. else
  1127. {
  1128. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1129. }
  1130. return dir + "/" + file;
  1131. #endif
  1132. }
  1133. /**
  1134. * Return path of a full filename (no trailing slashes).
  1135. * Warning: returned path is converted to Unix slashes format.
  1136. */
  1137. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1138. {
  1139. std::string fn = filename;
  1140. cmSystemTools::ConvertToUnixSlashes(fn);
  1141. std::string::size_type slash_pos = fn.rfind("/");
  1142. if(slash_pos != std::string::npos)
  1143. {
  1144. return fn.substr(0, slash_pos);
  1145. }
  1146. else
  1147. {
  1148. return "";
  1149. }
  1150. }
  1151. /**
  1152. * Return file name of a full filename (i.e. file name without path).
  1153. */
  1154. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1155. {
  1156. std::string fn = filename;
  1157. cmSystemTools::ConvertToUnixSlashes(fn);
  1158. std::string::size_type slash_pos = fn.rfind("/");
  1159. if(slash_pos != std::string::npos)
  1160. {
  1161. return fn.substr(slash_pos + 1);
  1162. }
  1163. else
  1164. {
  1165. return filename;
  1166. }
  1167. }
  1168. /**
  1169. * Return file extension of a full filename (dot included).
  1170. * Warning: this is the longest extension (for example: .tar.gz)
  1171. */
  1172. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1173. {
  1174. std::string name = cmSystemTools::GetFilenameName(filename);
  1175. std::string::size_type dot_pos = name.find(".");
  1176. if(dot_pos != std::string::npos)
  1177. {
  1178. return name.substr(dot_pos);
  1179. }
  1180. else
  1181. {
  1182. return "";
  1183. }
  1184. }
  1185. /**
  1186. * Return file extension of a full filename (dot included).
  1187. */
  1188. std::string cmSystemTools::GetFilenameShortestExtension(const std::string& filename)
  1189. {
  1190. std::string name = cmSystemTools::GetFilenameName(filename);
  1191. std::string::size_type dot_pos = name.rfind(".");
  1192. if(dot_pos != std::string::npos)
  1193. {
  1194. return name.substr(dot_pos);
  1195. }
  1196. else
  1197. {
  1198. return "";
  1199. }
  1200. }
  1201. /**
  1202. * Return file name without extension of a full filename (i.e. without path).
  1203. * Warning: it considers the longest extension (for example: .tar.gz)
  1204. */
  1205. std::string cmSystemTools::GetFilenameNameWithoutExtension(const std::string& filename)
  1206. {
  1207. std::string name = cmSystemTools::GetFilenameName(filename);
  1208. std::string::size_type dot_pos = name.find(".");
  1209. if(dot_pos != std::string::npos)
  1210. {
  1211. return name.substr(0, dot_pos);
  1212. }
  1213. else
  1214. {
  1215. return name;
  1216. }
  1217. }
  1218. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1219. std::vector<std::string>& files)
  1220. {
  1221. cmDirectory d;
  1222. cmRegularExpression reg(regexp);
  1223. if (d.Load(directory))
  1224. {
  1225. int i, numf;
  1226. numf = d.GetNumberOfFiles();
  1227. for (i = 0; i < numf; i++)
  1228. {
  1229. std::string fname = d.GetFile(i);
  1230. if (reg.find(fname))
  1231. {
  1232. files.push_back(fname);
  1233. }
  1234. }
  1235. }
  1236. }
  1237. void cmSystemTools::GlobDirs(const char *fullPath,
  1238. std::vector<std::string>& files)
  1239. {
  1240. std::string path = fullPath;
  1241. int pos = path.find("/*");
  1242. if(pos == std::string::npos)
  1243. {
  1244. files.push_back(fullPath);
  1245. return;
  1246. }
  1247. std::string startPath = path.substr(0, pos);
  1248. std::string finishPath = path.substr(pos+2);
  1249. cmDirectory d;
  1250. if (d.Load(startPath.c_str()))
  1251. {
  1252. for (int i = 0; i < d.GetNumberOfFiles(); ++i)
  1253. {
  1254. if((std::string(d.GetFile(i)) != ".")
  1255. && (std::string(d.GetFile(i)) != ".."))
  1256. {
  1257. std::string fname = startPath;
  1258. fname +="/";
  1259. fname += d.GetFile(i);
  1260. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1261. {
  1262. fname += finishPath;
  1263. cmSystemTools::GlobDirs(fname.c_str(), files);
  1264. }
  1265. }
  1266. }
  1267. }
  1268. }