cmSystemTools.cxx 34 KB

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