cmSystemTools.cxx 26 KB

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