cmSystemTools.cxx 31 KB

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