cmSystemTools.cxx 34 KB

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