cmSystemTools.cxx 35 KB

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