cmSystemTools.cxx 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  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. #if defined(_MSC_VER) || defined(__BORLANDC__)
  40. #include <windows.h>
  41. #include <direct.h>
  42. #define _unlink unlink
  43. inline int Mkdir(const char* dir)
  44. {
  45. return _mkdir(dir);
  46. }
  47. inline const char* Getcwd(char* buf, unsigned int len)
  48. {
  49. return _getcwd(buf, len);
  50. }
  51. inline int Chdir(const char* dir)
  52. {
  53. #if defined(__BORLANDC__)
  54. return chdir(dir);
  55. #else
  56. return _chdir(dir);
  57. #endif
  58. }
  59. #else
  60. #include <sys/types.h>
  61. #include <fcntl.h>
  62. #include <unistd.h>
  63. inline int Mkdir(const char* dir)
  64. {
  65. return mkdir(dir, 00777);
  66. }
  67. inline const char* Getcwd(char* buf, unsigned int len)
  68. {
  69. return getcwd(buf, len);
  70. }
  71. inline int Chdir(const char* dir)
  72. {
  73. return chdir(dir);
  74. }
  75. #endif
  76. bool cmSystemTools::s_ErrorOccured = false;
  77. // adds the elements of the env variable path to the arg passed in
  78. void cmSystemTools::GetPath(std::vector<std::string>& path)
  79. {
  80. #if defined(_WIN32) && !defined(__CYGWIN__)
  81. const char* pathSep = ";";
  82. #else
  83. const char* pathSep = ":";
  84. #endif
  85. std::string pathEnv = getenv("PATH");
  86. // A hack to make the below algorithm work.
  87. if(pathEnv[pathEnv.length()-1] != ':')
  88. {
  89. pathEnv += pathSep;
  90. }
  91. std::string::size_type start =0;
  92. bool done = false;
  93. while(!done)
  94. {
  95. std::string::size_type endpos = pathEnv.find(pathSep, start);
  96. if(endpos != std::string::npos)
  97. {
  98. path.push_back(pathEnv.substr(start, endpos-start));
  99. start = endpos+1;
  100. }
  101. else
  102. {
  103. done = true;
  104. }
  105. }
  106. for(std::vector<std::string>::iterator i = path.begin();
  107. i != path.end(); ++i)
  108. {
  109. cmSystemTools::ConvertToUnixSlashes(*i);
  110. }
  111. }
  112. const char* cmSystemTools::GetExecutableExtension()
  113. {
  114. #if defined(_WIN32) || defined(__CYGWIN__)
  115. return ".exe";
  116. #else
  117. return "";
  118. #endif
  119. }
  120. bool cmSystemTools::MakeDirectory(const char* path)
  121. {
  122. std::string dir = path;
  123. cmSystemTools::ConvertToUnixSlashes(dir);
  124. std::string::size_type pos = dir.find(':');
  125. if(pos == std::string::npos)
  126. {
  127. pos = 0;
  128. }
  129. while((pos = dir.find('/', pos)) != std::string::npos)
  130. {
  131. std::string topdir = dir.substr(0, pos);
  132. Mkdir(topdir.c_str());
  133. pos++;
  134. }
  135. if(Mkdir(path) != 0)
  136. {
  137. // There is a bug in the Borland Run time library which makes MKDIR
  138. // return EACCES when it should return EEXISTS
  139. #ifdef __BORLANDC__
  140. if( (errno != EEXIST) && (errno != EACCES) )
  141. {
  142. return false;
  143. }
  144. #else
  145. // if it is some other error besides directory exists
  146. // then return false
  147. if(errno != EEXIST)
  148. {
  149. return false;
  150. }
  151. #endif
  152. }
  153. return true;
  154. }
  155. // replace replace with with as many times as it shows up in source.
  156. // write the result into source.
  157. void cmSystemTools::ReplaceString(std::string& source,
  158. const char* replace,
  159. const char* with)
  160. {
  161. int lengthReplace = strlen(replace);
  162. std::string rest;
  163. size_t start = source.find(replace);
  164. while(start != std::string::npos)
  165. {
  166. rest = source.substr(start+lengthReplace);
  167. source = source.substr(0, start);
  168. source += with;
  169. source += rest;
  170. start = source.find(replace, start + lengthReplace );
  171. }
  172. }
  173. #if defined(_WIN32) && !defined(__CYGWIN__)
  174. // Get the data of key value.
  175. // Example :
  176. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  177. // => will return the data of the "default" value of the key
  178. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  179. // => will return the data of the "Root" value of the key
  180. bool ReadAValue(std::string &res, const char *key)
  181. {
  182. // find the primary key
  183. std::string primary = key;
  184. std::string second;
  185. std::string valuename;
  186. size_t start = primary.find("\\");
  187. if (start == std::string::npos)
  188. {
  189. return false;
  190. }
  191. size_t valuenamepos = primary.find(";");
  192. if (valuenamepos != std::string::npos)
  193. {
  194. valuename = primary.substr(valuenamepos+1);
  195. }
  196. second = primary.substr(start+1, valuenamepos-start-1);
  197. primary = primary.substr(0, start);
  198. HKEY primaryKey;
  199. if (primary == "HKEY_CURRENT_USER")
  200. {
  201. primaryKey = HKEY_CURRENT_USER;
  202. }
  203. if (primary == "HKEY_CURRENT_CONFIG")
  204. {
  205. primaryKey = HKEY_CURRENT_CONFIG;
  206. }
  207. if (primary == "HKEY_CLASSES_ROOT")
  208. {
  209. primaryKey = HKEY_CLASSES_ROOT;
  210. }
  211. if (primary == "HKEY_LOCAL_MACHINE")
  212. {
  213. primaryKey = HKEY_LOCAL_MACHINE;
  214. }
  215. if (primary == "HKEY_USERS")
  216. {
  217. primaryKey = HKEY_USERS;
  218. }
  219. HKEY hKey;
  220. if(RegOpenKeyEx(primaryKey, second.c_str(),
  221. 0, KEY_READ, &hKey) != ERROR_SUCCESS)
  222. {
  223. return false;
  224. }
  225. else
  226. {
  227. DWORD dwType, dwSize;
  228. dwSize = 1023;
  229. char data[1024];
  230. if(RegQueryValueEx(hKey, (LPTSTR)valuename.c_str(), NULL, &dwType,
  231. (BYTE *)data, &dwSize) == ERROR_SUCCESS)
  232. {
  233. if (dwType == REG_SZ)
  234. {
  235. res = data;
  236. return true;
  237. }
  238. }
  239. }
  240. return false;
  241. }
  242. #endif
  243. // replace replace with with as many times as it shows up in source.
  244. // write the result into source.
  245. void cmSystemTools::ExpandRegistryValues(std::string& source)
  246. {
  247. #if defined(_WIN32) && !defined(__CYGWIN__)
  248. // Regular expression to match anything inside [...] that begins in HKEY.
  249. // Note that there is a special rule for regular expressions to match a
  250. // close square-bracket inside a list delimited by square brackets.
  251. // The "[^]]" part of this expression will match any character except
  252. // a close square-bracket. The ']' character must be the first in the
  253. // list of characters inside the [^...] block of the expression.
  254. cmRegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  255. // check for black line or comment
  256. while (regEntry.find(source))
  257. {
  258. // the arguments are the second match
  259. std::string key = regEntry.match(1);
  260. std::string val;
  261. if (ReadAValue(val,key.c_str()))
  262. {
  263. std::string reg = "[";
  264. reg += key + "]";
  265. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  266. }
  267. else
  268. {
  269. std::string reg = "[";
  270. reg += key + "]";
  271. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  272. }
  273. }
  274. #endif
  275. }
  276. std::string cmSystemTools::EscapeSpaces(const char* str)
  277. {
  278. #if defined(_WIN32) && !defined(__CYGWIN__)
  279. std::string result = str;
  280. return "\""+result+"\"";
  281. #else
  282. std::string result = "";
  283. for(const char* ch = str; *ch != '\0'; ++ch)
  284. {
  285. if(*ch == ' ')
  286. {
  287. result += '\\';
  288. }
  289. result += *ch;
  290. }
  291. return result;
  292. #endif
  293. }
  294. std::string cmSystemTools::EscapeQuotes(const char* str)
  295. {
  296. std::string result = "";
  297. for(const char* ch = str; *ch != '\0'; ++ch)
  298. {
  299. if(*ch == '"')
  300. {
  301. result += '\\';
  302. }
  303. result += *ch;
  304. }
  305. return result;
  306. }
  307. // return true if the file exists
  308. bool cmSystemTools::FileExists(const char* filename)
  309. {
  310. struct stat fs;
  311. if (stat(filename, &fs) != 0)
  312. {
  313. return false;
  314. }
  315. else
  316. {
  317. return true;
  318. }
  319. }
  320. // Return a capitalized string (i.e the first letter is uppercased, all other
  321. // are lowercased)
  322. std::string cmSystemTools::Capitalized(const std::string& s)
  323. {
  324. std::string n;
  325. n.resize(s.size());
  326. n[0] = toupper(s[0]);
  327. for (size_t i = 1; i < s.size(); i++)
  328. {
  329. n[i] = tolower(s[i]);
  330. }
  331. return n;
  332. }
  333. // convert windows slashes to unix slashes \ with /
  334. void cmSystemTools::ConvertToUnixSlashes(std::string& path)
  335. {
  336. std::string::size_type pos = 0;
  337. while((pos = path.find('\\', pos)) != std::string::npos)
  338. {
  339. path[pos] = '/';
  340. pos++;
  341. }
  342. // remove any trailing slash
  343. if(path.size() && path[path.size()-1] == '/')
  344. {
  345. path = path.substr(0, path.size()-1);
  346. }
  347. }
  348. // convert windows slashes to unix slashes \ with /
  349. void cmSystemTools::CleanUpWindowsSlashes(std::string& path)
  350. {
  351. std::string::size_type pos = 0;
  352. while((pos = path.find('/', pos)) != std::string::npos)
  353. {
  354. path[pos] = '\\';
  355. pos++;
  356. }
  357. // remove any trailing slash
  358. if(path[path.size()-1] == '\\')
  359. {
  360. path = path.substr(0, path.size()-1);
  361. }
  362. // remove any duplicate // slashes
  363. pos = 0;
  364. while((pos = path.find("\\\\", pos)) != std::string::npos)
  365. {
  366. path.erase(pos, 1);
  367. }
  368. }
  369. int cmSystemTools::Grep(const char* dir, const char* file,
  370. const char* expression)
  371. {
  372. std::string path = dir;
  373. path += "/";
  374. path += file;
  375. std::ifstream fin(path.c_str());
  376. char buffer[2056];
  377. int count = 0;
  378. cmRegularExpression reg(expression);
  379. while(fin)
  380. {
  381. fin.getline(buffer, sizeof(buffer));
  382. count += reg.find(buffer);
  383. }
  384. return count;
  385. }
  386. void cmSystemTools::ConvertCygwinPath(std::string& pathname)
  387. {
  388. if(pathname.find("/cygdrive/") != std::string::npos)
  389. {
  390. std::string cygStuff = pathname.substr(0, 11);
  391. std::string replace;
  392. replace += cygStuff.at(10);
  393. replace += ":";
  394. cmSystemTools::ReplaceString(pathname, cygStuff.c_str(), replace.c_str());
  395. }
  396. }
  397. bool cmSystemTools::ParseFunction(std::ifstream& fin,
  398. std::string& name,
  399. std::vector<std::string>& arguments)
  400. {
  401. name = "";
  402. arguments = std::vector<std::string>();
  403. const int BUFFER_SIZE = 4096;
  404. char inbuffer[BUFFER_SIZE];
  405. if(!fin)
  406. {
  407. return false;
  408. }
  409. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  410. {
  411. cmRegularExpression blankLine("^[ \t]*$");
  412. cmRegularExpression comment("^[ \t]*#.*$");
  413. cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t]*$");
  414. cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
  415. cmRegularExpression lastLine("^(.*)\\)[ \t]*$");
  416. // check for black line or comment
  417. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  418. {
  419. return false;
  420. }
  421. // look for a oneline fun(arg arg2)
  422. else if(oneLiner.find(inbuffer))
  423. {
  424. // the arguments are the second match
  425. std::string args = oneLiner.match(2);
  426. name = oneLiner.match(1);
  427. // break up the arguments
  428. cmSystemTools::GetArguments(args, arguments);
  429. return true;
  430. }
  431. // look for a start of a multiline with no trailing ")" fun(arg arg2
  432. else if(multiLine.find(inbuffer))
  433. {
  434. name = multiLine.match(1);
  435. std::string args = multiLine.match(2);
  436. cmSystemTools::GetArguments(args, arguments);
  437. // Read lines until the closing paren is hit
  438. bool done = false;
  439. while(!done)
  440. {
  441. // read lines until the end paren is found
  442. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  443. {
  444. // Check for comment lines and ignore them.
  445. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  446. { continue; }
  447. // Is this the last line?
  448. if(lastLine.find(inbuffer))
  449. {
  450. done = true;
  451. std::string args = lastLine.match(1);
  452. cmSystemTools::GetArguments(args, arguments);
  453. }
  454. else
  455. {
  456. std::string line = inbuffer;
  457. cmSystemTools::GetArguments(line, arguments);
  458. }
  459. }
  460. else
  461. {
  462. cmSystemTools::Error("Parse error in read function missing end )",
  463. inbuffer);
  464. return false;
  465. }
  466. }
  467. return true;
  468. }
  469. else
  470. {
  471. cmSystemTools::Error("Parse error in read function ", inbuffer);
  472. return false;
  473. }
  474. }
  475. return false;
  476. }
  477. void cmSystemTools::GetArguments(std::string& line,
  478. std::vector<std::string>& arguments)
  479. {
  480. // Match a normal argument (not quoted, no spaces).
  481. cmRegularExpression normalArgument("[ \t]*(([^ \t\\]|[\\].)+)[ \t]*");
  482. // Match a quoted argument (surrounded by double quotes, spaces allowed).
  483. cmRegularExpression quotedArgument("[ \t]*(\"([^\"\\]|[\\].)*\")[ \t]*");
  484. bool done = false;
  485. while(!done)
  486. {
  487. std::string arg;
  488. long endpos;
  489. bool foundQuoted = quotedArgument.find(line.c_str());
  490. bool foundNormal = normalArgument.find(line.c_str());
  491. if(foundQuoted && foundNormal)
  492. {
  493. // Both matches were found. Take the earlier one.
  494. // Favor double-quoted version if there is a tie.
  495. if(normalArgument.start(1) < quotedArgument.start(1))
  496. {
  497. arg = normalArgument.match(1);
  498. endpos = normalArgument.end(1);
  499. }
  500. else
  501. {
  502. arg = quotedArgument.match(1);
  503. endpos = quotedArgument.end(1);
  504. // Strip off the double quotes on the ends.
  505. arg = arg.substr(1, arg.length()-2);
  506. }
  507. }
  508. else if (foundQuoted)
  509. {
  510. arg = quotedArgument.match(1);
  511. endpos = quotedArgument.end(1);
  512. // Strip off the double quotes on the ends.
  513. arg = arg.substr(1, arg.length()-2);
  514. }
  515. else if(foundNormal)
  516. {
  517. arg = normalArgument.match(1);
  518. endpos = normalArgument.end(1);
  519. }
  520. else
  521. {
  522. done = true;
  523. }
  524. if(!done)
  525. {
  526. arguments.push_back(cmSystemTools::RemoveEscapes(arg.c_str()));
  527. line = line.substr(endpos, line.length() - endpos);
  528. }
  529. }
  530. }
  531. std::string cmSystemTools::RemoveEscapes(const char* s)
  532. {
  533. std::string result = "";
  534. for(const char* ch = s; *ch; ++ch)
  535. {
  536. if(*ch == '\\')
  537. {
  538. ++ch;
  539. switch (*ch)
  540. {
  541. case '\\': result.insert(result.end(), '\\'); break;
  542. case '"': result.insert(result.end(), '"'); break;
  543. case ' ': result.insert(result.end(), ' '); break;
  544. case 't': result.insert(result.end(), '\t'); break;
  545. case 'n': result.insert(result.end(), '\n'); break;
  546. case 'r': result.insert(result.end(), '\r'); break;
  547. case '0': result.insert(result.end(), '\0'); break;
  548. case '\0':
  549. {
  550. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  551. return result;
  552. }
  553. default:
  554. {
  555. std::string chStr(1, *ch);
  556. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  557. "\nin argument ", s);
  558. }
  559. }
  560. }
  561. else
  562. {
  563. result.insert(result.end(), *ch);
  564. }
  565. }
  566. return result;
  567. }
  568. void cmSystemTools::Error(const char* m1, const char* m2,
  569. const char* m3, const char* m4)
  570. {
  571. std::string message = "CMake Error: ";
  572. if(m1)
  573. {
  574. message += m1;
  575. }
  576. if(m2)
  577. {
  578. message += m2;
  579. }
  580. if(m3)
  581. {
  582. message += m3;
  583. }
  584. if(m4)
  585. {
  586. message += m4;
  587. }
  588. cmSystemTools::s_ErrorOccured = true;
  589. cmSystemTools::Message(message.c_str(),"Error");
  590. }
  591. void cmSystemTools::Message(const char* m1, const char *title)
  592. {
  593. #if defined(_WIN32) && !defined(__CYGWIN__)
  594. static bool disableMessages = false;
  595. if(disableMessages)
  596. {
  597. return;
  598. }
  599. std::string message = m1;
  600. message += "\n\n(Press Cancel to suppress any further messages.)";
  601. if(::MessageBox(0, message.c_str(), title,
  602. MB_OKCANCEL) == IDCANCEL)
  603. {
  604. disableMessages = true;
  605. }
  606. #endif
  607. std::cerr << m1 << std::endl;
  608. }
  609. void cmSystemTools::CopyFileIfDifferent(const char* source,
  610. const char* destination)
  611. {
  612. if(cmSystemTools::FilesDiffer(source, destination))
  613. {
  614. cmSystemTools::cmCopyFile(source, destination);
  615. }
  616. }
  617. bool cmSystemTools::FilesDiffer(const char* source,
  618. const char* destination)
  619. {
  620. struct stat statSource;
  621. if (stat(source, &statSource) != 0)
  622. {
  623. return true;
  624. }
  625. struct stat statDestination;
  626. if (stat(destination, &statDestination) != 0)
  627. {
  628. return true;
  629. }
  630. if(statSource.st_size != statDestination.st_size)
  631. {
  632. return true;
  633. }
  634. std::ifstream finSource(source);
  635. std::ifstream finDestination(destination);
  636. if(!finSource || !finDestination)
  637. {
  638. return true;
  639. }
  640. while(finSource && finDestination)
  641. {
  642. char s, d;
  643. finSource >> s;
  644. finDestination >> d;
  645. if(s != d)
  646. {
  647. return true;
  648. }
  649. }
  650. return false;
  651. }
  652. /**
  653. * Copy a file named by "source" to the file named by "destination". This
  654. * implementation makes correct use of the C++ standard file streams to
  655. * perfectly copy any file with lines of any length (even binary files).
  656. */
  657. void cmSystemTools::cmCopyFile(const char* source,
  658. const char* destination)
  659. {
  660. // Buffer length is only for block size. Any file would still be copied
  661. // correctly if this were as small as 2.
  662. const int buffer_length = 4096;
  663. char buffer[buffer_length];
  664. std::ifstream fin(source,
  665. #ifdef _WIN32
  666. std::ios::binary |
  667. #endif
  668. std::ios::in);
  669. if(!fin)
  670. {
  671. cmSystemTools::Error("CopyFile failed to open input file \"",
  672. source, "\"");
  673. }
  674. std::ofstream fout(destination,
  675. #ifdef _WIN32
  676. std::ios::binary |
  677. #endif
  678. std::ios::out | std::ios::trunc);
  679. if(!fout)
  680. {
  681. cmSystemTools::Error("CopyFile failed to open output file \"",
  682. destination, "\"");
  683. }
  684. while(fin.getline(buffer, buffer_length, '\n') || fin.gcount())
  685. {
  686. unsigned long count = fin.gcount();
  687. if(fin.eof())
  688. {
  689. // Final line, but with no newline.
  690. fout.write(buffer, count);
  691. }
  692. else if(fin.fail())
  693. {
  694. // Part of a line longer than our buffer, clear the fail bit of
  695. // the stream so that we can continue.
  696. fin.clear(fin.rdstate() & ~std::ios::failbit);
  697. fout.write(buffer, count);
  698. }
  699. else
  700. {
  701. // Line on which a newline was encountered. It was read from
  702. // the stream, but not stored.
  703. --count;
  704. fout.write(buffer, count);
  705. fout << '\n';
  706. }
  707. }
  708. }
  709. // return true if the file exists
  710. long int cmSystemTools::ModifiedTime(const char* filename)
  711. {
  712. struct stat fs;
  713. if (stat(filename, &fs) != 0)
  714. {
  715. return 0;
  716. }
  717. else
  718. {
  719. return (long int)fs.st_mtime;
  720. }
  721. }
  722. void cmSystemTools::RemoveFile(const char* source)
  723. {
  724. unlink(source);
  725. }
  726. bool cmSystemTools::IsOn(const char* val)
  727. {
  728. if (!val)
  729. {
  730. return false;
  731. }
  732. std::basic_string<char> v = val;
  733. for(std::basic_string<char>::iterator c = v.begin();
  734. c != v.end(); c++)
  735. {
  736. *c = toupper(*c);
  737. }
  738. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  739. }
  740. bool cmSystemTools::IsOff(const char* val)
  741. {
  742. if (!val || strlen(val) == 0)
  743. {
  744. return true;
  745. }
  746. std::basic_string<char> v = val;
  747. for(std::basic_string<char>::iterator c = v.begin();
  748. c != v.end(); c++)
  749. {
  750. *c = toupper(*c);
  751. }
  752. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  753. v == "N" || v == "NOTFOUND");
  754. }
  755. bool cmSystemTools::RunCommand(const char* command,
  756. std::string& output,
  757. bool verbose)
  758. {
  759. const int BUFFER_SIZE = 4096;
  760. char buffer[BUFFER_SIZE];
  761. #if defined(WIN32) && !defined(__CYGWIN__)
  762. std::string commandToFile = command;
  763. commandToFile += " > ";
  764. std::string tempFile;
  765. tempFile += cmSystemTools::TemporaryFileName();
  766. commandToFile += tempFile;
  767. system(commandToFile.c_str());
  768. std::ifstream fin(tempFile.c_str());
  769. if(!fin)
  770. {
  771. if(verbose)
  772. {
  773. std::string errormsg = "RunCommand produced no output: command: \"";
  774. errormsg += command;
  775. errormsg += "\"";
  776. errormsg += "\nOutput file: ";
  777. errormsg += tempFile;
  778. cmSystemTools::Error(errormsg.c_str());
  779. }
  780. fin.close();
  781. cmSystemTools::RemoveFile(tempFile.c_str());
  782. return false;
  783. }
  784. while(fin)
  785. {
  786. fin.getline(buffer, BUFFER_SIZE);
  787. output += buffer;
  788. }
  789. fin.close();
  790. cmSystemTools::RemoveFile(tempFile.c_str());
  791. return true;
  792. #else
  793. if(verbose)
  794. {
  795. std::cout << "running " << command << std::endl;
  796. }
  797. FILE* cpipe = popen(command, "r");
  798. if(!cpipe)
  799. {
  800. return false;
  801. }
  802. fgets(buffer, BUFFER_SIZE, cpipe);
  803. while(!feof(cpipe))
  804. {
  805. if(verbose)
  806. {
  807. std::cout << buffer << std::flush;
  808. }
  809. output += buffer;
  810. fgets(buffer, BUFFER_SIZE, cpipe);
  811. }
  812. pclose(cpipe);
  813. return true;
  814. #endif
  815. }
  816. #ifdef _MSC_VER
  817. #define tempnam _tempnam
  818. #endif
  819. std::string cmSystemTools::TemporaryFileName()
  820. {
  821. /** \warning in Unix is recomended to use mkstemp( char * )
  822. instead of tempnam in order to avoid the security
  823. risk of setting rights with 0666 */
  824. return tempnam(0, "cmake");
  825. }
  826. /**
  827. * Find the executable with the given name. Searches the given path and then
  828. * the system search path. Returns the full path to the executable if it is
  829. * found. Otherwise, the empty string is returned.
  830. */
  831. std::string cmSystemTools::FindProgram(const char* name,
  832. const std::vector<std::string>& userPaths)
  833. {
  834. // See if the executable exists as written.
  835. if(cmSystemTools::FileExists(name) &&
  836. !cmSystemTools::FileIsDirectory(name))
  837. {
  838. return cmSystemTools::CollapseFullPath(name);
  839. }
  840. std::string tryPath = name;
  841. tryPath += cmSystemTools::GetExecutableExtension();
  842. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  843. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  844. {
  845. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  846. }
  847. // Add the system search path to our path.
  848. std::vector<std::string> path = userPaths;
  849. cmSystemTools::GetPath(path);
  850. for(std::vector<std::string>::const_iterator p = path.begin();
  851. p != path.end(); ++p)
  852. {
  853. tryPath = *p;
  854. tryPath += "/";
  855. tryPath += name;
  856. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  857. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  858. {
  859. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  860. }
  861. tryPath += cmSystemTools::GetExecutableExtension();
  862. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  863. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  864. {
  865. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  866. }
  867. }
  868. // Couldn't find the program.
  869. return "";
  870. }
  871. /**
  872. * Find the library with the given name. Searches the given path and then
  873. * the system search path. Returns the full path to the library if it is
  874. * found. Otherwise, the empty string is returned.
  875. */
  876. std::string cmSystemTools::FindLibrary(const char* name,
  877. const std::vector<std::string>& userPaths)
  878. {
  879. // See if the executable exists as written.
  880. if(cmSystemTools::FileExists(name))
  881. {
  882. return cmSystemTools::CollapseFullPath(name);
  883. }
  884. // Add the system search path to our path.
  885. std::vector<std::string> path = userPaths;
  886. cmSystemTools::GetPath(path);
  887. std::string tryPath;
  888. for(std::vector<std::string>::const_iterator p = path.begin();
  889. p != path.end(); ++p)
  890. {
  891. #if defined(_WIN32) && !defined(__CYGWIN__)
  892. tryPath = *p;
  893. tryPath += "/";
  894. tryPath += name;
  895. tryPath += ".lib";
  896. if(cmSystemTools::FileExists(tryPath.c_str()))
  897. {
  898. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  899. }
  900. #else
  901. tryPath = *p;
  902. tryPath += "/lib";
  903. tryPath += name;
  904. tryPath += ".so";
  905. if(cmSystemTools::FileExists(tryPath.c_str()))
  906. {
  907. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  908. }
  909. tryPath = *p;
  910. tryPath += "/lib";
  911. tryPath += name;
  912. tryPath += ".a";
  913. if(cmSystemTools::FileExists(tryPath.c_str()))
  914. {
  915. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  916. }
  917. tryPath = *p;
  918. tryPath += "/lib";
  919. tryPath += name;
  920. tryPath += ".sl";
  921. if(cmSystemTools::FileExists(tryPath.c_str()))
  922. {
  923. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  924. }
  925. #endif
  926. }
  927. // Couldn't find the library.
  928. return "";
  929. }
  930. bool cmSystemTools::FileIsDirectory(const char* name)
  931. {
  932. struct stat fs;
  933. if(stat(name, &fs) == 0)
  934. {
  935. #if _WIN32
  936. return ((fs.st_mode & _S_IFDIR) != 0);
  937. #else
  938. return S_ISDIR(fs.st_mode);
  939. #endif
  940. }
  941. else
  942. {
  943. return false;
  944. }
  945. }
  946. int cmSystemTools::ChangeDirectory(const char *dir)
  947. {
  948. return Chdir(dir);
  949. }
  950. std::string cmSystemTools::GetCurrentWorkingDirectory()
  951. {
  952. char buf[2048];
  953. std::string path = Getcwd(buf, 2048);
  954. return path;
  955. }
  956. /**
  957. * Given the path to a program executable, get the directory part of the path with the
  958. * file stripped off. If there is no directory part, the empty string is returned.
  959. */
  960. std::string cmSystemTools::GetProgramPath(const char* in_name)
  961. {
  962. std::string dir, file;
  963. cmSystemTools::SplitProgramPath(in_name, dir, file);
  964. return dir;
  965. }
  966. /**
  967. * Given the path to a program executable, get the directory part of the path
  968. * with the file stripped off. If there is no directory part, the empty
  969. * string is returned.
  970. */
  971. void cmSystemTools::SplitProgramPath(const char* in_name,
  972. std::string& dir,
  973. std::string& file)
  974. {
  975. dir = in_name;
  976. file = "";
  977. cmSystemTools::ConvertToUnixSlashes(dir);
  978. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  979. {
  980. std::string::size_type slashPos = dir.rfind("/");
  981. if(slashPos != std::string::npos)
  982. {
  983. file = dir.substr(slashPos+1);
  984. dir = dir.substr(0, slashPos);
  985. }
  986. else
  987. {
  988. file = dir;
  989. dir = "";
  990. }
  991. }
  992. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  993. {
  994. std::string oldDir = in_name;
  995. cmSystemTools::ConvertToUnixSlashes(oldDir);
  996. cmSystemTools::Error("Error splitting file name off end of path:\n",
  997. oldDir.c_str(), "\nDirectory not found: ",
  998. dir.c_str());
  999. dir = in_name;
  1000. return;
  1001. }
  1002. }
  1003. /**
  1004. * Given a path to a file or directory, convert it to a full path.
  1005. * This collapses away relative paths. The full path is returned.
  1006. */
  1007. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1008. {
  1009. std::string dir, file;
  1010. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1011. // Ultra-hack warning:
  1012. // This changes to the target directory, saves the working directory,
  1013. // and then changes back to the original working directory.
  1014. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1015. if(dir != "") { Chdir(dir.c_str()); }
  1016. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1017. Chdir(cwd.c_str());
  1018. cmSystemTools::ConvertToUnixSlashes(newDir);
  1019. std::string newPath = newDir+"/"+file;
  1020. return newPath;
  1021. }
  1022. /**
  1023. * Return path of a full filename (no trailing slashes).
  1024. * Warning: returned path is converted to Unix slashes format.
  1025. */
  1026. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1027. {
  1028. std::string fn = filename;
  1029. cmSystemTools::ConvertToUnixSlashes(fn);
  1030. std::string::size_type slash_pos = fn.rfind("/");
  1031. if(slash_pos != std::string::npos)
  1032. {
  1033. return fn.substr(0, slash_pos);
  1034. }
  1035. else
  1036. {
  1037. return "";
  1038. }
  1039. }
  1040. /**
  1041. * Return file name of a full filename (i.e. file name without path).
  1042. */
  1043. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1044. {
  1045. std::string fn = filename;
  1046. cmSystemTools::ConvertToUnixSlashes(fn);
  1047. std::string::size_type slash_pos = fn.rfind("/");
  1048. if(slash_pos != std::string::npos)
  1049. {
  1050. return fn.substr(slash_pos + 1);
  1051. }
  1052. else
  1053. {
  1054. return filename;
  1055. }
  1056. }
  1057. /**
  1058. * Return file extension of a full filename (dot included).
  1059. * Warning: this is the longest extension (for example: .tar.gz)
  1060. */
  1061. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1062. {
  1063. std::string name = cmSystemTools::GetFilenameName(filename);
  1064. std::string::size_type dot_pos = name.find(".");
  1065. if(dot_pos != std::string::npos)
  1066. {
  1067. return name.substr(dot_pos);
  1068. }
  1069. else
  1070. {
  1071. return "";
  1072. }
  1073. }
  1074. /**
  1075. * Return file name without extension of a full filename (i.e. without path).
  1076. * Warning: it considers the longest extension (for example: .tar.gz)
  1077. */
  1078. std::string cmSystemTools::GetFilenameNameWithoutExtension(const std::string& filename)
  1079. {
  1080. std::string name = cmSystemTools::GetFilenameName(filename);
  1081. std::string::size_type dot_pos = name.find(".");
  1082. if(dot_pos != std::string::npos)
  1083. {
  1084. return name.substr(0, dot_pos);
  1085. }
  1086. else
  1087. {
  1088. return name;
  1089. }
  1090. }
  1091. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1092. std::vector<std::string>& files)
  1093. {
  1094. cmDirectory d;
  1095. cmRegularExpression reg(regexp);
  1096. if (d.Load(directory))
  1097. {
  1098. int i, numf;
  1099. numf = d.GetNumberOfFiles();
  1100. for (i = 0; i < numf; i++)
  1101. {
  1102. std::string fname = d.GetFile(i);
  1103. if (reg.find(fname))
  1104. {
  1105. files.push_back(fname);
  1106. }
  1107. }
  1108. }
  1109. }