cmSystemTools.cxx 35 KB

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