cmSystemTools.cxx 35 KB

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