cmSystemTools.cxx 34 KB

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