cmSystemTools.cxx 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450
  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::EscapeQuotes(const char* str)
  282. {
  283. std::string result = "";
  284. for(const char* ch = str; *ch != '\0'; ++ch)
  285. {
  286. if(*ch == '"')
  287. {
  288. result += '\\';
  289. }
  290. result += *ch;
  291. }
  292. return result;
  293. }
  294. bool cmSystemTools::SameFile(const char* file1, const char* file2)
  295. {
  296. struct stat fileStat1, fileStat2;
  297. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  298. {
  299. // see if the files are the same file
  300. // check the device inode and size
  301. if(fileStat2.st_dev == fileStat1.st_dev &&
  302. fileStat2.st_ino == fileStat1.st_ino &&
  303. fileStat2.st_size == fileStat1.st_size
  304. )
  305. {
  306. return true;
  307. }
  308. }
  309. return false;
  310. }
  311. // return true if the file exists
  312. bool cmSystemTools::FileExists(const char* filename)
  313. {
  314. struct stat fs;
  315. if (stat(filename, &fs) != 0)
  316. {
  317. return false;
  318. }
  319. else
  320. {
  321. return true;
  322. }
  323. }
  324. // Return a capitalized string (i.e the first letter is uppercased, all other
  325. // are lowercased)
  326. std::string cmSystemTools::Capitalized(const std::string& s)
  327. {
  328. std::string n;
  329. n.resize(s.size());
  330. n[0] = toupper(s[0]);
  331. for (size_t i = 1; i < s.size(); i++)
  332. {
  333. n[i] = tolower(s[i]);
  334. }
  335. return n;
  336. }
  337. // Return a lower case string
  338. std::string cmSystemTools::LowerCase(const std::string& s)
  339. {
  340. std::string n;
  341. n.resize(s.size());
  342. for (size_t i = 0; i < s.size(); i++)
  343. {
  344. n[i] = tolower(s[i]);
  345. }
  346. return n;
  347. }
  348. // Return a lower case string
  349. std::string cmSystemTools::UpperCase(const std::string& s)
  350. {
  351. std::string n;
  352. n.resize(s.size());
  353. for (size_t i = 0; i < s.size(); i++)
  354. {
  355. n[i] = toupper(s[i]);
  356. }
  357. return n;
  358. }
  359. // convert windows slashes to unix slashes \ with /
  360. void cmSystemTools::ConvertToUnixSlashes(std::string& path)
  361. {
  362. std::string::size_type pos = 0;
  363. while((pos = path.find('\\', pos)) != std::string::npos)
  364. {
  365. path[pos] = '/';
  366. pos++;
  367. }
  368. // remove any trailing slash
  369. if(path.size() && path[path.size()-1] == '/')
  370. {
  371. path = path.substr(0, path.size()-1);
  372. }
  373. // if there is a tilda ~ then replace it with HOME
  374. if(path.find("~") == 0)
  375. {
  376. if (getenv("HOME"))
  377. {
  378. path = std::string(getenv("HOME")) + path.substr(1);
  379. }
  380. }
  381. // if there is a /tmp_mnt in a path get rid of it!
  382. // stupid sgi's
  383. if(path.find("/tmp_mnt") == 0)
  384. {
  385. path = path.substr(8);
  386. }
  387. }
  388. // change // to /, and escape any spaces in the path
  389. std::string cmSystemTools::ConvertToUnixOutputPath(const char* path)
  390. {
  391. std::string ret = path;
  392. // remove //
  393. std::string::size_type pos = 0;
  394. while((pos = ret.find("//", pos)) != std::string::npos)
  395. {
  396. ret.erase(pos, 1);
  397. }
  398. // now escape spaces if there is a space in the path
  399. if(ret.find(" ") != std::string::npos)
  400. {
  401. std::string result = "";
  402. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  403. {
  404. if(*ch == ' ')
  405. {
  406. result += '\\';
  407. }
  408. result += *ch;
  409. }
  410. ret = result;
  411. }
  412. return ret;
  413. }
  414. std::string cmSystemTools::EscapeSpaces(const char* str)
  415. {
  416. #if defined(_WIN32) && !defined(__CYGWIN__)
  417. std::string result;
  418. // if there are spaces
  419. std::string temp = str;
  420. if (temp.find(" ") != std::string::npos &&
  421. temp.find("\"")==std::string::npos)
  422. {
  423. result = "\"";
  424. result += str;
  425. result += "\"";
  426. return result;
  427. }
  428. return str;
  429. #else
  430. std::string result = "";
  431. for(const char* ch = str; *ch != '\0'; ++ch)
  432. {
  433. if(*ch == ' ')
  434. {
  435. result += '\\';
  436. }
  437. result += *ch;
  438. }
  439. return result;
  440. #endif
  441. }
  442. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  443. {
  444. #if defined(_WIN32) && !defined(__CYGWIN__)
  445. return cmSystemTools::ConvertToWindowsOutputPath(path);
  446. #else
  447. return cmSystemTools::ConvertToUnixOutputPath(path);
  448. #endif
  449. }
  450. // remove double slashes not at the start
  451. std::string cmSystemTools::ConvertToWindowsOutputPath(const char* path)
  452. {
  453. std::string ret = path;
  454. std::string::size_type pos = 0;
  455. // first convert all of the slashes
  456. while((pos = ret.find('/', pos)) != std::string::npos)
  457. {
  458. ret[pos] = '\\';
  459. pos++;
  460. }
  461. // check for really small paths
  462. if(ret.size() < 2)
  463. {
  464. return ret;
  465. }
  466. // now clean up a bit and remove double slashes
  467. // Only if it is not the first position in the path which is a network
  468. // path on windows
  469. pos = 1; // start at position 1
  470. while((pos = ret.find("\\\\", pos)) != std::string::npos)
  471. {
  472. ret.erase(pos, 1);
  473. }
  474. // now double quote the path if it has spaces in it
  475. // and is not already double quoted
  476. if(ret.find(" ") != std::string::npos
  477. && ret[0] != '\"')
  478. {
  479. std::string result;
  480. result = "\"" + ret + "\"";
  481. ret = result;
  482. }
  483. return ret;
  484. }
  485. bool cmSystemTools::ParseFunction(std::ifstream& fin,
  486. std::string& name,
  487. std::vector<std::string>& arguments,
  488. const char* filename,
  489. bool& parseError)
  490. {
  491. parseError = false;
  492. name = "";
  493. arguments = std::vector<std::string>();
  494. const int BUFFER_SIZE = 4096;
  495. char inbuffer[BUFFER_SIZE];
  496. if(!fin)
  497. {
  498. return false;
  499. }
  500. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  501. {
  502. cmRegularExpression blankLine("^[ \t\r]*$");
  503. cmRegularExpression comment("^[ \t]*#.*$");
  504. cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t\r]*$");
  505. cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
  506. cmRegularExpression lastLine("^(.*)\\)[ \t\r]*$");
  507. // check for black line or comment
  508. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  509. {
  510. return false;
  511. }
  512. // look for a oneline fun(arg arg2)
  513. else if(oneLiner.find(inbuffer))
  514. {
  515. // the arguments are the second match
  516. std::string args = oneLiner.match(2);
  517. name = oneLiner.match(1);
  518. // break up the arguments
  519. cmSystemTools::GetArguments(args, arguments);
  520. return true;
  521. }
  522. // look for a start of a multiline with no trailing ")" fun(arg arg2
  523. else if(multiLine.find(inbuffer))
  524. {
  525. name = multiLine.match(1);
  526. std::string args = multiLine.match(2);
  527. cmSystemTools::GetArguments(args, arguments);
  528. // Read lines until the closing paren is hit
  529. bool done = false;
  530. while(!done)
  531. {
  532. // read lines until the end paren is found
  533. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  534. {
  535. // Check for comment lines and ignore them.
  536. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  537. { continue; }
  538. // Is this the last line?
  539. if(lastLine.find(inbuffer))
  540. {
  541. done = true;
  542. std::string args = lastLine.match(1);
  543. cmSystemTools::GetArguments(args, arguments);
  544. }
  545. else
  546. {
  547. std::string line = inbuffer;
  548. cmSystemTools::GetArguments(line, arguments);
  549. }
  550. }
  551. else
  552. {
  553. parseError = true;
  554. cmSystemTools::Error("Parse error in read function missing end )\nIn File: ",
  555. filename, "\nCurrent line:", inbuffer);
  556. return false;
  557. }
  558. }
  559. return true;
  560. }
  561. else
  562. {
  563. parseError = true;
  564. cmSystemTools::Error("Parse error in read function\nIn file:",
  565. filename, "\nCurrent line:", inbuffer);
  566. return false;
  567. }
  568. }
  569. return false;
  570. }
  571. void cmSystemTools::GetArguments(std::string& line,
  572. std::vector<std::string>& arguments)
  573. {
  574. // Match a normal argument (not quoted, no spaces).
  575. cmRegularExpression normalArgument("[ \t]*(([^ \t\r\\]|[\\].)+)[ \t\r]*");
  576. // Match a quoted argument (surrounded by double quotes, spaces allowed).
  577. cmRegularExpression quotedArgument("[ \t]*(\"([^\"\\]|[\\].)*\")[ \t\r]*");
  578. bool done = false;
  579. while(!done)
  580. {
  581. std::string arg;
  582. long endpos;
  583. bool foundQuoted = quotedArgument.find(line.c_str());
  584. bool foundNormal = normalArgument.find(line.c_str());
  585. if(foundQuoted && foundNormal)
  586. {
  587. // Both matches were found. Take the earlier one.
  588. // Favor double-quoted version if there is a tie.
  589. if(normalArgument.start(1) < quotedArgument.start(1))
  590. {
  591. arg = normalArgument.match(1);
  592. endpos = normalArgument.end(1);
  593. }
  594. else
  595. {
  596. arg = quotedArgument.match(1);
  597. endpos = quotedArgument.end(1);
  598. // Strip off the double quotes on the ends.
  599. arg = arg.substr(1, arg.length()-2);
  600. }
  601. }
  602. else if (foundQuoted)
  603. {
  604. arg = quotedArgument.match(1);
  605. endpos = quotedArgument.end(1);
  606. // Strip off the double quotes on the ends.
  607. arg = arg.substr(1, arg.length()-2);
  608. }
  609. else if(foundNormal)
  610. {
  611. arg = normalArgument.match(1);
  612. endpos = normalArgument.end(1);
  613. }
  614. else
  615. {
  616. done = true;
  617. }
  618. if(!done)
  619. {
  620. arguments.push_back(cmSystemTools::RemoveEscapes(arg.c_str()));
  621. line = line.substr(endpos, line.length() - endpos);
  622. }
  623. }
  624. }
  625. std::string cmSystemTools::RemoveEscapes(const char* s)
  626. {
  627. std::string result = "";
  628. for(const char* ch = s; *ch; ++ch)
  629. {
  630. if(*ch == '\\')
  631. {
  632. ++ch;
  633. switch (*ch)
  634. {
  635. case '\\': result.insert(result.end(), '\\'); break;
  636. case '"': result.insert(result.end(), '"'); break;
  637. case ' ': result.insert(result.end(), ' '); break;
  638. case 't': result.insert(result.end(), '\t'); break;
  639. case 'n': result.insert(result.end(), '\n'); break;
  640. case 'r': result.insert(result.end(), '\r'); break;
  641. case '0': result.insert(result.end(), '\0'); break;
  642. case '\0':
  643. {
  644. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  645. return result;
  646. }
  647. default:
  648. {
  649. std::string chStr(1, *ch);
  650. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  651. "\nin argument ", s);
  652. }
  653. }
  654. }
  655. else
  656. {
  657. result.insert(result.end(), *ch);
  658. }
  659. }
  660. return result;
  661. }
  662. void cmSystemTools::Error(const char* m1, const char* m2,
  663. const char* m3, const char* m4)
  664. {
  665. std::string message = "CMake Error: ";
  666. if(m1)
  667. {
  668. message += m1;
  669. }
  670. if(m2)
  671. {
  672. message += m2;
  673. }
  674. if(m3)
  675. {
  676. message += m3;
  677. }
  678. if(m4)
  679. {
  680. message += m4;
  681. }
  682. cmSystemTools::s_ErrorOccured = true;
  683. cmSystemTools::Message(message.c_str(),"Error");
  684. }
  685. void cmSystemTools::SetErrorCallback(ErrorCallback f)
  686. {
  687. s_ErrorCallback = f;
  688. }
  689. void cmSystemTools::Message(const char* m1, const char *title)
  690. {
  691. if(s_DisableMessages)
  692. {
  693. return;
  694. }
  695. if(s_ErrorCallback)
  696. {
  697. (*s_ErrorCallback)(m1, title, s_DisableMessages);
  698. return;
  699. }
  700. else
  701. {
  702. std::cerr << m1 << std::endl;
  703. }
  704. }
  705. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  706. const char* destination)
  707. {
  708. if(cmSystemTools::FilesDiffer(source, destination))
  709. {
  710. cmSystemTools::cmCopyFile(source, destination);
  711. return true;
  712. }
  713. return false;
  714. }
  715. bool cmSystemTools::FilesDiffer(const char* source,
  716. const char* destination)
  717. {
  718. struct stat statSource;
  719. if (stat(source, &statSource) != 0)
  720. {
  721. return true;
  722. }
  723. struct stat statDestination;
  724. if (stat(destination, &statDestination) != 0)
  725. {
  726. return true;
  727. }
  728. if(statSource.st_size != statDestination.st_size)
  729. {
  730. return true;
  731. }
  732. std::ifstream finSource(source);
  733. std::ifstream finDestination(destination);
  734. if(!finSource || !finDestination)
  735. {
  736. return true;
  737. }
  738. const int buffer_length = 4096;
  739. char bufferSource[buffer_length];
  740. char bufferDest[buffer_length];
  741. while(finSource && finDestination)
  742. {
  743. if(finSource.getline(bufferSource, buffer_length, '\n')
  744. || finSource.gcount())
  745. {
  746. if(finDestination.getline(bufferDest, buffer_length, '\n')
  747. || finDestination.gcount())
  748. {
  749. // both if statements passed
  750. if(finSource.eof())
  751. {
  752. if(!finDestination.eof())
  753. {
  754. return true;
  755. }
  756. if(finSource.gcount() != finDestination.gcount())
  757. {
  758. return true;
  759. }
  760. if(strncmp(bufferSource, bufferDest, finSource.gcount()) != 0)
  761. {
  762. return true;
  763. }
  764. }
  765. else if(finSource.fail())
  766. {
  767. if(!finDestination.fail())
  768. {
  769. return true;
  770. }
  771. if(strcmp(bufferSource, bufferDest) != 0)
  772. {
  773. return true;
  774. }
  775. finSource.clear(finSource.rdstate() & ~std::ios::failbit);
  776. finDestination.clear(finDestination.rdstate() & ~std::ios::failbit);
  777. }
  778. else
  779. {
  780. if(strcmp(bufferSource, bufferDest) != 0)
  781. {
  782. return true;
  783. }
  784. }
  785. }
  786. else
  787. {
  788. return true;
  789. }
  790. }
  791. }
  792. return false;
  793. }
  794. /**
  795. * Copy a file named by "source" to the file named by "destination".
  796. */
  797. void cmSystemTools::cmCopyFile(const char* source,
  798. const char* destination)
  799. {
  800. const int bufferSize = 4096;
  801. char buffer[bufferSize];
  802. std::ifstream fin(source, std::ios::binary | std::ios::in);
  803. if(!fin)
  804. {
  805. cmSystemTools::Error("CopyFile failed to open input file \"",
  806. source, "\"");
  807. return;
  808. }
  809. std::ofstream fout(destination,
  810. std::ios::binary | std::ios::out | std::ios::trunc);
  811. if(!fout)
  812. {
  813. cmSystemTools::Error("CopyFile failed to open output file \"",
  814. destination, "\"");
  815. return;
  816. }
  817. // This copy loop is very sensitive on certain platforms with
  818. // slightly broken stream libraries (like HPUX). Normally, it is
  819. // incorrect to not check the error condition on the fin.read()
  820. // before using the data, but the fin.gcount() will be zero if an
  821. // error occurred. Therefore, the loop should be safe everywhere.
  822. while(fin)
  823. {
  824. fin.read(buffer, bufferSize);
  825. if(fin.gcount())
  826. {
  827. fout.write(buffer, fin.gcount());
  828. }
  829. }
  830. }
  831. // return true if the file exists
  832. long int cmSystemTools::ModifiedTime(const char* filename)
  833. {
  834. struct stat fs;
  835. if (stat(filename, &fs) != 0)
  836. {
  837. return 0;
  838. }
  839. else
  840. {
  841. return (long int)fs.st_mtime;
  842. }
  843. }
  844. bool cmSystemTools::RemoveFile(const char* source)
  845. {
  846. return unlink(source) != 0 ? false : true;
  847. }
  848. bool cmSystemTools::IsOn(const char* val)
  849. {
  850. if (!val)
  851. {
  852. return false;
  853. }
  854. std::basic_string<char> v = val;
  855. for(std::basic_string<char>::iterator c = v.begin();
  856. c != v.end(); c++)
  857. {
  858. *c = toupper(*c);
  859. }
  860. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  861. }
  862. bool cmSystemTools::IsOff(const char* val)
  863. {
  864. if (!val || strlen(val) == 0)
  865. {
  866. return true;
  867. }
  868. std::basic_string<char> v = val;
  869. for(std::basic_string<char>::iterator c = v.begin();
  870. c != v.end(); c++)
  871. {
  872. *c = toupper(*c);
  873. }
  874. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  875. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  876. }
  877. bool cmSystemTools::RunCommand(const char* command,
  878. std::string& output,
  879. bool verbose)
  880. {
  881. int foo;
  882. return cmSystemTools::RunCommand(command, output, foo, verbose);
  883. }
  884. bool cmSystemTools::RunCommand(const char* command,
  885. std::string& output,
  886. int &retVal, bool verbose)
  887. {
  888. const int BUFFER_SIZE = 4096;
  889. char buffer[BUFFER_SIZE];
  890. if(s_DisableRunCommandOutput)
  891. {
  892. verbose = false;
  893. }
  894. #if defined(WIN32) && !defined(__CYGWIN__)
  895. std::string commandToFile = command;
  896. commandToFile += " > ";
  897. std::string tempFile;
  898. tempFile += _tempnam(0, "cmake");
  899. commandToFile += tempFile;
  900. retVal = system(commandToFile.c_str());
  901. std::ifstream fin(tempFile.c_str());
  902. if(!fin)
  903. {
  904. if(verbose)
  905. {
  906. std::string errormsg = "RunCommand produced no output: command: \"";
  907. errormsg += command;
  908. errormsg += "\"";
  909. errormsg += "\nOutput file: ";
  910. errormsg += tempFile;
  911. cmSystemTools::Error(errormsg.c_str());
  912. }
  913. fin.close();
  914. cmSystemTools::RemoveFile(tempFile.c_str());
  915. return false;
  916. }
  917. while(fin)
  918. {
  919. fin.getline(buffer, BUFFER_SIZE);
  920. output += buffer;
  921. }
  922. fin.close();
  923. cmSystemTools::RemoveFile(tempFile.c_str());
  924. return true;
  925. #else
  926. if(verbose)
  927. {
  928. std::cout << "running " << command << std::endl;
  929. }
  930. FILE* cpipe = popen(command, "r");
  931. if(!cpipe)
  932. {
  933. return false;
  934. }
  935. fgets(buffer, BUFFER_SIZE, cpipe);
  936. while(!feof(cpipe))
  937. {
  938. if(verbose)
  939. {
  940. std::cout << buffer << std::flush;
  941. }
  942. output += buffer;
  943. fgets(buffer, BUFFER_SIZE, cpipe);
  944. }
  945. retVal = pclose(cpipe);
  946. return true;
  947. #endif
  948. }
  949. /**
  950. * Find the file the given name. Searches the given path and then
  951. * the system search path. Returns the full path to the file if it is
  952. * found. Otherwise, the empty string is returned.
  953. */
  954. std::string cmSystemTools::FindFile(const char* name,
  955. const std::vector<std::string>& userPaths)
  956. {
  957. // Add the system search path to our path.
  958. std::vector<std::string> path = userPaths;
  959. cmSystemTools::GetPath(path);
  960. std::string tryPath;
  961. for(std::vector<std::string>::const_iterator p = path.begin();
  962. p != path.end(); ++p)
  963. {
  964. tryPath = *p;
  965. tryPath += "/";
  966. tryPath += name;
  967. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  968. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  969. {
  970. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  971. }
  972. }
  973. // Couldn't find the file.
  974. return "";
  975. }
  976. /**
  977. * Find the executable with the given name. Searches the given path and then
  978. * the system search path. Returns the full path to the executable if it is
  979. * found. Otherwise, the empty string is returned.
  980. */
  981. std::string cmSystemTools::FindProgram(const char* name,
  982. const std::vector<std::string>& userPaths)
  983. {
  984. // See if the executable exists as written.
  985. if(cmSystemTools::FileExists(name) &&
  986. !cmSystemTools::FileIsDirectory(name))
  987. {
  988. return cmSystemTools::CollapseFullPath(name);
  989. }
  990. std::string tryPath = name;
  991. tryPath += cmSystemTools::GetExecutableExtension();
  992. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  993. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  994. {
  995. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  996. }
  997. // Add the system search path to our path.
  998. std::vector<std::string> path = userPaths;
  999. cmSystemTools::GetPath(path);
  1000. for(std::vector<std::string>::const_iterator p = path.begin();
  1001. p != path.end(); ++p)
  1002. {
  1003. tryPath = *p;
  1004. tryPath += "/";
  1005. tryPath += name;
  1006. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1007. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1008. {
  1009. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1010. }
  1011. tryPath += cmSystemTools::GetExecutableExtension();
  1012. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1013. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1014. {
  1015. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1016. }
  1017. }
  1018. // Couldn't find the program.
  1019. return "";
  1020. }
  1021. /**
  1022. * Find the library with the given name. Searches the given path and then
  1023. * the system search path. Returns the full path to the library if it is
  1024. * found. Otherwise, the empty string is returned.
  1025. */
  1026. std::string cmSystemTools::FindLibrary(const char* name,
  1027. const std::vector<std::string>& userPaths)
  1028. {
  1029. // See if the executable exists as written.
  1030. if(cmSystemTools::FileExists(name))
  1031. {
  1032. return cmSystemTools::CollapseFullPath(name);
  1033. }
  1034. // Add the system search path to our path.
  1035. std::vector<std::string> path = userPaths;
  1036. cmSystemTools::GetPath(path);
  1037. std::string tryPath;
  1038. for(std::vector<std::string>::const_iterator p = path.begin();
  1039. p != path.end(); ++p)
  1040. {
  1041. #if defined(_WIN32) && !defined(__CYGWIN__)
  1042. tryPath = *p;
  1043. tryPath += "/";
  1044. tryPath += name;
  1045. tryPath += ".lib";
  1046. if(cmSystemTools::FileExists(tryPath.c_str()))
  1047. {
  1048. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1049. }
  1050. #else
  1051. tryPath = *p;
  1052. tryPath += "/lib";
  1053. tryPath += name;
  1054. tryPath += ".so";
  1055. if(cmSystemTools::FileExists(tryPath.c_str()))
  1056. {
  1057. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1058. }
  1059. tryPath = *p;
  1060. tryPath += "/lib";
  1061. tryPath += name;
  1062. tryPath += ".a";
  1063. if(cmSystemTools::FileExists(tryPath.c_str()))
  1064. {
  1065. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1066. }
  1067. tryPath = *p;
  1068. tryPath += "/lib";
  1069. tryPath += name;
  1070. tryPath += ".sl";
  1071. if(cmSystemTools::FileExists(tryPath.c_str()))
  1072. {
  1073. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1074. }
  1075. #endif
  1076. }
  1077. // Couldn't find the library.
  1078. return "";
  1079. }
  1080. bool cmSystemTools::FileIsDirectory(const char* name)
  1081. {
  1082. struct stat fs;
  1083. if(stat(name, &fs) == 0)
  1084. {
  1085. #if _WIN32
  1086. return ((fs.st_mode & _S_IFDIR) != 0);
  1087. #else
  1088. return S_ISDIR(fs.st_mode);
  1089. #endif
  1090. }
  1091. else
  1092. {
  1093. return false;
  1094. }
  1095. }
  1096. int cmSystemTools::ChangeDirectory(const char *dir)
  1097. {
  1098. return Chdir(dir);
  1099. }
  1100. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1101. {
  1102. char buf[2048];
  1103. std::string path = Getcwd(buf, 2048);
  1104. return path;
  1105. }
  1106. /**
  1107. * Given the path to a program executable, get the directory part of the path with the
  1108. * file stripped off. If there is no directory part, the empty string is returned.
  1109. */
  1110. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1111. {
  1112. std::string dir, file;
  1113. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1114. return dir;
  1115. }
  1116. /**
  1117. * Given the path to a program executable, get the directory part of the path
  1118. * with the file stripped off. If there is no directory part, the empty
  1119. * string is returned.
  1120. */
  1121. void cmSystemTools::SplitProgramPath(const char* in_name,
  1122. std::string& dir,
  1123. std::string& file)
  1124. {
  1125. dir = in_name;
  1126. file = "";
  1127. cmSystemTools::ConvertToUnixSlashes(dir);
  1128. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1129. {
  1130. std::string::size_type slashPos = dir.rfind("/");
  1131. if(slashPos != std::string::npos)
  1132. {
  1133. file = dir.substr(slashPos+1);
  1134. dir = dir.substr(0, slashPos);
  1135. }
  1136. else
  1137. {
  1138. file = dir;
  1139. dir = "";
  1140. }
  1141. }
  1142. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1143. {
  1144. std::string oldDir = in_name;
  1145. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1146. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1147. oldDir.c_str(), "\nDirectory not found: ",
  1148. dir.c_str());
  1149. dir = in_name;
  1150. return;
  1151. }
  1152. }
  1153. /**
  1154. * Given a path to a file or directory, convert it to a full path.
  1155. * This collapses away relative paths. The full path is returned.
  1156. */
  1157. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1158. {
  1159. std::string dir, file;
  1160. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1161. #ifdef _WIN32
  1162. // Ultra-hack warning:
  1163. // This changes to the target directory, saves the working directory,
  1164. // and then changes back to the original working directory.
  1165. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1166. if(dir != "") { Chdir(dir.c_str()); }
  1167. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1168. Chdir(cwd.c_str());
  1169. cmSystemTools::ConvertToUnixSlashes(newDir);
  1170. std::string newPath = newDir+"/"+file;
  1171. return newPath;
  1172. #else
  1173. # ifdef MAXPATHLEN
  1174. char resolved_name[MAXPATHLEN];
  1175. # else
  1176. # ifdef PATH_MAX
  1177. char resolved_name[PATH_MAX];
  1178. # else
  1179. char resolved_name[5024];
  1180. # endif
  1181. # endif
  1182. if(dir != "")
  1183. {
  1184. realpath(dir.c_str(), resolved_name);
  1185. dir = resolved_name;
  1186. }
  1187. else
  1188. {
  1189. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1190. }
  1191. if(file == "")
  1192. {
  1193. return dir;
  1194. }
  1195. return dir + "/" + file;
  1196. #endif
  1197. }
  1198. /**
  1199. * Return path of a full filename (no trailing slashes).
  1200. * Warning: returned path is converted to Unix slashes format.
  1201. */
  1202. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1203. {
  1204. std::string fn = filename;
  1205. cmSystemTools::ConvertToUnixSlashes(fn);
  1206. std::string::size_type slash_pos = fn.rfind("/");
  1207. if(slash_pos != std::string::npos)
  1208. {
  1209. return fn.substr(0, slash_pos);
  1210. }
  1211. else
  1212. {
  1213. return "";
  1214. }
  1215. }
  1216. /**
  1217. * Return file name of a full filename (i.e. file name without path).
  1218. */
  1219. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1220. {
  1221. std::string fn = filename;
  1222. cmSystemTools::ConvertToUnixSlashes(fn);
  1223. std::string::size_type slash_pos = fn.rfind("/");
  1224. if(slash_pos != std::string::npos)
  1225. {
  1226. return fn.substr(slash_pos + 1);
  1227. }
  1228. else
  1229. {
  1230. return filename;
  1231. }
  1232. }
  1233. /**
  1234. * Return file extension of a full filename (dot included).
  1235. * Warning: this is the longest extension (for example: .tar.gz)
  1236. */
  1237. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1238. {
  1239. std::string name = cmSystemTools::GetFilenameName(filename);
  1240. std::string::size_type dot_pos = name.find(".");
  1241. if(dot_pos != std::string::npos)
  1242. {
  1243. return name.substr(dot_pos);
  1244. }
  1245. else
  1246. {
  1247. return "";
  1248. }
  1249. }
  1250. /**
  1251. * Return file extension of a full filename (dot included).
  1252. */
  1253. std::string cmSystemTools::GetFilenameShortestExtension(const std::string& filename)
  1254. {
  1255. std::string name = cmSystemTools::GetFilenameName(filename);
  1256. std::string::size_type dot_pos = name.rfind(".");
  1257. if(dot_pos != std::string::npos)
  1258. {
  1259. return name.substr(dot_pos);
  1260. }
  1261. else
  1262. {
  1263. return "";
  1264. }
  1265. }
  1266. /**
  1267. * Return file name without extension of a full filename (i.e. without path).
  1268. * Warning: it considers the longest extension (for example: .tar.gz)
  1269. */
  1270. std::string cmSystemTools::GetFilenameNameWithoutExtension(const std::string& filename)
  1271. {
  1272. std::string name = cmSystemTools::GetFilenameName(filename);
  1273. std::string::size_type dot_pos = name.find(".");
  1274. if(dot_pos != std::string::npos)
  1275. {
  1276. return name.substr(0, dot_pos);
  1277. }
  1278. else
  1279. {
  1280. return name;
  1281. }
  1282. }
  1283. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1284. std::vector<std::string>& files)
  1285. {
  1286. cmDirectory d;
  1287. cmRegularExpression reg(regexp);
  1288. if (d.Load(directory))
  1289. {
  1290. int i, numf;
  1291. numf = d.GetNumberOfFiles();
  1292. for (i = 0; i < numf; i++)
  1293. {
  1294. std::string fname = d.GetFile(i);
  1295. if (reg.find(fname))
  1296. {
  1297. files.push_back(fname);
  1298. }
  1299. }
  1300. }
  1301. }
  1302. void cmSystemTools::GlobDirs(const char *fullPath,
  1303. std::vector<std::string>& files)
  1304. {
  1305. std::string path = fullPath;
  1306. std::string::size_type pos = path.find("/*");
  1307. if(pos == std::string::npos)
  1308. {
  1309. files.push_back(fullPath);
  1310. return;
  1311. }
  1312. std::string startPath = path.substr(0, pos);
  1313. std::string finishPath = path.substr(pos+2);
  1314. cmDirectory d;
  1315. if (d.Load(startPath.c_str()))
  1316. {
  1317. for (int i = 0; i < d.GetNumberOfFiles(); ++i)
  1318. {
  1319. if((std::string(d.GetFile(i)) != ".")
  1320. && (std::string(d.GetFile(i)) != ".."))
  1321. {
  1322. std::string fname = startPath;
  1323. fname +="/";
  1324. fname += d.GetFile(i);
  1325. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1326. {
  1327. fname += finishPath;
  1328. cmSystemTools::GlobDirs(fname.c_str(), files);
  1329. }
  1330. }
  1331. }
  1332. }
  1333. }