cmSystemTools.cxx 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  1. /*=========================================================================
  2. Program: Insight Segmentation & Registration Toolkit
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2001 Insight Consortium
  8. All rights reserved.
  9. Redistribution and use in source and binary forms, with or without
  10. modification, are permitted provided that the following conditions are met:
  11. * Redistributions of source code must retain the above copyright notice,
  12. this list of conditions and the following disclaimer.
  13. * Redistributions in binary form must reproduce the above copyright notice,
  14. this list of conditions and the following disclaimer in the documentation
  15. and/or other materials provided with the distribution.
  16. * The name of the Insight Consortium, nor the names of any consortium members,
  17. nor of any contributors, may be used to endorse or promote products derived
  18. from this software without specific prior written permission.
  19. * Modified source versions must be plainly marked as such, and must not be
  20. misrepresented as being the original software.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
  22. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24. ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
  25. ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  26. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  27. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  28. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  29. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. =========================================================================*/
  32. #include "cmSystemTools.h"
  33. #include "errno.h"
  34. #include "stdio.h"
  35. #include <sys/stat.h>
  36. #include "cmRegularExpression.h"
  37. #include <ctype.h>
  38. #include "cmDirectory.h"
  39. // support for realpath call
  40. #ifndef _WIN32
  41. #include <limits.h>
  42. #include <stdlib.h>
  43. #include <sys/param.h>
  44. #endif
  45. #if defined(_MSC_VER) || defined(__BORLANDC__)
  46. #include <windows.h>
  47. #include <direct.h>
  48. #define _unlink unlink
  49. inline int Mkdir(const char* dir)
  50. {
  51. return _mkdir(dir);
  52. }
  53. inline const char* Getcwd(char* buf, unsigned int len)
  54. {
  55. return _getcwd(buf, len);
  56. }
  57. inline int Chdir(const char* dir)
  58. {
  59. #if defined(__BORLANDC__)
  60. return chdir(dir);
  61. #else
  62. return _chdir(dir);
  63. #endif
  64. }
  65. #else
  66. #include <sys/types.h>
  67. #include <fcntl.h>
  68. #include <unistd.h>
  69. inline int Mkdir(const char* dir)
  70. {
  71. return mkdir(dir, 00777);
  72. }
  73. inline const char* Getcwd(char* buf, unsigned int len)
  74. {
  75. return getcwd(buf, len);
  76. }
  77. inline int Chdir(const char* dir)
  78. {
  79. return chdir(dir);
  80. }
  81. #endif
  82. bool cmSystemTools::s_DisableRunCommandOutput = false;
  83. bool cmSystemTools::s_ErrorOccured = false;
  84. bool cmSystemTools::s_DisableMessages = false;
  85. void (*cmSystemTools::s_ErrorCallback)(const char*, const char*, bool&);
  86. // adds the elements of the env variable path to the arg passed in
  87. void cmSystemTools::GetPath(std::vector<std::string>& path)
  88. {
  89. #if defined(_WIN32) && !defined(__CYGWIN__)
  90. const char* pathSep = ";";
  91. #else
  92. const char* pathSep = ":";
  93. #endif
  94. std::string pathEnv = getenv("PATH");
  95. // A hack to make the below algorithm work.
  96. if(pathEnv[pathEnv.length()-1] != ':')
  97. {
  98. pathEnv += pathSep;
  99. }
  100. std::string::size_type start =0;
  101. bool done = false;
  102. while(!done)
  103. {
  104. std::string::size_type endpos = pathEnv.find(pathSep, start);
  105. if(endpos != std::string::npos)
  106. {
  107. path.push_back(pathEnv.substr(start, endpos-start));
  108. start = endpos+1;
  109. }
  110. else
  111. {
  112. done = true;
  113. }
  114. }
  115. for(std::vector<std::string>::iterator i = path.begin();
  116. i != path.end(); ++i)
  117. {
  118. cmSystemTools::ConvertToUnixSlashes(*i);
  119. }
  120. }
  121. const char* cmSystemTools::GetExecutableExtension()
  122. {
  123. #if defined(_WIN32) || defined(__CYGWIN__)
  124. return ".exe";
  125. #else
  126. return "";
  127. #endif
  128. }
  129. bool cmSystemTools::MakeDirectory(const char* path)
  130. {
  131. if(cmSystemTools::FileExists(path))
  132. {
  133. return true;
  134. }
  135. std::string dir = path;
  136. if(dir.size() == 0)
  137. {
  138. return false;
  139. }
  140. cmSystemTools::ConvertToUnixSlashes(dir);
  141. std::string::size_type pos = dir.find(':');
  142. if(pos == std::string::npos)
  143. {
  144. pos = 0;
  145. }
  146. std::string topdir;
  147. while((pos = dir.find('/', pos)) != std::string::npos)
  148. {
  149. topdir = dir.substr(0, pos);
  150. Mkdir(topdir.c_str());
  151. pos++;
  152. }
  153. if(dir[dir.size()-1] == '/')
  154. {
  155. topdir = dir.substr(0, dir.size());
  156. }
  157. else
  158. {
  159. topdir = dir;
  160. }
  161. if(Mkdir(topdir.c_str()) != 0)
  162. {
  163. // There is a bug in the Borland Run time library which makes MKDIR
  164. // return EACCES when it should return EEXISTS
  165. // if it is some other error besides directory exists
  166. // then return false
  167. if( (errno != EEXIST)
  168. #ifdef __BORLANDC__
  169. && (errno != EACCES)
  170. #endif
  171. )
  172. {
  173. cmSystemTools::Error("Faild to create directory:", path);
  174. return false;
  175. }
  176. }
  177. return true;
  178. }
  179. // replace replace with with as many times as it shows up in source.
  180. // write the result into source.
  181. void cmSystemTools::ReplaceString(std::string& source,
  182. const char* replace,
  183. const char* with)
  184. {
  185. int lengthReplace = strlen(replace);
  186. std::string rest;
  187. size_t start = source.find(replace);
  188. while(start != std::string::npos)
  189. {
  190. rest = source.substr(start+lengthReplace);
  191. source = source.substr(0, start);
  192. source += with;
  193. source += rest;
  194. start = source.find(replace, start + lengthReplace );
  195. }
  196. }
  197. #if defined(_WIN32) && !defined(__CYGWIN__)
  198. // Get the data of key value.
  199. // Example :
  200. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  201. // => will return the data of the "default" value of the key
  202. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  203. // => will return the data of the "Root" value of the key
  204. bool ReadAValue(std::string &res, const char *key)
  205. {
  206. // find the primary key
  207. std::string primary = key;
  208. std::string second;
  209. std::string valuename;
  210. size_t start = primary.find("\\");
  211. if (start == std::string::npos)
  212. {
  213. return false;
  214. }
  215. size_t valuenamepos = primary.find(";");
  216. if (valuenamepos != std::string::npos)
  217. {
  218. valuename = primary.substr(valuenamepos+1);
  219. }
  220. second = primary.substr(start+1, valuenamepos-start-1);
  221. primary = primary.substr(0, start);
  222. HKEY primaryKey;
  223. if (primary == "HKEY_CURRENT_USER")
  224. {
  225. primaryKey = HKEY_CURRENT_USER;
  226. }
  227. if (primary == "HKEY_CURRENT_CONFIG")
  228. {
  229. primaryKey = HKEY_CURRENT_CONFIG;
  230. }
  231. if (primary == "HKEY_CLASSES_ROOT")
  232. {
  233. primaryKey = HKEY_CLASSES_ROOT;
  234. }
  235. if (primary == "HKEY_LOCAL_MACHINE")
  236. {
  237. primaryKey = HKEY_LOCAL_MACHINE;
  238. }
  239. if (primary == "HKEY_USERS")
  240. {
  241. primaryKey = HKEY_USERS;
  242. }
  243. HKEY hKey;
  244. if(RegOpenKeyEx(primaryKey, second.c_str(),
  245. 0, KEY_READ, &hKey) != ERROR_SUCCESS)
  246. {
  247. return false;
  248. }
  249. else
  250. {
  251. DWORD dwType, dwSize;
  252. dwSize = 1023;
  253. char data[1024];
  254. if(RegQueryValueEx(hKey, (LPTSTR)valuename.c_str(), NULL, &dwType,
  255. (BYTE *)data, &dwSize) == ERROR_SUCCESS)
  256. {
  257. if (dwType == REG_SZ)
  258. {
  259. res = data;
  260. return true;
  261. }
  262. }
  263. }
  264. return false;
  265. }
  266. #endif
  267. // replace replace with with as many times as it shows up in source.
  268. // write the result into source.
  269. void cmSystemTools::ExpandRegistryValues(std::string& source)
  270. {
  271. #if defined(_WIN32) && !defined(__CYGWIN__)
  272. // Regular expression to match anything inside [...] that begins in HKEY.
  273. // Note that there is a special rule for regular expressions to match a
  274. // close square-bracket inside a list delimited by square brackets.
  275. // The "[^]]" part of this expression will match any character except
  276. // a close square-bracket. The ']' character must be the first in the
  277. // list of characters inside the [^...] block of the expression.
  278. cmRegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  279. // check for black line or comment
  280. while (regEntry.find(source))
  281. {
  282. // the arguments are the second match
  283. std::string key = regEntry.match(1);
  284. std::string val;
  285. if (ReadAValue(val,key.c_str()))
  286. {
  287. std::string reg = "[";
  288. reg += key + "]";
  289. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  290. }
  291. else
  292. {
  293. std::string reg = "[";
  294. reg += key + "]";
  295. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  296. }
  297. }
  298. #endif
  299. }
  300. std::string cmSystemTools::HandleNetworkPaths(const char* str)
  301. {
  302. #if defined(_WIN32) && !defined(__CYGWIN__)
  303. std::string result;
  304. // watch for network paths, MSVC can't seem to load //
  305. if (strlen(str) > 2 && str[0] == '/' && str[1] == '/')
  306. {
  307. result = "\\\\";
  308. result += (str + 2);
  309. }
  310. else
  311. {
  312. result += str;
  313. }
  314. #else
  315. std::string result = "";
  316. #endif
  317. return result;
  318. }
  319. std::string cmSystemTools::EscapeSpaces(const char* str)
  320. {
  321. #if defined(_WIN32) && !defined(__CYGWIN__)
  322. std::string result;
  323. // if there are spaces
  324. std::string temp = str;
  325. if (temp.find(" ") != std::string::npos)
  326. {
  327. // don't add quotes if they're already there
  328. if (temp.find("\"")==std::string::npos)
  329. {
  330. result = "\"";
  331. }
  332. result += cmSystemTools::HandleNetworkPaths(str);
  333. if (temp.find("\"")==std::string::npos)
  334. {
  335. result += "\"";
  336. }
  337. return result;
  338. }
  339. return cmSystemTools::HandleNetworkPaths(str);
  340. #else
  341. std::string result = "";
  342. for(const char* ch = str; *ch != '\0'; ++ch)
  343. {
  344. if(*ch == ' ')
  345. {
  346. result += '\\';
  347. }
  348. result += *ch;
  349. }
  350. return result;
  351. #endif
  352. }
  353. std::string cmSystemTools::EscapeQuotes(const char* str)
  354. {
  355. std::string result = "";
  356. for(const char* ch = str; *ch != '\0'; ++ch)
  357. {
  358. if(*ch == '"')
  359. {
  360. result += '\\';
  361. }
  362. result += *ch;
  363. }
  364. return result;
  365. }
  366. bool cmSystemTools::SameFile(const char* file1, const char* file2)
  367. {
  368. struct stat fileStat1, fileStat2;
  369. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  370. {
  371. // see if the files are the same file
  372. // check the device inode and size
  373. if(fileStat2.st_dev == fileStat1.st_dev &&
  374. fileStat2.st_ino == fileStat1.st_ino &&
  375. fileStat2.st_size == fileStat1.st_size
  376. )
  377. {
  378. return true;
  379. }
  380. }
  381. return false;
  382. }
  383. // return true if the file exists
  384. bool cmSystemTools::FileExists(const char* filename)
  385. {
  386. struct stat fs;
  387. if (stat(filename, &fs) != 0)
  388. {
  389. return false;
  390. }
  391. else
  392. {
  393. return true;
  394. }
  395. }
  396. // Return a capitalized string (i.e the first letter is uppercased, all other
  397. // are lowercased)
  398. std::string cmSystemTools::Capitalized(const std::string& s)
  399. {
  400. std::string n;
  401. n.resize(s.size());
  402. n[0] = toupper(s[0]);
  403. for (size_t i = 1; i < s.size(); i++)
  404. {
  405. n[i] = tolower(s[i]);
  406. }
  407. return n;
  408. }
  409. // Return a lower case string
  410. std::string cmSystemTools::LowerCase(const std::string& s)
  411. {
  412. std::string n;
  413. n.resize(s.size());
  414. for (size_t i = 0; i < s.size(); i++)
  415. {
  416. n[i] = tolower(s[i]);
  417. }
  418. return n;
  419. }
  420. // Return a lower case string
  421. std::string cmSystemTools::UpperCase(const std::string& s)
  422. {
  423. std::string n;
  424. n.resize(s.size());
  425. for (size_t i = 0; i < s.size(); i++)
  426. {
  427. n[i] = toupper(s[i]);
  428. }
  429. return n;
  430. }
  431. // convert windows slashes to unix slashes \ with /
  432. const char *cmSystemTools::ConvertToUnixSlashes(std::string& path)
  433. {
  434. std::string::size_type pos = 0;
  435. while((pos = path.find('\\', pos)) != std::string::npos)
  436. {
  437. path[pos] = '/';
  438. pos++;
  439. }
  440. // remove any trailing slash
  441. if(path.size() && path[path.size()-1] == '/')
  442. {
  443. path = path.substr(0, path.size()-1);
  444. }
  445. // if there is a tilda ~ then replace it with HOME
  446. if(path.find("~") == 0)
  447. {
  448. if (getenv("HOME"))
  449. {
  450. path = std::string(getenv("HOME")) + path.substr(1);
  451. }
  452. }
  453. // if there is a /tmp_mnt in a path get rid of it!
  454. // stupid sgi's
  455. if(path.find("/tmp_mnt") == 0)
  456. {
  457. path = path.substr(8);
  458. }
  459. return path.c_str();
  460. }
  461. // convert windows slashes to unix slashes
  462. const char *cmSystemTools::ConvertToWindowsSlashes(std::string& path)
  463. {
  464. std::string::size_type pos = 0;
  465. while((pos = path.find('/', pos)) != std::string::npos)
  466. {
  467. path[pos] = '\\';
  468. pos++;
  469. }
  470. // remove any trailing slash
  471. if(path[path.size()-1] == '\\')
  472. {
  473. path = path.substr(0, path.size()-1);
  474. }
  475. return path.c_str();
  476. }
  477. // convert Unix slashes to Windows slashes and cleanup double slashes
  478. const char *cmSystemTools::ConvertToWindowsSlashesAndCleanUp(std::string& path)
  479. {
  480. cmSystemTools::ConvertToWindowsSlashes(path);
  481. std::string::size_type pos = 0;
  482. pos = 0;
  483. while((pos = path.find("\\\\", pos)) != std::string::npos)
  484. {
  485. path.erase(pos, 1);
  486. }
  487. return path.c_str();
  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. long 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. void cmSystemTools::CopyFileIfDifferent(const char* source,
  710. const char* destination)
  711. {
  712. if(cmSystemTools::FilesDiffer(source, destination))
  713. {
  714. cmSystemTools::cmCopyFile(source, destination);
  715. }
  716. }
  717. bool cmSystemTools::FilesDiffer(const char* source,
  718. const char* destination)
  719. {
  720. struct stat statSource;
  721. if (stat(source, &statSource) != 0)
  722. {
  723. return true;
  724. }
  725. struct stat statDestination;
  726. if (stat(destination, &statDestination) != 0)
  727. {
  728. return true;
  729. }
  730. if(statSource.st_size != statDestination.st_size)
  731. {
  732. return true;
  733. }
  734. std::ifstream finSource(source);
  735. std::ifstream finDestination(destination);
  736. if(!finSource || !finDestination)
  737. {
  738. return true;
  739. }
  740. while(finSource && finDestination)
  741. {
  742. char s, d;
  743. finSource >> s;
  744. finDestination >> d;
  745. if(s != d)
  746. {
  747. return true;
  748. }
  749. }
  750. return false;
  751. }
  752. /**
  753. * Copy a file named by "source" to the file named by "destination". This
  754. * implementation makes correct use of the C++ standard file streams to
  755. * perfectly copy any file with lines of any length (even binary files).
  756. */
  757. void cmSystemTools::cmCopyFile(const char* source,
  758. const char* destination)
  759. {
  760. // Buffer length is only for block size. Any file would still be copied
  761. // correctly if this were as small as 2.
  762. const int buffer_length = 4096;
  763. char buffer[buffer_length];
  764. std::ifstream fin(source,
  765. #ifdef _WIN32
  766. std::ios::binary |
  767. #endif
  768. std::ios::in);
  769. if(!fin)
  770. {
  771. cmSystemTools::Error("CopyFile failed to open input file \"",
  772. source, "\"");
  773. return;
  774. }
  775. std::ofstream fout(destination,
  776. #ifdef _WIN32
  777. std::ios::binary |
  778. #endif
  779. std::ios::out | std::ios::trunc);
  780. if(!fout)
  781. {
  782. cmSystemTools::Error("CopyFile failed to open output file \"",
  783. destination, "\"");
  784. return;
  785. }
  786. while(fin.getline(buffer, buffer_length, '\n') || fin.gcount())
  787. {
  788. unsigned long count = fin.gcount();
  789. if(fin.eof())
  790. {
  791. // Final line, but with no newline.
  792. fout.write(buffer, count);
  793. }
  794. else if(fin.fail())
  795. {
  796. // Part of a line longer than our buffer, clear the fail bit of
  797. // the stream so that we can continue.
  798. fin.clear(fin.rdstate() & ~std::ios::failbit);
  799. fout.write(buffer, count);
  800. }
  801. else
  802. {
  803. // Line on which a newline was encountered. It was read from
  804. // the stream, but not stored.
  805. --count;
  806. fout.write(buffer, count);
  807. fout << '\n';
  808. }
  809. }
  810. }
  811. // return true if the file exists
  812. long int cmSystemTools::ModifiedTime(const char* filename)
  813. {
  814. struct stat fs;
  815. if (stat(filename, &fs) != 0)
  816. {
  817. return 0;
  818. }
  819. else
  820. {
  821. return (long int)fs.st_mtime;
  822. }
  823. }
  824. void cmSystemTools::RemoveFile(const char* source)
  825. {
  826. unlink(source);
  827. }
  828. bool cmSystemTools::IsOn(const char* val)
  829. {
  830. if (!val)
  831. {
  832. return false;
  833. }
  834. std::basic_string<char> v = val;
  835. for(std::basic_string<char>::iterator c = v.begin();
  836. c != v.end(); c++)
  837. {
  838. *c = toupper(*c);
  839. }
  840. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  841. }
  842. bool cmSystemTools::IsOff(const char* val)
  843. {
  844. if (!val || strlen(val) == 0)
  845. {
  846. return true;
  847. }
  848. std::basic_string<char> v = val;
  849. for(std::basic_string<char>::iterator c = v.begin();
  850. c != v.end(); c++)
  851. {
  852. *c = toupper(*c);
  853. }
  854. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  855. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  856. }
  857. bool cmSystemTools::RunCommand(const char* command,
  858. std::string& output,
  859. bool verbose)
  860. {
  861. int foo;
  862. return cmSystemTools::RunCommand(command, output, foo, verbose);
  863. }
  864. bool cmSystemTools::RunCommand(const char* command,
  865. std::string& output,
  866. int &retVal, bool verbose)
  867. {
  868. const int BUFFER_SIZE = 4096;
  869. char buffer[BUFFER_SIZE];
  870. if(s_DisableRunCommandOutput)
  871. {
  872. verbose = false;
  873. }
  874. #if defined(WIN32) && !defined(__CYGWIN__)
  875. std::string commandToFile = command;
  876. commandToFile += " > ";
  877. std::string tempFile;
  878. tempFile += _tempnam(0, "cmake");
  879. commandToFile += tempFile;
  880. retVal = system(commandToFile.c_str());
  881. std::ifstream fin(tempFile.c_str());
  882. if(!fin)
  883. {
  884. if(verbose)
  885. {
  886. std::string errormsg = "RunCommand produced no output: command: \"";
  887. errormsg += command;
  888. errormsg += "\"";
  889. errormsg += "\nOutput file: ";
  890. errormsg += tempFile;
  891. cmSystemTools::Error(errormsg.c_str());
  892. }
  893. fin.close();
  894. cmSystemTools::RemoveFile(tempFile.c_str());
  895. return false;
  896. }
  897. while(fin)
  898. {
  899. fin.getline(buffer, BUFFER_SIZE);
  900. output += buffer;
  901. }
  902. fin.close();
  903. cmSystemTools::RemoveFile(tempFile.c_str());
  904. return true;
  905. #else
  906. if(verbose)
  907. {
  908. std::cout << "running " << command << std::endl;
  909. }
  910. FILE* cpipe = popen(command, "r");
  911. if(!cpipe)
  912. {
  913. return false;
  914. }
  915. fgets(buffer, BUFFER_SIZE, cpipe);
  916. while(!feof(cpipe))
  917. {
  918. if(verbose)
  919. {
  920. std::cout << buffer << std::flush;
  921. }
  922. output += buffer;
  923. fgets(buffer, BUFFER_SIZE, cpipe);
  924. }
  925. retVal = pclose(cpipe);
  926. return true;
  927. #endif
  928. }
  929. /**
  930. * Find the file the given name. Searches the given path and then
  931. * the system search path. Returns the full path to the file if it is
  932. * found. Otherwise, the empty string is returned.
  933. */
  934. std::string cmSystemTools::FindFile(const char* name,
  935. const std::vector<std::string>& userPaths)
  936. {
  937. // Add the system search path to our path.
  938. std::vector<std::string> path = userPaths;
  939. cmSystemTools::GetPath(path);
  940. std::string tryPath;
  941. for(std::vector<std::string>::const_iterator p = path.begin();
  942. p != path.end(); ++p)
  943. {
  944. tryPath = *p;
  945. tryPath += "/";
  946. tryPath += name;
  947. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  948. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  949. {
  950. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  951. }
  952. }
  953. // Couldn't find the file.
  954. return "";
  955. }
  956. /**
  957. * Find the executable with the given name. Searches the given path and then
  958. * the system search path. Returns the full path to the executable if it is
  959. * found. Otherwise, the empty string is returned.
  960. */
  961. std::string cmSystemTools::FindProgram(const char* name,
  962. const std::vector<std::string>& userPaths)
  963. {
  964. // See if the executable exists as written.
  965. if(cmSystemTools::FileExists(name) &&
  966. !cmSystemTools::FileIsDirectory(name))
  967. {
  968. return cmSystemTools::CollapseFullPath(name);
  969. }
  970. std::string tryPath = name;
  971. tryPath += cmSystemTools::GetExecutableExtension();
  972. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  973. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  974. {
  975. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  976. }
  977. // Add the system search path to our path.
  978. std::vector<std::string> path = userPaths;
  979. cmSystemTools::GetPath(path);
  980. for(std::vector<std::string>::const_iterator p = path.begin();
  981. p != path.end(); ++p)
  982. {
  983. tryPath = *p;
  984. tryPath += "/";
  985. tryPath += name;
  986. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  987. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  988. {
  989. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  990. }
  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. }
  998. // Couldn't find the program.
  999. return "";
  1000. }
  1001. /**
  1002. * Find the library with the given name. Searches the given path and then
  1003. * the system search path. Returns the full path to the library if it is
  1004. * found. Otherwise, the empty string is returned.
  1005. */
  1006. std::string cmSystemTools::FindLibrary(const char* name,
  1007. const std::vector<std::string>& userPaths)
  1008. {
  1009. // See if the executable exists as written.
  1010. if(cmSystemTools::FileExists(name))
  1011. {
  1012. return cmSystemTools::CollapseFullPath(name);
  1013. }
  1014. // Add the system search path to our path.
  1015. std::vector<std::string> path = userPaths;
  1016. cmSystemTools::GetPath(path);
  1017. std::string tryPath;
  1018. for(std::vector<std::string>::const_iterator p = path.begin();
  1019. p != path.end(); ++p)
  1020. {
  1021. #if defined(_WIN32) && !defined(__CYGWIN__)
  1022. tryPath = *p;
  1023. tryPath += "/";
  1024. tryPath += name;
  1025. tryPath += ".lib";
  1026. if(cmSystemTools::FileExists(tryPath.c_str()))
  1027. {
  1028. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1029. }
  1030. #else
  1031. tryPath = *p;
  1032. tryPath += "/lib";
  1033. tryPath += name;
  1034. tryPath += ".so";
  1035. if(cmSystemTools::FileExists(tryPath.c_str()))
  1036. {
  1037. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1038. }
  1039. tryPath = *p;
  1040. tryPath += "/lib";
  1041. tryPath += name;
  1042. tryPath += ".a";
  1043. if(cmSystemTools::FileExists(tryPath.c_str()))
  1044. {
  1045. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1046. }
  1047. tryPath = *p;
  1048. tryPath += "/lib";
  1049. tryPath += name;
  1050. tryPath += ".sl";
  1051. if(cmSystemTools::FileExists(tryPath.c_str()))
  1052. {
  1053. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1054. }
  1055. #endif
  1056. }
  1057. // Couldn't find the library.
  1058. return "";
  1059. }
  1060. bool cmSystemTools::FileIsDirectory(const char* name)
  1061. {
  1062. struct stat fs;
  1063. if(stat(name, &fs) == 0)
  1064. {
  1065. #if _WIN32
  1066. return ((fs.st_mode & _S_IFDIR) != 0);
  1067. #else
  1068. return S_ISDIR(fs.st_mode);
  1069. #endif
  1070. }
  1071. else
  1072. {
  1073. return false;
  1074. }
  1075. }
  1076. int cmSystemTools::ChangeDirectory(const char *dir)
  1077. {
  1078. return Chdir(dir);
  1079. }
  1080. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1081. {
  1082. char buf[2048];
  1083. std::string path = Getcwd(buf, 2048);
  1084. return path;
  1085. }
  1086. /**
  1087. * Given the path to a program executable, get the directory part of the path with the
  1088. * file stripped off. If there is no directory part, the empty string is returned.
  1089. */
  1090. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1091. {
  1092. std::string dir, file;
  1093. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1094. return dir;
  1095. }
  1096. /**
  1097. * Given the path to a program executable, get the directory part of the path
  1098. * with the file stripped off. If there is no directory part, the empty
  1099. * string is returned.
  1100. */
  1101. void cmSystemTools::SplitProgramPath(const char* in_name,
  1102. std::string& dir,
  1103. std::string& file)
  1104. {
  1105. dir = in_name;
  1106. file = "";
  1107. cmSystemTools::ConvertToUnixSlashes(dir);
  1108. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1109. {
  1110. std::string::size_type slashPos = dir.rfind("/");
  1111. if(slashPos != std::string::npos)
  1112. {
  1113. file = dir.substr(slashPos+1);
  1114. dir = dir.substr(0, slashPos);
  1115. }
  1116. else
  1117. {
  1118. file = dir;
  1119. dir = "";
  1120. }
  1121. }
  1122. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1123. {
  1124. std::string oldDir = in_name;
  1125. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1126. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1127. oldDir.c_str(), "\nDirectory not found: ",
  1128. dir.c_str());
  1129. dir = in_name;
  1130. return;
  1131. }
  1132. }
  1133. /**
  1134. * Given a path to a file or directory, convert it to a full path.
  1135. * This collapses away relative paths. The full path is returned.
  1136. */
  1137. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1138. {
  1139. std::string dir, file;
  1140. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1141. #ifdef _WIN32
  1142. // Ultra-hack warning:
  1143. // This changes to the target directory, saves the working directory,
  1144. // and then changes back to the original working directory.
  1145. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1146. if(dir != "") { Chdir(dir.c_str()); }
  1147. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1148. Chdir(cwd.c_str());
  1149. cmSystemTools::ConvertToUnixSlashes(newDir);
  1150. std::string newPath = newDir+"/"+file;
  1151. return newPath;
  1152. #else
  1153. # ifdef MAXPATHLEN
  1154. char resolved_name[MAXPATHLEN];
  1155. # else
  1156. # ifdef PATH_MAX
  1157. char resolved_name[PATH_MAX];
  1158. # else
  1159. char resolved_name[5024];
  1160. # endif
  1161. # endif
  1162. if(dir != "")
  1163. {
  1164. realpath(dir.c_str(), resolved_name);
  1165. dir = resolved_name;
  1166. }
  1167. else
  1168. {
  1169. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1170. }
  1171. return dir + "/" + file;
  1172. #endif
  1173. }
  1174. /**
  1175. * Return path of a full filename (no trailing slashes).
  1176. * Warning: returned path is converted to Unix slashes format.
  1177. */
  1178. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1179. {
  1180. std::string fn = filename;
  1181. cmSystemTools::ConvertToUnixSlashes(fn);
  1182. std::string::size_type slash_pos = fn.rfind("/");
  1183. if(slash_pos != std::string::npos)
  1184. {
  1185. return fn.substr(0, slash_pos);
  1186. }
  1187. else
  1188. {
  1189. return "";
  1190. }
  1191. }
  1192. /**
  1193. * Return file name of a full filename (i.e. file name without path).
  1194. */
  1195. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1196. {
  1197. std::string fn = filename;
  1198. cmSystemTools::ConvertToUnixSlashes(fn);
  1199. std::string::size_type slash_pos = fn.rfind("/");
  1200. if(slash_pos != std::string::npos)
  1201. {
  1202. return fn.substr(slash_pos + 1);
  1203. }
  1204. else
  1205. {
  1206. return filename;
  1207. }
  1208. }
  1209. /**
  1210. * Return file extension of a full filename (dot included).
  1211. * Warning: this is the longest extension (for example: .tar.gz)
  1212. */
  1213. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1214. {
  1215. std::string name = cmSystemTools::GetFilenameName(filename);
  1216. std::string::size_type dot_pos = name.find(".");
  1217. if(dot_pos != std::string::npos)
  1218. {
  1219. return name.substr(dot_pos);
  1220. }
  1221. else
  1222. {
  1223. return "";
  1224. }
  1225. }
  1226. /**
  1227. * Return file extension of a full filename (dot included).
  1228. */
  1229. std::string cmSystemTools::GetFilenameShortestExtension(const std::string& filename)
  1230. {
  1231. std::string name = cmSystemTools::GetFilenameName(filename);
  1232. std::string::size_type dot_pos = name.rfind(".");
  1233. if(dot_pos != std::string::npos)
  1234. {
  1235. return name.substr(dot_pos);
  1236. }
  1237. else
  1238. {
  1239. return "";
  1240. }
  1241. }
  1242. /**
  1243. * Return file name without extension of a full filename (i.e. without path).
  1244. * Warning: it considers the longest extension (for example: .tar.gz)
  1245. */
  1246. std::string cmSystemTools::GetFilenameNameWithoutExtension(const std::string& filename)
  1247. {
  1248. std::string name = cmSystemTools::GetFilenameName(filename);
  1249. std::string::size_type dot_pos = name.find(".");
  1250. if(dot_pos != std::string::npos)
  1251. {
  1252. return name.substr(0, dot_pos);
  1253. }
  1254. else
  1255. {
  1256. return name;
  1257. }
  1258. }
  1259. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1260. std::vector<std::string>& files)
  1261. {
  1262. cmDirectory d;
  1263. cmRegularExpression reg(regexp);
  1264. if (d.Load(directory))
  1265. {
  1266. int i, numf;
  1267. numf = d.GetNumberOfFiles();
  1268. for (i = 0; i < numf; i++)
  1269. {
  1270. std::string fname = d.GetFile(i);
  1271. if (reg.find(fname))
  1272. {
  1273. files.push_back(fname);
  1274. }
  1275. }
  1276. }
  1277. }
  1278. void cmSystemTools::GlobDirs(const char *fullPath,
  1279. std::vector<std::string>& files)
  1280. {
  1281. std::string path = fullPath;
  1282. std::string::size_type pos = path.find("/*");
  1283. if(pos == std::string::npos)
  1284. {
  1285. files.push_back(fullPath);
  1286. return;
  1287. }
  1288. std::string startPath = path.substr(0, pos);
  1289. std::string finishPath = path.substr(pos+2);
  1290. cmDirectory d;
  1291. if (d.Load(startPath.c_str()))
  1292. {
  1293. for (int i = 0; i < d.GetNumberOfFiles(); ++i)
  1294. {
  1295. if((std::string(d.GetFile(i)) != ".")
  1296. && (std::string(d.GetFile(i)) != ".."))
  1297. {
  1298. std::string fname = startPath;
  1299. fname +="/";
  1300. fname += d.GetFile(i);
  1301. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1302. {
  1303. fname += finishPath;
  1304. cmSystemTools::GlobDirs(fname.c_str(), files);
  1305. }
  1306. }
  1307. }
  1308. }
  1309. }