cmSystemTools.cxx 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  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. void cmSystemTools::CopyFileIfDifferent(const char* source,
  694. const char* destination)
  695. {
  696. if(cmSystemTools::FilesDiffer(source, destination))
  697. {
  698. cmSystemTools::cmCopyFile(source, destination);
  699. }
  700. }
  701. bool cmSystemTools::FilesDiffer(const char* source,
  702. const char* destination)
  703. {
  704. struct stat statSource;
  705. if (stat(source, &statSource) != 0)
  706. {
  707. return true;
  708. }
  709. struct stat statDestination;
  710. if (stat(destination, &statDestination) != 0)
  711. {
  712. return true;
  713. }
  714. if(statSource.st_size != statDestination.st_size)
  715. {
  716. return true;
  717. }
  718. std::ifstream finSource(source);
  719. std::ifstream finDestination(destination);
  720. if(!finSource || !finDestination)
  721. {
  722. return true;
  723. }
  724. while(finSource && finDestination)
  725. {
  726. char s, d;
  727. finSource >> s;
  728. finDestination >> d;
  729. if(s != d)
  730. {
  731. return true;
  732. }
  733. }
  734. return false;
  735. }
  736. /**
  737. * Copy a file named by "source" to the file named by "destination". This
  738. * implementation makes correct use of the C++ standard file streams to
  739. * perfectly copy any file with lines of any length (even binary files).
  740. */
  741. void cmSystemTools::cmCopyFile(const char* source,
  742. const char* destination)
  743. {
  744. // Buffer length is only for block size. Any file would still be copied
  745. // correctly if this were as small as 2.
  746. const int buffer_length = 4096;
  747. char buffer[buffer_length];
  748. std::ifstream fin(source,
  749. #ifdef _WIN32
  750. std::ios::binary |
  751. #endif
  752. std::ios::in);
  753. if(!fin)
  754. {
  755. cmSystemTools::Error("CopyFile failed to open input file \"",
  756. source, "\"");
  757. return;
  758. }
  759. std::ofstream fout(destination,
  760. #ifdef _WIN32
  761. std::ios::binary |
  762. #endif
  763. std::ios::out | std::ios::trunc);
  764. if(!fout)
  765. {
  766. cmSystemTools::Error("CopyFile failed to open output file \"",
  767. destination, "\"");
  768. return;
  769. }
  770. while(fin.getline(buffer, buffer_length, '\n') || fin.gcount())
  771. {
  772. unsigned long count = fin.gcount();
  773. if(fin.eof())
  774. {
  775. // Final line, but with no newline.
  776. fout.write(buffer, count);
  777. }
  778. else if(fin.fail())
  779. {
  780. // Part of a line longer than our buffer, clear the fail bit of
  781. // the stream so that we can continue.
  782. fin.clear(fin.rdstate() & ~std::ios::failbit);
  783. fout.write(buffer, count);
  784. }
  785. else
  786. {
  787. // Line on which a newline was encountered. It was read from
  788. // the stream, but not stored.
  789. --count;
  790. fout.write(buffer, count);
  791. fout << '\n';
  792. }
  793. }
  794. }
  795. // return true if the file exists
  796. long int cmSystemTools::ModifiedTime(const char* filename)
  797. {
  798. struct stat fs;
  799. if (stat(filename, &fs) != 0)
  800. {
  801. return 0;
  802. }
  803. else
  804. {
  805. return (long int)fs.st_mtime;
  806. }
  807. }
  808. bool cmSystemTools::RemoveFile(const char* source)
  809. {
  810. return unlink(source) != 0 ? false : true;
  811. }
  812. bool cmSystemTools::IsOn(const char* val)
  813. {
  814. if (!val)
  815. {
  816. return false;
  817. }
  818. std::basic_string<char> v = val;
  819. for(std::basic_string<char>::iterator c = v.begin();
  820. c != v.end(); c++)
  821. {
  822. *c = toupper(*c);
  823. }
  824. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  825. }
  826. bool cmSystemTools::IsOff(const char* val)
  827. {
  828. if (!val || strlen(val) == 0)
  829. {
  830. return true;
  831. }
  832. std::basic_string<char> v = val;
  833. for(std::basic_string<char>::iterator c = v.begin();
  834. c != v.end(); c++)
  835. {
  836. *c = toupper(*c);
  837. }
  838. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  839. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  840. }
  841. bool cmSystemTools::RunCommand(const char* command,
  842. std::string& output,
  843. bool verbose)
  844. {
  845. int foo;
  846. return cmSystemTools::RunCommand(command, output, foo, verbose);
  847. }
  848. bool cmSystemTools::RunCommand(const char* command,
  849. std::string& output,
  850. int &retVal, bool verbose)
  851. {
  852. const int BUFFER_SIZE = 4096;
  853. char buffer[BUFFER_SIZE];
  854. if(s_DisableRunCommandOutput)
  855. {
  856. verbose = false;
  857. }
  858. #if defined(WIN32) && !defined(__CYGWIN__)
  859. std::string commandToFile = command;
  860. commandToFile += " > ";
  861. std::string tempFile;
  862. tempFile += _tempnam(0, "cmake");
  863. commandToFile += tempFile;
  864. retVal = system(commandToFile.c_str());
  865. std::ifstream fin(tempFile.c_str());
  866. if(!fin)
  867. {
  868. if(verbose)
  869. {
  870. std::string errormsg = "RunCommand produced no output: command: \"";
  871. errormsg += command;
  872. errormsg += "\"";
  873. errormsg += "\nOutput file: ";
  874. errormsg += tempFile;
  875. cmSystemTools::Error(errormsg.c_str());
  876. }
  877. fin.close();
  878. cmSystemTools::RemoveFile(tempFile.c_str());
  879. return false;
  880. }
  881. while(fin)
  882. {
  883. fin.getline(buffer, BUFFER_SIZE);
  884. output += buffer;
  885. }
  886. fin.close();
  887. cmSystemTools::RemoveFile(tempFile.c_str());
  888. return true;
  889. #else
  890. if(verbose)
  891. {
  892. std::cout << "running " << command << std::endl;
  893. }
  894. FILE* cpipe = popen(command, "r");
  895. if(!cpipe)
  896. {
  897. return false;
  898. }
  899. fgets(buffer, BUFFER_SIZE, cpipe);
  900. while(!feof(cpipe))
  901. {
  902. if(verbose)
  903. {
  904. std::cout << buffer << std::flush;
  905. }
  906. output += buffer;
  907. fgets(buffer, BUFFER_SIZE, cpipe);
  908. }
  909. retVal = pclose(cpipe);
  910. return true;
  911. #endif
  912. }
  913. /**
  914. * Find the file the given name. Searches the given path and then
  915. * the system search path. Returns the full path to the file if it is
  916. * found. Otherwise, the empty string is returned.
  917. */
  918. std::string cmSystemTools::FindFile(const char* name,
  919. const std::vector<std::string>& userPaths)
  920. {
  921. // Add the system search path to our path.
  922. std::vector<std::string> path = userPaths;
  923. cmSystemTools::GetPath(path);
  924. std::string tryPath;
  925. for(std::vector<std::string>::const_iterator p = path.begin();
  926. p != path.end(); ++p)
  927. {
  928. tryPath = *p;
  929. tryPath += "/";
  930. tryPath += name;
  931. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  932. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  933. {
  934. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  935. }
  936. }
  937. // Couldn't find the file.
  938. return "";
  939. }
  940. /**
  941. * Find the executable with the given name. Searches the given path and then
  942. * the system search path. Returns the full path to the executable if it is
  943. * found. Otherwise, the empty string is returned.
  944. */
  945. std::string cmSystemTools::FindProgram(const char* name,
  946. const std::vector<std::string>& userPaths)
  947. {
  948. // See if the executable exists as written.
  949. if(cmSystemTools::FileExists(name) &&
  950. !cmSystemTools::FileIsDirectory(name))
  951. {
  952. return cmSystemTools::CollapseFullPath(name);
  953. }
  954. std::string tryPath = name;
  955. tryPath += cmSystemTools::GetExecutableExtension();
  956. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  957. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  958. {
  959. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  960. }
  961. // Add the system search path to our path.
  962. std::vector<std::string> path = userPaths;
  963. cmSystemTools::GetPath(path);
  964. for(std::vector<std::string>::const_iterator p = path.begin();
  965. p != path.end(); ++p)
  966. {
  967. tryPath = *p;
  968. tryPath += "/";
  969. tryPath += name;
  970. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  971. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  972. {
  973. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  974. }
  975. tryPath += cmSystemTools::GetExecutableExtension();
  976. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  977. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  978. {
  979. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  980. }
  981. }
  982. // Couldn't find the program.
  983. return "";
  984. }
  985. /**
  986. * Find the library with the given name. Searches the given path and then
  987. * the system search path. Returns the full path to the library if it is
  988. * found. Otherwise, the empty string is returned.
  989. */
  990. std::string cmSystemTools::FindLibrary(const char* name,
  991. const std::vector<std::string>& userPaths)
  992. {
  993. // See if the executable exists as written.
  994. if(cmSystemTools::FileExists(name))
  995. {
  996. return cmSystemTools::CollapseFullPath(name);
  997. }
  998. // Add the system search path to our path.
  999. std::vector<std::string> path = userPaths;
  1000. cmSystemTools::GetPath(path);
  1001. std::string tryPath;
  1002. for(std::vector<std::string>::const_iterator p = path.begin();
  1003. p != path.end(); ++p)
  1004. {
  1005. #if defined(_WIN32) && !defined(__CYGWIN__)
  1006. tryPath = *p;
  1007. tryPath += "/";
  1008. tryPath += name;
  1009. tryPath += ".lib";
  1010. if(cmSystemTools::FileExists(tryPath.c_str()))
  1011. {
  1012. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1013. }
  1014. #else
  1015. tryPath = *p;
  1016. tryPath += "/lib";
  1017. tryPath += name;
  1018. tryPath += ".so";
  1019. if(cmSystemTools::FileExists(tryPath.c_str()))
  1020. {
  1021. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1022. }
  1023. tryPath = *p;
  1024. tryPath += "/lib";
  1025. tryPath += name;
  1026. tryPath += ".a";
  1027. if(cmSystemTools::FileExists(tryPath.c_str()))
  1028. {
  1029. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1030. }
  1031. tryPath = *p;
  1032. tryPath += "/lib";
  1033. tryPath += name;
  1034. tryPath += ".sl";
  1035. if(cmSystemTools::FileExists(tryPath.c_str()))
  1036. {
  1037. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1038. }
  1039. #endif
  1040. }
  1041. // Couldn't find the library.
  1042. return "";
  1043. }
  1044. bool cmSystemTools::FileIsDirectory(const char* name)
  1045. {
  1046. struct stat fs;
  1047. if(stat(name, &fs) == 0)
  1048. {
  1049. #if _WIN32
  1050. return ((fs.st_mode & _S_IFDIR) != 0);
  1051. #else
  1052. return S_ISDIR(fs.st_mode);
  1053. #endif
  1054. }
  1055. else
  1056. {
  1057. return false;
  1058. }
  1059. }
  1060. int cmSystemTools::ChangeDirectory(const char *dir)
  1061. {
  1062. return Chdir(dir);
  1063. }
  1064. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1065. {
  1066. char buf[2048];
  1067. std::string path = Getcwd(buf, 2048);
  1068. return path;
  1069. }
  1070. /**
  1071. * Given the path to a program executable, get the directory part of the path with the
  1072. * file stripped off. If there is no directory part, the empty string is returned.
  1073. */
  1074. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1075. {
  1076. std::string dir, file;
  1077. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1078. return dir;
  1079. }
  1080. /**
  1081. * Given the path to a program executable, get the directory part of the path
  1082. * with the file stripped off. If there is no directory part, the empty
  1083. * string is returned.
  1084. */
  1085. void cmSystemTools::SplitProgramPath(const char* in_name,
  1086. std::string& dir,
  1087. std::string& file)
  1088. {
  1089. dir = in_name;
  1090. file = "";
  1091. cmSystemTools::ConvertToUnixSlashes(dir);
  1092. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1093. {
  1094. std::string::size_type slashPos = dir.rfind("/");
  1095. if(slashPos != std::string::npos)
  1096. {
  1097. file = dir.substr(slashPos+1);
  1098. dir = dir.substr(0, slashPos);
  1099. }
  1100. else
  1101. {
  1102. file = dir;
  1103. dir = "";
  1104. }
  1105. }
  1106. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1107. {
  1108. std::string oldDir = in_name;
  1109. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1110. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1111. oldDir.c_str(), "\nDirectory not found: ",
  1112. dir.c_str());
  1113. dir = in_name;
  1114. return;
  1115. }
  1116. }
  1117. /**
  1118. * Given a path to a file or directory, convert it to a full path.
  1119. * This collapses away relative paths. The full path is returned.
  1120. */
  1121. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1122. {
  1123. std::string dir, file;
  1124. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1125. #ifdef _WIN32
  1126. // Ultra-hack warning:
  1127. // This changes to the target directory, saves the working directory,
  1128. // and then changes back to the original working directory.
  1129. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1130. if(dir != "") { Chdir(dir.c_str()); }
  1131. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1132. Chdir(cwd.c_str());
  1133. cmSystemTools::ConvertToUnixSlashes(newDir);
  1134. std::string newPath = newDir+"/"+file;
  1135. return newPath;
  1136. #else
  1137. # ifdef MAXPATHLEN
  1138. char resolved_name[MAXPATHLEN];
  1139. # else
  1140. # ifdef PATH_MAX
  1141. char resolved_name[PATH_MAX];
  1142. # else
  1143. char resolved_name[5024];
  1144. # endif
  1145. # endif
  1146. if(dir != "")
  1147. {
  1148. realpath(dir.c_str(), resolved_name);
  1149. dir = resolved_name;
  1150. }
  1151. else
  1152. {
  1153. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1154. }
  1155. return dir + "/" + file;
  1156. #endif
  1157. }
  1158. /**
  1159. * Return path of a full filename (no trailing slashes).
  1160. * Warning: returned path is converted to Unix slashes format.
  1161. */
  1162. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1163. {
  1164. std::string fn = filename;
  1165. cmSystemTools::ConvertToUnixSlashes(fn);
  1166. std::string::size_type slash_pos = fn.rfind("/");
  1167. if(slash_pos != std::string::npos)
  1168. {
  1169. return fn.substr(0, slash_pos);
  1170. }
  1171. else
  1172. {
  1173. return "";
  1174. }
  1175. }
  1176. /**
  1177. * Return file name of a full filename (i.e. file name without path).
  1178. */
  1179. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1180. {
  1181. std::string fn = filename;
  1182. cmSystemTools::ConvertToUnixSlashes(fn);
  1183. std::string::size_type slash_pos = fn.rfind("/");
  1184. if(slash_pos != std::string::npos)
  1185. {
  1186. return fn.substr(slash_pos + 1);
  1187. }
  1188. else
  1189. {
  1190. return filename;
  1191. }
  1192. }
  1193. /**
  1194. * Return file extension of a full filename (dot included).
  1195. * Warning: this is the longest extension (for example: .tar.gz)
  1196. */
  1197. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1198. {
  1199. std::string name = cmSystemTools::GetFilenameName(filename);
  1200. std::string::size_type dot_pos = name.find(".");
  1201. if(dot_pos != std::string::npos)
  1202. {
  1203. return name.substr(dot_pos);
  1204. }
  1205. else
  1206. {
  1207. return "";
  1208. }
  1209. }
  1210. /**
  1211. * Return file extension of a full filename (dot included).
  1212. */
  1213. std::string cmSystemTools::GetFilenameShortestExtension(const std::string& filename)
  1214. {
  1215. std::string name = cmSystemTools::GetFilenameName(filename);
  1216. std::string::size_type dot_pos = name.rfind(".");
  1217. if(dot_pos != std::string::npos)
  1218. {
  1219. return name.substr(dot_pos);
  1220. }
  1221. else
  1222. {
  1223. return "";
  1224. }
  1225. }
  1226. /**
  1227. * Return file name without extension of a full filename (i.e. without path).
  1228. * Warning: it considers the longest extension (for example: .tar.gz)
  1229. */
  1230. std::string cmSystemTools::GetFilenameNameWithoutExtension(const std::string& filename)
  1231. {
  1232. std::string name = cmSystemTools::GetFilenameName(filename);
  1233. std::string::size_type dot_pos = name.find(".");
  1234. if(dot_pos != std::string::npos)
  1235. {
  1236. return name.substr(0, dot_pos);
  1237. }
  1238. else
  1239. {
  1240. return name;
  1241. }
  1242. }
  1243. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1244. std::vector<std::string>& files)
  1245. {
  1246. cmDirectory d;
  1247. cmRegularExpression reg(regexp);
  1248. if (d.Load(directory))
  1249. {
  1250. int i, numf;
  1251. numf = d.GetNumberOfFiles();
  1252. for (i = 0; i < numf; i++)
  1253. {
  1254. std::string fname = d.GetFile(i);
  1255. if (reg.find(fname))
  1256. {
  1257. files.push_back(fname);
  1258. }
  1259. }
  1260. }
  1261. }
  1262. void cmSystemTools::GlobDirs(const char *fullPath,
  1263. std::vector<std::string>& files)
  1264. {
  1265. std::string path = fullPath;
  1266. std::string::size_type pos = path.find("/*");
  1267. if(pos == std::string::npos)
  1268. {
  1269. files.push_back(fullPath);
  1270. return;
  1271. }
  1272. std::string startPath = path.substr(0, pos);
  1273. std::string finishPath = path.substr(pos+2);
  1274. cmDirectory d;
  1275. if (d.Load(startPath.c_str()))
  1276. {
  1277. for (int i = 0; i < d.GetNumberOfFiles(); ++i)
  1278. {
  1279. if((std::string(d.GetFile(i)) != ".")
  1280. && (std::string(d.GetFile(i)) != ".."))
  1281. {
  1282. std::string fname = startPath;
  1283. fname +="/";
  1284. fname += d.GetFile(i);
  1285. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1286. {
  1287. fname += finishPath;
  1288. cmSystemTools::GlobDirs(fname.c_str(), files);
  1289. }
  1290. }
  1291. }
  1292. }
  1293. }