cmSystemTools.cxx 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  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. cmRegularExpression regEntry("\\[(HKEY[A-Za-z0-9_~\\:\\-\\(\\)\\.\\; ]*)\\]");
  248. // check for black line or comment
  249. while (regEntry.find(source))
  250. {
  251. // the arguments are the second match
  252. std::string key = regEntry.match(1);
  253. std::string val;
  254. if (ReadAValue(val,key.c_str()))
  255. {
  256. std::string reg = "[";
  257. reg += key + "]";
  258. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  259. }
  260. else
  261. {
  262. std::string reg = "[";
  263. reg += key + "]";
  264. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  265. }
  266. }
  267. #endif
  268. }
  269. std::string cmSystemTools::EscapeSpaces(const char* str)
  270. {
  271. #if defined(_WIN32) && !defined(__CYGWIN__)
  272. std::string result = str;
  273. return "\""+result+"\"";
  274. #else
  275. std::string result = "";
  276. for(const char* ch = str; *ch != '\0'; ++ch)
  277. {
  278. if(*ch == ' ')
  279. {
  280. result += '\\';
  281. }
  282. result += *ch;
  283. }
  284. return result;
  285. #endif
  286. }
  287. // return true if the file exists
  288. bool cmSystemTools::FileExists(const char* filename)
  289. {
  290. struct stat fs;
  291. if (stat(filename, &fs) != 0)
  292. {
  293. return false;
  294. }
  295. else
  296. {
  297. return true;
  298. }
  299. }
  300. // Return a capitalized string (i.e the first letter is uppercased, all other
  301. // are lowercased)
  302. std::string cmSystemTools::Capitalized(const std::string& s)
  303. {
  304. std::string n;
  305. n.resize(s.size());
  306. n[0] = toupper(s[0]);
  307. for (size_t i = 1; i < s.size(); i++)
  308. {
  309. n[i] = tolower(s[i]);
  310. }
  311. return n;
  312. }
  313. // convert windows slashes to unix slashes \ with /
  314. void cmSystemTools::ConvertToUnixSlashes(std::string& path)
  315. {
  316. std::string::size_type pos = 0;
  317. while((pos = path.find('\\', pos)) != std::string::npos)
  318. {
  319. path[pos] = '/';
  320. pos++;
  321. }
  322. // remove any trailing slash
  323. if(path[path.size()-1] == '/')
  324. {
  325. path = path.substr(0, path.size()-1);
  326. }
  327. }
  328. // convert windows slashes to unix slashes \ with /
  329. void cmSystemTools::CleanUpWindowsSlashes(std::string& path)
  330. {
  331. std::string::size_type pos = 0;
  332. while((pos = path.find('/', pos)) != std::string::npos)
  333. {
  334. path[pos] = '\\';
  335. pos++;
  336. }
  337. // remove any trailing slash
  338. if(path[path.size()-1] == '\\')
  339. {
  340. path = path.substr(0, path.size()-1);
  341. }
  342. // remove any duplicate // slashes
  343. pos = 0;
  344. while((pos = path.find("\\\\", pos)) != std::string::npos)
  345. {
  346. path.erase(pos, 1);
  347. }
  348. }
  349. int cmSystemTools::Grep(const char* dir, const char* file,
  350. const char* expression)
  351. {
  352. std::string path = dir;
  353. path += "/";
  354. path += file;
  355. std::ifstream fin(path.c_str());
  356. char buffer[2056];
  357. int count = 0;
  358. cmRegularExpression reg(expression);
  359. while(fin)
  360. {
  361. fin.getline(buffer, sizeof(buffer));
  362. count += reg.find(buffer);
  363. }
  364. return count;
  365. }
  366. void cmSystemTools::ConvertCygwinPath(std::string& pathname)
  367. {
  368. if(pathname.find("/cygdrive/") != std::string::npos)
  369. {
  370. std::string cygStuff = pathname.substr(0, 11);
  371. std::string replace;
  372. replace += cygStuff.at(10);
  373. replace += ":";
  374. cmSystemTools::ReplaceString(pathname, cygStuff.c_str(), replace.c_str());
  375. }
  376. }
  377. bool cmSystemTools::ParseFunction(std::ifstream& fin,
  378. std::string& name,
  379. std::vector<std::string>& arguments)
  380. {
  381. name = "";
  382. arguments = std::vector<std::string>();
  383. const int BUFFER_SIZE = 4096;
  384. char inbuffer[BUFFER_SIZE];
  385. if(!fin)
  386. {
  387. return false;
  388. }
  389. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  390. {
  391. cmRegularExpression blankLine("^[ \t]*$");
  392. cmRegularExpression comment("^[ \t]*#.*$");
  393. cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t]*$");
  394. cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
  395. cmRegularExpression lastLine("^(.*)\\)[ \t]*$");
  396. // check for black line or comment
  397. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  398. {
  399. return false;
  400. }
  401. // look for a oneline fun(arg arg2)
  402. else if(oneLiner.find(inbuffer))
  403. {
  404. // the arguments are the second match
  405. std::string args = oneLiner.match(2);
  406. name = oneLiner.match(1);
  407. // break up the arguments
  408. cmSystemTools::GetArguments(args, arguments);
  409. return true;
  410. }
  411. // look for a start of a multiline with no trailing ")" fun(arg arg2
  412. else if(multiLine.find(inbuffer))
  413. {
  414. name = multiLine.match(1);
  415. std::string args = multiLine.match(2);
  416. cmSystemTools::GetArguments(args, arguments);
  417. // Read lines until the closing paren is hit
  418. bool done = false;
  419. while(!done)
  420. {
  421. // read lines until the end paren is found
  422. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  423. {
  424. // Check for comment lines and ignore them.
  425. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  426. { continue; }
  427. // Is this the last line?
  428. if(lastLine.find(inbuffer))
  429. {
  430. done = true;
  431. std::string args = lastLine.match(1);
  432. cmSystemTools::GetArguments(args, arguments);
  433. }
  434. else
  435. {
  436. std::string line = inbuffer;
  437. cmSystemTools::GetArguments(line, arguments);
  438. }
  439. }
  440. else
  441. {
  442. cmSystemTools::Error("Parse error in read function missing end )",
  443. inbuffer);
  444. return false;
  445. }
  446. }
  447. return true;
  448. }
  449. else
  450. {
  451. cmSystemTools::Error("Parse error in read function ", inbuffer);
  452. return false;
  453. }
  454. }
  455. return false;
  456. }
  457. void cmSystemTools::GetArguments(std::string& line,
  458. std::vector<std::string>& arguments)
  459. {
  460. // Match a normal argument (not quoted, no spaces).
  461. cmRegularExpression normalArgument("[\t ]*([^\" \t]+)[\t ]*");
  462. // Match a quoted argument (surrounded by double quotes, spaces allowed).
  463. cmRegularExpression quotedArgument("[\t ]*(\"[^\"]*\")[\t ]*");
  464. bool done = false;
  465. while(!done)
  466. {
  467. std::string arg;
  468. long endpos;
  469. bool foundQuoted = quotedArgument.find(line.c_str());
  470. bool foundNormal = normalArgument.find(line.c_str());
  471. if(foundQuoted && foundNormal)
  472. {
  473. // Both matches were found. Take the earlier one.
  474. if(normalArgument.start(1) < quotedArgument.start(1))
  475. {
  476. arg = normalArgument.match(1);
  477. endpos = normalArgument.end(1);
  478. }
  479. else
  480. {
  481. arg = quotedArgument.match(1);
  482. endpos = quotedArgument.end(1);
  483. // Strip off the double quotes on the ends.
  484. arg = arg.substr(1, arg.length()-2);
  485. }
  486. }
  487. else if (foundQuoted)
  488. {
  489. arg = quotedArgument.match(1);
  490. endpos = quotedArgument.end(1);
  491. // Strip off the double quotes on the ends.
  492. arg = arg.substr(1, arg.length()-2);
  493. }
  494. else if(foundNormal)
  495. {
  496. arg = normalArgument.match(1);
  497. endpos = normalArgument.end(1);
  498. }
  499. else
  500. {
  501. done = true;
  502. }
  503. if(!done)
  504. {
  505. arguments.push_back(arg);
  506. line = line.substr(endpos, line.length() - endpos);
  507. }
  508. }
  509. }
  510. void cmSystemTools::Error(const char* m1, const char* m2,
  511. const char* m3, const char* m4)
  512. {
  513. std::string message = "CMake Error: ";
  514. if(m1)
  515. {
  516. message += m1;
  517. }
  518. if(m2)
  519. {
  520. message += m2;
  521. }
  522. if(m3)
  523. {
  524. message += m3;
  525. }
  526. if(m4)
  527. {
  528. message += m4;
  529. }
  530. cmSystemTools::s_ErrorOccured = true;
  531. cmSystemTools::Message(message.c_str(),"Error");
  532. }
  533. void cmSystemTools::Message(const char* m1, const char *title)
  534. {
  535. #if defined(_WIN32) && !defined(__CYGWIN__)
  536. ::MessageBox(0, m1, title, MB_OK);
  537. #endif
  538. std::cerr << m1 << std::endl;
  539. }
  540. void cmSystemTools::CopyFileIfDifferent(const char* source,
  541. const char* destination)
  542. {
  543. if(cmSystemTools::FilesDiffer(source, destination))
  544. {
  545. cmSystemTools::cmCopyFile(source, destination);
  546. }
  547. }
  548. bool cmSystemTools::FilesDiffer(const char* source,
  549. const char* destination)
  550. {
  551. struct stat statSource;
  552. if (stat(source, &statSource) != 0)
  553. {
  554. return true;
  555. }
  556. struct stat statDestination;
  557. if (stat(destination, &statDestination) != 0)
  558. {
  559. return true;
  560. }
  561. if(statSource.st_size != statDestination.st_size)
  562. {
  563. return true;
  564. }
  565. std::ifstream finSource(source);
  566. std::ifstream finDestination(destination);
  567. if(!finSource || !finDestination)
  568. {
  569. return true;
  570. }
  571. while(finSource && finDestination)
  572. {
  573. char s, d;
  574. finSource >> s;
  575. finDestination >> d;
  576. if(s != d)
  577. {
  578. return true;
  579. }
  580. }
  581. return false;
  582. }
  583. void cmSystemTools::cmCopyFile(const char* source,
  584. const char* destination)
  585. {
  586. std::ifstream fin(source);
  587. char buff[4096];
  588. std::ofstream fout(destination);
  589. if(!fout )
  590. {
  591. cmSystemTools::Error("CopyFile failed to open input file", source);
  592. }
  593. if(!fin)
  594. {
  595. cmSystemTools::Error("CopyFile failed to open output file", destination);
  596. }
  597. while(fin)
  598. {
  599. fin.getline(buff, 4096);
  600. if(fin)
  601. {
  602. fout << buff << "\n";
  603. }
  604. }
  605. }
  606. // return true if the file exists
  607. long int cmSystemTools::ModifiedTime(const char* filename)
  608. {
  609. struct stat fs;
  610. if (stat(filename, &fs) != 0)
  611. {
  612. return 0;
  613. }
  614. else
  615. {
  616. return (long int)fs.st_mtime;
  617. }
  618. }
  619. void cmSystemTools::RemoveFile(const char* source)
  620. {
  621. unlink(source);
  622. }
  623. bool cmSystemTools::IsOn(const char* val)
  624. {
  625. if (!val)
  626. {
  627. return false;
  628. }
  629. std::basic_string<char> v = val;
  630. for(std::basic_string<char>::iterator c = v.begin();
  631. c != v.end(); c++)
  632. {
  633. *c = toupper(*c);
  634. }
  635. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  636. }
  637. bool cmSystemTools::IsOff(const char* val)
  638. {
  639. if (!val)
  640. {
  641. return true;
  642. }
  643. std::basic_string<char> v = val;
  644. for(std::basic_string<char>::iterator c = v.begin();
  645. c != v.end(); c++)
  646. {
  647. *c = toupper(*c);
  648. }
  649. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  650. v == "N" || v == "NOTFOUND");
  651. }
  652. bool cmSystemTools::RunCommand(const char* command,
  653. std::string& output)
  654. {
  655. const int BUFFER_SIZE = 4096;
  656. char buffer[BUFFER_SIZE];
  657. #if defined(WIN32) && !defined(__CYGWIN__)
  658. std::string commandToFile = command;
  659. commandToFile += " > ";
  660. std::string tempFile;
  661. tempFile += cmSystemTools::TemporaryFileName();
  662. commandToFile += tempFile;
  663. system(commandToFile.c_str());
  664. std::ifstream fin(tempFile.c_str());
  665. if(!fin)
  666. {
  667. cmSystemTools::Error(command, " from RunCommand Faild to create output file",
  668. tempFile.c_str());
  669. return false;
  670. }
  671. while(fin)
  672. {
  673. fin.getline(buffer, BUFFER_SIZE);
  674. output += buffer;
  675. }
  676. cmSystemTools::RemoveFile(tempFile.c_str());
  677. return true;
  678. #else
  679. std::cout << "runing " << command << std::endl;
  680. FILE* cpipe = popen(command, "r");
  681. if(!cpipe)
  682. {
  683. return false;
  684. }
  685. fgets(buffer, BUFFER_SIZE, cpipe);
  686. while(!feof(cpipe))
  687. {
  688. std::cout << buffer << std::flush;
  689. output += buffer;
  690. fgets(buffer, BUFFER_SIZE, cpipe);
  691. }
  692. fclose(cpipe);
  693. return true;
  694. #endif
  695. }
  696. #ifdef _MSC_VER
  697. #define tempnam _tempnam
  698. #endif
  699. std::string cmSystemTools::TemporaryFileName()
  700. {
  701. return tempnam(0, "cmake");
  702. }
  703. /**
  704. * Find the executable with the given name. Searches the given path and then
  705. * the system search path. Returns the full path to the executable if it is
  706. * found. Otherwise, the empty string is returned.
  707. */
  708. std::string cmSystemTools::FindProgram(const char* name,
  709. const std::vector<std::string>& userPaths)
  710. {
  711. // See if the executable exists as written.
  712. if(cmSystemTools::FileExists(name))
  713. {
  714. return cmSystemTools::CollapseFullPath(name);
  715. }
  716. std::string tryPath = name;
  717. tryPath += cmSystemTools::GetExecutableExtension();
  718. if(cmSystemTools::FileExists(tryPath.c_str()))
  719. {
  720. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  721. }
  722. // Add the system search path to our path.
  723. std::vector<std::string> path = userPaths;
  724. cmSystemTools::GetPath(path);
  725. for(std::vector<std::string>::const_iterator p = path.begin();
  726. p != path.end(); ++p)
  727. {
  728. tryPath = *p;
  729. tryPath += "/";
  730. tryPath += name;
  731. if(cmSystemTools::FileExists(tryPath.c_str()))
  732. {
  733. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  734. }
  735. tryPath += cmSystemTools::GetExecutableExtension();
  736. if(cmSystemTools::FileExists(tryPath.c_str()))
  737. {
  738. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  739. }
  740. }
  741. // Couldn't find the program.
  742. return "";
  743. }
  744. /**
  745. * Find the library with the given name. Searches the given path and then
  746. * the system search path. Returns the full path to the library if it is
  747. * found. Otherwise, the empty string is returned.
  748. */
  749. std::string cmSystemTools::FindLibrary(const char* name,
  750. const std::vector<std::string>& userPaths)
  751. {
  752. // See if the executable exists as written.
  753. if(cmSystemTools::FileExists(name))
  754. {
  755. return cmSystemTools::CollapseFullPath(name);
  756. }
  757. // Add the system search path to our path.
  758. std::vector<std::string> path = userPaths;
  759. cmSystemTools::GetPath(path);
  760. std::string tryPath;
  761. for(std::vector<std::string>::const_iterator p = path.begin();
  762. p != path.end(); ++p)
  763. {
  764. tryPath = *p;
  765. tryPath += "/";
  766. tryPath += name;
  767. tryPath += ".lib";
  768. if(cmSystemTools::FileExists(tryPath.c_str()))
  769. {
  770. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  771. }
  772. tryPath = *p;
  773. tryPath += "/lib";
  774. tryPath += name;
  775. tryPath += ".so";
  776. if(cmSystemTools::FileExists(tryPath.c_str()))
  777. {
  778. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  779. }
  780. tryPath = *p;
  781. tryPath += "/lib";
  782. tryPath += name;
  783. tryPath += ".a";
  784. if(cmSystemTools::FileExists(tryPath.c_str()))
  785. {
  786. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  787. }
  788. tryPath = *p;
  789. tryPath += "/lib";
  790. tryPath += name;
  791. tryPath += ".sl";
  792. if(cmSystemTools::FileExists(tryPath.c_str()))
  793. {
  794. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  795. }
  796. }
  797. // Couldn't find the library.
  798. return "";
  799. }
  800. bool cmSystemTools::FileIsDirectory(const char* name)
  801. {
  802. struct stat fs;
  803. if(stat(name, &fs) == 0)
  804. {
  805. #if _WIN32
  806. return ((fs.st_mode & _S_IFDIR) != 0);
  807. #else
  808. return S_ISDIR(fs.st_mode);
  809. #endif
  810. }
  811. else
  812. {
  813. return false;
  814. }
  815. }
  816. std::string cmSystemTools::GetCurrentWorkingDirectory()
  817. {
  818. char buf[2048];
  819. std::string path = Getcwd(buf, 2048);
  820. return path;
  821. }
  822. /**
  823. * Given the path to a program executable, get the directory part of the path with the
  824. * file stripped off. If there is no directory part, the empty string is returned.
  825. */
  826. std::string cmSystemTools::GetProgramPath(const char* in_name)
  827. {
  828. std::string dir, file;
  829. cmSystemTools::SplitProgramPath(in_name, dir, file);
  830. return dir;
  831. }
  832. /**
  833. * Given the path to a program executable, get the directory part of the path
  834. * with the file stripped off. If there is no directory part, the empty
  835. * string is returned.
  836. */
  837. void cmSystemTools::SplitProgramPath(const char* in_name,
  838. std::string& dir,
  839. std::string& file)
  840. {
  841. dir = in_name;
  842. file = "";
  843. cmSystemTools::ConvertToUnixSlashes(dir);
  844. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  845. {
  846. std::string::size_type slashPos = dir.rfind("/");
  847. if(slashPos != std::string::npos)
  848. {
  849. file = dir.substr(slashPos+1);
  850. dir = dir.substr(0, slashPos);
  851. }
  852. else
  853. {
  854. file = dir;
  855. dir = "";
  856. }
  857. }
  858. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  859. {
  860. std::string oldDir = in_name;
  861. cmSystemTools::ConvertToUnixSlashes(oldDir);
  862. cmSystemTools::Error("Error splitting file name off end of path:\n",
  863. oldDir.c_str(), "\nDirectory not found: ",
  864. dir.c_str());
  865. dir = in_name;
  866. return;
  867. }
  868. }
  869. /**
  870. * Given a path to a file or directory, convert it to a full path.
  871. * This collapses away relative paths. The full path is returned.
  872. */
  873. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  874. {
  875. std::string dir, file;
  876. cmSystemTools::SplitProgramPath(in_name, dir, file);
  877. // Ultra-hack warning:
  878. // This changes to the target directory, saves the working directory,
  879. // and then changes back to the original working directory.
  880. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  881. if(dir != "") { Chdir(dir.c_str()); }
  882. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  883. Chdir(cwd.c_str());
  884. cmSystemTools::ConvertToUnixSlashes(newDir);
  885. std::string newPath = newDir+"/"+file;
  886. return newPath;
  887. }
  888. /**
  889. * Return path of a full filename (no trailing slashes).
  890. * Warning: returned path is converted to Unix slashes format.
  891. */
  892. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  893. {
  894. std::string fn = filename;
  895. cmSystemTools::ConvertToUnixSlashes(fn);
  896. std::string::size_type slash_pos = fn.rfind("/");
  897. if(slash_pos != std::string::npos)
  898. {
  899. return fn.substr(0, slash_pos);
  900. }
  901. else
  902. {
  903. return "";
  904. }
  905. }
  906. /**
  907. * Return file name of a full filename (i.e. file name without path).
  908. */
  909. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  910. {
  911. std::string fn = filename;
  912. cmSystemTools::ConvertToUnixSlashes(fn);
  913. std::string::size_type slash_pos = fn.rfind("/");
  914. if(slash_pos != std::string::npos)
  915. {
  916. return fn.substr(slash_pos + 1);
  917. }
  918. else
  919. {
  920. return filename;
  921. }
  922. }
  923. /**
  924. * Return file extension of a full filename (dot included).
  925. * Warning: this is the longest extension (for example: .tar.gz)
  926. */
  927. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  928. {
  929. std::string name = cmSystemTools::GetFilenameName(filename);
  930. std::string::size_type dot_pos = name.find(".");
  931. if(dot_pos != std::string::npos)
  932. {
  933. return name.substr(dot_pos);
  934. }
  935. else
  936. {
  937. return "";
  938. }
  939. }
  940. /**
  941. * Return file name without extension of a full filename (i.e. without path).
  942. * Warning: it considers the longest extension (for example: .tar.gz)
  943. */
  944. std::string cmSystemTools::GetFilenameNameWithoutExtension(const std::string& filename)
  945. {
  946. std::string name = cmSystemTools::GetFilenameName(filename);
  947. std::string::size_type dot_pos = name.find(".");
  948. if(dot_pos != std::string::npos)
  949. {
  950. return name.substr(0, dot_pos);
  951. }
  952. else
  953. {
  954. return name;
  955. }
  956. }