cmSystemTools.cxx 35 KB

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