cmSystemTools.cxx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. #if defined(_MSC_VER) || defined(__BORLANDC__)
  39. #include <windows.h>
  40. #include <direct.h>
  41. #define _unlink unlink
  42. inline int Mkdir(const char* dir)
  43. {
  44. return _mkdir(dir);
  45. }
  46. inline const char* Getcwd(char* buf, unsigned int len)
  47. {
  48. return _getcwd(buf, len);
  49. }
  50. inline int Chdir(const char* dir)
  51. {
  52. return _chdir(dir);
  53. }
  54. #else
  55. #include <sys/types.h>
  56. #include <fcntl.h>
  57. #include <unistd.h>
  58. inline int Mkdir(const char* dir)
  59. {
  60. return mkdir(dir, 00777);
  61. }
  62. inline const char* Getcwd(char* buf, unsigned int len)
  63. {
  64. return getcwd(buf, len);
  65. }
  66. inline int Chdir(const char* dir)
  67. {
  68. return chdir(dir);
  69. }
  70. #endif
  71. bool cmSystemTools::s_ErrorOccured = false;
  72. // adds the elements of the env variable path to the arg passed in
  73. void cmSystemTools::GetPath(std::vector<std::string>& path)
  74. {
  75. #if defined(_WIN32) && !defined(__CYGWIN__)
  76. const char* pathSep = ";";
  77. #else
  78. const char* pathSep = ":";
  79. #endif
  80. std::string pathEnv = getenv("PATH");
  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)
  105. return ".exe";
  106. #else
  107. return "";
  108. #endif
  109. }
  110. bool cmSystemTools::MakeDirectory(const char* path)
  111. {
  112. std::string dir = path;
  113. // replace all of the \ with /
  114. size_t pos = 0;
  115. while((pos = dir.find('\\', pos)) != std::string::npos)
  116. {
  117. dir[pos] = '/';
  118. pos++;
  119. }
  120. pos = dir.find(':');
  121. if(pos == std::string::npos)
  122. {
  123. pos = 0;
  124. }
  125. while((pos = dir.find('/', pos)) != std::string::npos)
  126. {
  127. std::string topdir = dir.substr(0, pos);
  128. Mkdir(topdir.c_str());
  129. pos++;
  130. }
  131. if(Mkdir(path) != 0)
  132. {
  133. // if it is some other error besides directory exists
  134. // then return false
  135. if(errno != EEXIST)
  136. {
  137. return false;
  138. }
  139. }
  140. return true;
  141. }
  142. // replace replace with with as many times as it shows up in source.
  143. // write the result into source.
  144. void cmSystemTools::ReplaceString(std::string& source,
  145. const char* replace,
  146. const char* with)
  147. {
  148. int lengthReplace = strlen(replace);
  149. std::string rest;
  150. size_t start = source.find(replace);
  151. while(start != std::string::npos)
  152. {
  153. rest = source.substr(start+lengthReplace);
  154. source = source.substr(0, start);
  155. source += with;
  156. source += rest;
  157. start = source.find(replace, start + lengthReplace );
  158. }
  159. }
  160. std::string cmSystemTools::EscapeSpaces(const char* str)
  161. {
  162. #if defined(_WIN32) && !defined(__CYGWIN__)
  163. std::string result = str;
  164. return "\""+result+"\"";
  165. #else
  166. std::string result = "";
  167. for(const char* ch = str; *ch != '\0'; ++ch)
  168. {
  169. if(*ch == ' ')
  170. {
  171. result += '\\';
  172. }
  173. result += *ch;
  174. }
  175. return result;
  176. #endif
  177. }
  178. // return true if the file exists
  179. bool cmSystemTools::FileExists(const char* filename)
  180. {
  181. struct stat fs;
  182. if (stat(filename, &fs) != 0)
  183. {
  184. return false;
  185. }
  186. else
  187. {
  188. return true;
  189. }
  190. }
  191. // convert windows slashes to unix slashes \ with /
  192. void cmSystemTools::ConvertToUnixSlashes(std::string& path)
  193. {
  194. std::string::size_type pos = path.find('\\');
  195. while(pos != std::string::npos)
  196. {
  197. path[pos] = '/';
  198. pos = path.find('\\');
  199. }
  200. // remove any trailing slash
  201. if(path[path.size()-1] == '/')
  202. {
  203. path = path.substr(0, path.size()-1);
  204. }
  205. }
  206. int cmSystemTools::Grep(const char* dir, const char* file,
  207. const char* expression)
  208. {
  209. std::string path = dir;
  210. path += "/";
  211. path += file;
  212. std::ifstream fin(path.c_str());
  213. char buffer[2056];
  214. int count = 0;
  215. cmRegularExpression reg(expression);
  216. while(fin)
  217. {
  218. fin.getline(buffer, sizeof(buffer));
  219. count += reg.find(buffer);
  220. }
  221. return count;
  222. }
  223. void cmSystemTools::ConvertCygwinPath(std::string& pathname)
  224. {
  225. if(pathname.find("/cygdrive/") != std::string::npos)
  226. {
  227. std::string cygStuff = pathname.substr(0, 11);
  228. std::string replace;
  229. replace += cygStuff.at(10);
  230. replace += ":";
  231. cmSystemTools::ReplaceString(pathname, cygStuff.c_str(), replace.c_str());
  232. }
  233. }
  234. bool cmSystemTools::ParseFunction(std::ifstream& fin,
  235. std::string& name,
  236. std::vector<std::string>& arguments)
  237. {
  238. name = "";
  239. arguments = std::vector<std::string>();
  240. const int BUFFER_SIZE = 4096;
  241. char inbuffer[BUFFER_SIZE];
  242. if(!fin)
  243. {
  244. return false;
  245. }
  246. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  247. {
  248. cmRegularExpression blankLine("^[ \t]*$");
  249. cmRegularExpression comment("^[ \t]*#.*$");
  250. cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t]*$");
  251. cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
  252. cmRegularExpression lastLine("^(.*)\\)[ \t]*$");
  253. // check for black line or comment
  254. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  255. {
  256. return false;
  257. }
  258. // look for a oneline fun(arg arg2)
  259. else if(oneLiner.find(inbuffer))
  260. {
  261. // the arguments are the second match
  262. std::string args = oneLiner.match(2);
  263. name = oneLiner.match(1);
  264. // break up the arguments
  265. cmSystemTools::GetArguments(args, arguments);
  266. return true;
  267. }
  268. // look for a start of a multiline with no trailing ")" fun(arg arg2
  269. else if(multiLine.find(inbuffer))
  270. {
  271. name = multiLine.match(1);
  272. std::string args = multiLine.match(2);
  273. cmSystemTools::GetArguments(args, arguments);
  274. // Read lines until the closing paren is hit
  275. bool done = false;
  276. while(!done)
  277. {
  278. // read lines until the end paren is found
  279. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  280. {
  281. // Check for comment lines and ignore them.
  282. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  283. { continue; }
  284. // Is this the last line?
  285. if(lastLine.find(inbuffer))
  286. {
  287. done = true;
  288. std::string args = lastLine.match(1);
  289. cmSystemTools::GetArguments(args, arguments);
  290. }
  291. else
  292. {
  293. std::string line = inbuffer;
  294. cmSystemTools::GetArguments(line, arguments);
  295. }
  296. }
  297. else
  298. {
  299. cmSystemTools::Error("Parse error in read function missing end )",
  300. inbuffer);
  301. return false;
  302. }
  303. }
  304. return true;
  305. }
  306. else
  307. {
  308. cmSystemTools::Error("Parse error in read function ", inbuffer);
  309. return false;
  310. }
  311. }
  312. return false;
  313. }
  314. void cmSystemTools::GetArguments(std::string& line,
  315. std::vector<std::string>& arguments)
  316. {
  317. // Match a normal argument (not quoted, no spaces).
  318. cmRegularExpression normalArgument("[\t ]*([^\" \t]+)[\t ]*");
  319. // Match a quoted argument (surrounded by double quotes, spaces allowed).
  320. cmRegularExpression quotedArgument("[\t ]*(\"[^\"]*\")[\t ]*");
  321. bool done = false;
  322. while(!done)
  323. {
  324. std::string arg;
  325. long endpos;
  326. bool foundQuoted = quotedArgument.find(line.c_str());
  327. bool foundNormal = normalArgument.find(line.c_str());
  328. if(foundQuoted && foundNormal)
  329. {
  330. // Both matches were found. Take the earlier one.
  331. if(normalArgument.start(1) < quotedArgument.start(1))
  332. {
  333. arg = normalArgument.match(1);
  334. endpos = normalArgument.end(1);
  335. }
  336. else
  337. {
  338. arg = quotedArgument.match(1);
  339. endpos = quotedArgument.end(1);
  340. // Strip off the double quotes on the ends.
  341. arg = arg.substr(1, arg.length()-2);
  342. }
  343. }
  344. else if (foundQuoted)
  345. {
  346. arg = quotedArgument.match(1);
  347. endpos = quotedArgument.end(1);
  348. // Strip off the double quotes on the ends.
  349. arg = arg.substr(1, arg.length()-2);
  350. }
  351. else if(foundNormal)
  352. {
  353. arg = normalArgument.match(1);
  354. endpos = normalArgument.end(1);
  355. }
  356. else
  357. {
  358. done = true;
  359. }
  360. if(!done)
  361. {
  362. arguments.push_back(arg);
  363. line = line.substr(endpos, line.length() - endpos);
  364. }
  365. }
  366. }
  367. void cmSystemTools::Error(const char* m1, const char* m2,
  368. const char* m3, const char* m4)
  369. {
  370. std::string message = "CMake Error: ";
  371. if(m1)
  372. {
  373. message += m1;
  374. }
  375. if(m2)
  376. {
  377. message += m2;
  378. }
  379. if(m3)
  380. {
  381. message += m3;
  382. }
  383. if(m4)
  384. {
  385. message += m4;
  386. }
  387. cmSystemTools::s_ErrorOccured = true;
  388. #if defined(_WIN32) && !defined(__CYGWIN__)
  389. ::MessageBox(0, message.c_str(), 0, MB_OK);
  390. std::cerr << message.c_str() << std::endl;
  391. #else
  392. std::cerr << message.c_str() << std::endl;
  393. #endif
  394. }
  395. void cmSystemTools::CopyFileIfDifferent(const char* source,
  396. const char* destination)
  397. {
  398. if(cmSystemTools::FilesDiffer(source, destination))
  399. {
  400. cmSystemTools::cmCopyFile(source, destination);
  401. }
  402. }
  403. bool cmSystemTools::FilesDiffer(const char* source,
  404. const char* destination)
  405. {
  406. struct stat statSource;
  407. if (stat(source, &statSource) != 0)
  408. {
  409. return true;
  410. }
  411. struct stat statDestination;
  412. if (stat(destination, &statDestination) != 0)
  413. {
  414. return true;
  415. }
  416. if(statSource.st_size != statDestination.st_size)
  417. {
  418. return true;
  419. }
  420. std::ifstream finSource(source);
  421. std::ifstream finDestination(destination);
  422. if(!finSource || !finDestination)
  423. {
  424. return true;
  425. }
  426. while(finSource && finDestination)
  427. {
  428. char s, d;
  429. finSource >> s;
  430. finDestination >> d;
  431. if(s != d)
  432. {
  433. return true;
  434. }
  435. }
  436. return false;
  437. }
  438. void cmSystemTools::cmCopyFile(const char* source,
  439. const char* destination)
  440. {
  441. std::ifstream fin(source);
  442. char buff[4096];
  443. std::ofstream fout(destination);
  444. if(!fout )
  445. {
  446. cmSystemTools::Error("CopyFile failed to open input file", source);
  447. }
  448. if(!fin)
  449. {
  450. cmSystemTools::Error("CopyFile failed to open output file", destination);
  451. }
  452. while(fin)
  453. {
  454. fin.getline(buff, 4096);
  455. if(fin)
  456. {
  457. fout << buff << "\n";
  458. }
  459. }
  460. }
  461. // return true if the file exists
  462. long int cmSystemTools::ModifiedTime(const char* filename)
  463. {
  464. struct stat fs;
  465. if (stat(filename, &fs) != 0)
  466. {
  467. return 0;
  468. }
  469. else
  470. {
  471. return (long int)fs.st_mtime;
  472. }
  473. }
  474. void cmSystemTools::RemoveFile(const char* source)
  475. {
  476. unlink(source);
  477. }
  478. bool cmSystemTools::IsOn(const char* val)
  479. {
  480. if (!val)
  481. {
  482. return false;
  483. }
  484. std::basic_string<char> v = val;
  485. for(std::basic_string<char>::iterator c = v.begin();
  486. c != v.end(); c++)
  487. {
  488. *c = toupper(*c);
  489. }
  490. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  491. }
  492. bool cmSystemTools::IsOff(const char* val)
  493. {
  494. if (!val)
  495. {
  496. return true;
  497. }
  498. std::basic_string<char> v = val;
  499. for(std::basic_string<char>::iterator c = v.begin();
  500. c != v.end(); c++)
  501. {
  502. *c = toupper(*c);
  503. }
  504. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  505. v == "N" || v == "NOTFOUND");
  506. }
  507. bool cmSystemTools::RunCommand(const char* command,
  508. std::string& output)
  509. {
  510. std::string commandToFile = command;
  511. commandToFile += " > ";
  512. std::string tempFile;
  513. tempFile += cmSystemTools::TemporaryFileName();
  514. commandToFile += tempFile;
  515. system(commandToFile.c_str());
  516. std::ifstream fin(tempFile.c_str());
  517. if(!fin)
  518. {
  519. cmSystemTools::Error(command, " from RunCommand Faild to create output file",
  520. tempFile.c_str());
  521. return false;
  522. }
  523. const int BUFFER_SIZE = 4096;
  524. char buffer[BUFFER_SIZE];
  525. while(fin)
  526. {
  527. fin.getline(buffer, BUFFER_SIZE);
  528. output += buffer;
  529. }
  530. cmSystemTools::RemoveFile(tempFile.c_str());
  531. return true;
  532. }
  533. #ifdef _MSC_VER
  534. #define tempnam _tempnam
  535. #endif
  536. std::string cmSystemTools::TemporaryFileName()
  537. {
  538. return tempnam(0, "cmake");
  539. }
  540. /**
  541. * Find the executable with the given name. Searches the given path and then
  542. * the system search path. Returns the full path to the executable if it is
  543. * found. Otherwise, the empty string is returned.
  544. */
  545. std::string cmSystemTools::FindProgram(const char* name,
  546. const std::vector<std::string>& userPaths)
  547. {
  548. // See if the executable exists as written.
  549. if(cmSystemTools::FileExists(name))
  550. {
  551. return cmSystemTools::CollapseFullPath(name);
  552. }
  553. // Add the system search path to our path.
  554. std::vector<std::string> path = userPaths;
  555. cmSystemTools::GetPath(path);
  556. for(std::vector<std::string>::const_iterator p = path.begin();
  557. p != path.end(); ++p)
  558. {
  559. std::string tryPath = *p;
  560. tryPath += "/";
  561. tryPath += name;
  562. if(cmSystemTools::FileExists(tryPath.c_str()))
  563. {
  564. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  565. }
  566. tryPath += cmSystemTools::GetExecutableExtension();
  567. if(cmSystemTools::FileExists(tryPath.c_str()))
  568. {
  569. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  570. }
  571. }
  572. // Couldn't find the program.
  573. return "";
  574. }
  575. bool cmSystemTools::FileIsDirectory(const char* name)
  576. {
  577. struct stat fs;
  578. if(stat(name, &fs) == 0)
  579. {
  580. #if _WIN32
  581. return ((fs.st_mode & _S_IFDIR) != 0);
  582. #else
  583. return S_ISDIR(fs.st_mode);
  584. #endif
  585. }
  586. else
  587. {
  588. return false;
  589. }
  590. }
  591. std::string cmSystemTools::GetCurrentWorkingDirectory()
  592. {
  593. char buf[2048];
  594. std::string path = Getcwd(buf, 2048);
  595. return path;
  596. }
  597. /**
  598. * Given the path to a program executable, get the directory part of the path with the
  599. * file stripped off. If there is no directory part, the empty string is returned.
  600. */
  601. std::string cmSystemTools::GetProgramPath(const char* in_name)
  602. {
  603. std::string dir, file;
  604. cmSystemTools::SplitProgramPath(in_name, dir, file);
  605. return dir;
  606. }
  607. /**
  608. * Given the path to a program executable, get the directory part of the path with the
  609. * file stripped off. If there is no directory part, the empty string is returned.
  610. */
  611. void cmSystemTools::SplitProgramPath(const char* in_name,
  612. std::string& dir,
  613. std::string& file)
  614. {
  615. dir = in_name;
  616. file = "";
  617. cmSystemTools::ConvertToUnixSlashes(dir);
  618. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  619. {
  620. std::string::size_type slashPos = dir.rfind("/");
  621. if(slashPos != std::string::npos)
  622. {
  623. file = dir.substr(slashPos+1) + file;
  624. dir = dir.substr(0, slashPos);
  625. }
  626. else
  627. {
  628. file = dir;
  629. dir = "";
  630. }
  631. }
  632. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  633. {
  634. std::string oldDir = in_name;
  635. cmSystemTools::ConvertToUnixSlashes(oldDir);
  636. cmSystemTools::Error("Error splitting file name off end of path:\n",
  637. oldDir.c_str());
  638. dir = in_name;
  639. return;
  640. }
  641. }
  642. /**
  643. * Given a path to a file or directory, convert it to a full path.
  644. * This collapses away relative paths. The full path is returned.
  645. */
  646. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  647. {
  648. std::string dir, file;
  649. cmSystemTools::SplitProgramPath(in_name, dir, file);
  650. // Ultra-hack warning:
  651. // This changes to the target directory, saves the working directory,
  652. // and then changes back to the original working directory.
  653. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  654. if(dir != "") { Chdir(dir.c_str()); }
  655. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  656. Chdir(cwd.c_str());
  657. cmSystemTools::ConvertToUnixSlashes(newDir);
  658. std::string newPath = newDir+"/"+file;
  659. return newPath;
  660. }