cmSystemTools.cxx 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  1. /*=========================================================================
  2. Program: Insight Segmentation & Registration Toolkit
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2002 Insight Consortium. All rights reserved.
  8. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
  9. This software is distributed WITHOUT ANY WARRANTY; without even
  10. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  11. PURPOSE. See the above copyright notices for more information.
  12. =========================================================================*/
  13. #include "cmSystemTools.h"
  14. #include "errno.h"
  15. #include "stdio.h"
  16. #include <sys/stat.h>
  17. #include "cmRegularExpression.h"
  18. #include <ctype.h>
  19. #include "cmDirectory.h"
  20. // support for realpath call
  21. #ifndef _WIN32
  22. #include <limits.h>
  23. #include <stdlib.h>
  24. #include <sys/param.h>
  25. #include <sys/wait.h>
  26. #endif
  27. #if defined(_MSC_VER) || defined(__BORLANDC__)
  28. #include <string.h>
  29. #include <windows.h>
  30. #include <direct.h>
  31. #define _unlink unlink
  32. inline int Mkdir(const char* dir)
  33. {
  34. return _mkdir(dir);
  35. }
  36. inline const char* Getcwd(char* buf, unsigned int len)
  37. {
  38. return _getcwd(buf, len);
  39. }
  40. inline int Chdir(const char* dir)
  41. {
  42. #if defined(__BORLANDC__)
  43. return chdir(dir);
  44. #else
  45. return _chdir(dir);
  46. #endif
  47. }
  48. #else
  49. #include <sys/types.h>
  50. #include <fcntl.h>
  51. #include <unistd.h>
  52. inline int Mkdir(const char* dir)
  53. {
  54. return mkdir(dir, 00777);
  55. }
  56. inline const char* Getcwd(char* buf, unsigned int len)
  57. {
  58. return getcwd(buf, len);
  59. }
  60. inline int Chdir(const char* dir)
  61. {
  62. return chdir(dir);
  63. }
  64. #endif
  65. bool cmSystemTools::s_DisableRunCommandOutput = false;
  66. bool cmSystemTools::s_ErrorOccured = false;
  67. bool cmSystemTools::s_DisableMessages = false;
  68. void (*cmSystemTools::s_ErrorCallback)(const char*, const char*, bool&);
  69. // adds the elements of the env variable path to the arg passed in
  70. void cmSystemTools::GetPath(std::vector<std::string>& path)
  71. {
  72. #if defined(_WIN32) && !defined(__CYGWIN__)
  73. const char* pathSep = ";";
  74. #else
  75. const char* pathSep = ":";
  76. #endif
  77. std::string pathEnv = getenv("PATH");
  78. // A hack to make the below algorithm work.
  79. if(pathEnv[pathEnv.length()-1] != ':')
  80. {
  81. pathEnv += pathSep;
  82. }
  83. std::string::size_type start =0;
  84. bool done = false;
  85. while(!done)
  86. {
  87. std::string::size_type endpos = pathEnv.find(pathSep, start);
  88. if(endpos != std::string::npos)
  89. {
  90. path.push_back(pathEnv.substr(start, endpos-start));
  91. start = endpos+1;
  92. }
  93. else
  94. {
  95. done = true;
  96. }
  97. }
  98. for(std::vector<std::string>::iterator i = path.begin();
  99. i != path.end(); ++i)
  100. {
  101. cmSystemTools::ConvertToUnixSlashes(*i);
  102. }
  103. }
  104. const char* cmSystemTools::GetExecutableExtension()
  105. {
  106. #if defined(_WIN32) || defined(__CYGWIN__)
  107. return ".exe";
  108. #else
  109. return "";
  110. #endif
  111. }
  112. bool cmSystemTools::MakeDirectory(const char* path)
  113. {
  114. if(cmSystemTools::FileExists(path))
  115. {
  116. return true;
  117. }
  118. std::string dir = path;
  119. if(dir.size() == 0)
  120. {
  121. return false;
  122. }
  123. cmSystemTools::ConvertToUnixSlashes(dir);
  124. std::string::size_type pos = dir.find(':');
  125. if(pos == std::string::npos)
  126. {
  127. pos = 0;
  128. }
  129. std::string topdir;
  130. while((pos = dir.find('/', pos)) != std::string::npos)
  131. {
  132. topdir = dir.substr(0, pos);
  133. Mkdir(topdir.c_str());
  134. pos++;
  135. }
  136. if(dir[dir.size()-1] == '/')
  137. {
  138. topdir = dir.substr(0, dir.size());
  139. }
  140. else
  141. {
  142. topdir = dir;
  143. }
  144. if(Mkdir(topdir.c_str()) != 0)
  145. {
  146. // There is a bug in the Borland Run time library which makes MKDIR
  147. // return EACCES when it should return EEXISTS
  148. // if it is some other error besides directory exists
  149. // then return false
  150. if( (errno != EEXIST)
  151. #ifdef __BORLANDC__
  152. && (errno != EACCES)
  153. #endif
  154. )
  155. {
  156. cmSystemTools::Error("Faild to create directory:", path);
  157. return false;
  158. }
  159. }
  160. return true;
  161. }
  162. // replace replace with with as many times as it shows up in source.
  163. // write the result into source.
  164. void cmSystemTools::ReplaceString(std::string& source,
  165. const char* replace,
  166. const char* with)
  167. {
  168. std::string::size_type lengthReplace = strlen(replace);
  169. std::string::size_type lengthWith = strlen(with);
  170. std::string rest;
  171. std::string::size_type start = source.find(replace);
  172. while(start != std::string::npos)
  173. {
  174. rest = source.substr(start+lengthReplace);
  175. source = source.substr(0, start);
  176. source += with;
  177. source += rest;
  178. start = source.find(replace, start + lengthWith );
  179. }
  180. }
  181. // Read a registry value.
  182. // Example :
  183. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  184. // => will return the data of the "default" value of the key
  185. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  186. // => will return the data of the "Root" value of the key
  187. bool cmSystemTools::ReadRegistryValue(const char *key, std::string &value)
  188. {
  189. #if defined(_WIN32) && !defined(__CYGWIN__)
  190. std::string primary = key;
  191. std::string second;
  192. std::string valuename;
  193. size_t start = primary.find("\\");
  194. if (start == std::string::npos)
  195. {
  196. return false;
  197. }
  198. size_t valuenamepos = primary.find(";");
  199. if (valuenamepos != std::string::npos)
  200. {
  201. valuename = primary.substr(valuenamepos+1);
  202. }
  203. second = primary.substr(start+1, valuenamepos-start-1);
  204. primary = primary.substr(0, start);
  205. HKEY primaryKey;
  206. if (primary == "HKEY_CURRENT_USER")
  207. {
  208. primaryKey = HKEY_CURRENT_USER;
  209. }
  210. if (primary == "HKEY_CURRENT_CONFIG")
  211. {
  212. primaryKey = HKEY_CURRENT_CONFIG;
  213. }
  214. if (primary == "HKEY_CLASSES_ROOT")
  215. {
  216. primaryKey = HKEY_CLASSES_ROOT;
  217. }
  218. if (primary == "HKEY_LOCAL_MACHINE")
  219. {
  220. primaryKey = HKEY_LOCAL_MACHINE;
  221. }
  222. if (primary == "HKEY_USERS")
  223. {
  224. primaryKey = HKEY_USERS;
  225. }
  226. HKEY hKey;
  227. if(RegOpenKeyEx(primaryKey,
  228. second.c_str(),
  229. 0,
  230. KEY_READ,
  231. &hKey) != ERROR_SUCCESS)
  232. {
  233. return false;
  234. }
  235. else
  236. {
  237. DWORD dwType, dwSize;
  238. dwSize = 1023;
  239. char data[1024];
  240. if(RegQueryValueEx(hKey,
  241. (LPTSTR)valuename.c_str(),
  242. NULL,
  243. &dwType,
  244. (BYTE *)data,
  245. &dwSize) == ERROR_SUCCESS)
  246. {
  247. if (dwType == REG_SZ)
  248. {
  249. value = data;
  250. return true;
  251. }
  252. }
  253. }
  254. #endif
  255. return false;
  256. }
  257. // Write a registry value.
  258. // Example :
  259. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  260. // => will set the data of the "default" value of the key
  261. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  262. // => will set the data of the "Root" value of the key
  263. bool cmSystemTools::WriteRegistryValue(const char *key, const char *value)
  264. {
  265. #if defined(_WIN32) && !defined(__CYGWIN__)
  266. std::string primary = key;
  267. std::string second;
  268. std::string valuename;
  269. size_t start = primary.find("\\");
  270. if (start == std::string::npos)
  271. {
  272. return false;
  273. }
  274. size_t valuenamepos = primary.find(";");
  275. if (valuenamepos != std::string::npos)
  276. {
  277. valuename = primary.substr(valuenamepos+1);
  278. }
  279. second = primary.substr(start+1, valuenamepos-start-1);
  280. primary = primary.substr(0, start);
  281. HKEY primaryKey;
  282. if (primary == "HKEY_CURRENT_USER")
  283. {
  284. primaryKey = HKEY_CURRENT_USER;
  285. }
  286. if (primary == "HKEY_CURRENT_CONFIG")
  287. {
  288. primaryKey = HKEY_CURRENT_CONFIG;
  289. }
  290. if (primary == "HKEY_CLASSES_ROOT")
  291. {
  292. primaryKey = HKEY_CLASSES_ROOT;
  293. }
  294. if (primary == "HKEY_LOCAL_MACHINE")
  295. {
  296. primaryKey = HKEY_LOCAL_MACHINE;
  297. }
  298. if (primary == "HKEY_USERS")
  299. {
  300. primaryKey = HKEY_USERS;
  301. }
  302. HKEY hKey;
  303. DWORD dwDummy;
  304. if(RegCreateKeyEx(primaryKey,
  305. second.c_str(),
  306. 0,
  307. "",
  308. REG_OPTION_NON_VOLATILE,
  309. KEY_WRITE,
  310. NULL,
  311. &hKey,
  312. &dwDummy) != ERROR_SUCCESS)
  313. {
  314. return false;
  315. }
  316. if(RegSetValueEx(hKey,
  317. (LPTSTR)valuename.c_str(),
  318. 0,
  319. REG_SZ,
  320. (CONST BYTE *)value,
  321. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  322. {
  323. return true;
  324. }
  325. #endif
  326. return false;
  327. }
  328. // Delete a registry value.
  329. // Example :
  330. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  331. // => will delete the data of the "default" value of the key
  332. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  333. // => will delete the data of the "Root" value of the key
  334. bool cmSystemTools::DeleteRegistryValue(const char *key)
  335. {
  336. #if defined(_WIN32) && !defined(__CYGWIN__)
  337. std::string primary = key;
  338. std::string second;
  339. std::string valuename;
  340. size_t start = primary.find("\\");
  341. if (start == std::string::npos)
  342. {
  343. return false;
  344. }
  345. size_t valuenamepos = primary.find(";");
  346. if (valuenamepos != std::string::npos)
  347. {
  348. valuename = primary.substr(valuenamepos+1);
  349. }
  350. second = primary.substr(start+1, valuenamepos-start-1);
  351. primary = primary.substr(0, start);
  352. HKEY primaryKey;
  353. if (primary == "HKEY_CURRENT_USER")
  354. {
  355. primaryKey = HKEY_CURRENT_USER;
  356. }
  357. if (primary == "HKEY_CURRENT_CONFIG")
  358. {
  359. primaryKey = HKEY_CURRENT_CONFIG;
  360. }
  361. if (primary == "HKEY_CLASSES_ROOT")
  362. {
  363. primaryKey = HKEY_CLASSES_ROOT;
  364. }
  365. if (primary == "HKEY_LOCAL_MACHINE")
  366. {
  367. primaryKey = HKEY_LOCAL_MACHINE;
  368. }
  369. if (primary == "HKEY_USERS")
  370. {
  371. primaryKey = HKEY_USERS;
  372. }
  373. HKEY hKey;
  374. if(RegOpenKeyEx(primaryKey,
  375. second.c_str(),
  376. 0,
  377. KEY_WRITE,
  378. &hKey) != ERROR_SUCCESS)
  379. {
  380. return false;
  381. }
  382. else
  383. {
  384. if(RegDeleteValue(hKey,
  385. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  386. {
  387. return true;
  388. }
  389. }
  390. #endif
  391. return false;
  392. }
  393. // replace replace with with as many times as it shows up in source.
  394. // write the result into source.
  395. void cmSystemTools::ExpandRegistryValues(std::string& source)
  396. {
  397. #if defined(_WIN32) && !defined(__CYGWIN__)
  398. // Regular expression to match anything inside [...] that begins in HKEY.
  399. // Note that there is a special rule for regular expressions to match a
  400. // close square-bracket inside a list delimited by square brackets.
  401. // The "[^]]" part of this expression will match any character except
  402. // a close square-bracket. The ']' character must be the first in the
  403. // list of characters inside the [^...] block of the expression.
  404. cmRegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  405. // check for black line or comment
  406. while (regEntry.find(source))
  407. {
  408. // the arguments are the second match
  409. std::string key = regEntry.match(1);
  410. std::string val;
  411. if (ReadRegistryValue(key.c_str(), val))
  412. {
  413. std::string reg = "[";
  414. reg += key + "]";
  415. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  416. }
  417. else
  418. {
  419. std::string reg = "[";
  420. reg += key + "]";
  421. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  422. }
  423. }
  424. #endif
  425. }
  426. std::string cmSystemTools::EscapeQuotes(const char* str)
  427. {
  428. std::string result = "";
  429. for(const char* ch = str; *ch != '\0'; ++ch)
  430. {
  431. if(*ch == '"')
  432. {
  433. result += '\\';
  434. }
  435. result += *ch;
  436. }
  437. return result;
  438. }
  439. bool cmSystemTools::SameFile(const char* file1, const char* file2)
  440. {
  441. #ifdef _WIN32
  442. HANDLE hFile1, hFile2;
  443. hFile1 = CreateFile( file1,
  444. GENERIC_READ,
  445. FILE_SHARE_READ ,
  446. NULL,
  447. OPEN_EXISTING,
  448. FILE_FLAG_BACKUP_SEMANTICS,
  449. NULL
  450. );
  451. hFile2 = CreateFile( file2,
  452. GENERIC_READ,
  453. FILE_SHARE_READ,
  454. NULL,
  455. OPEN_EXISTING,
  456. FILE_FLAG_BACKUP_SEMANTICS,
  457. NULL
  458. );
  459. if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
  460. {
  461. if(hFile1 != INVALID_HANDLE_VALUE)
  462. {
  463. CloseHandle(hFile1);
  464. }
  465. if(hFile2 != INVALID_HANDLE_VALUE)
  466. {
  467. CloseHandle(hFile2);
  468. }
  469. return false;
  470. }
  471. BY_HANDLE_FILE_INFORMATION fiBuf1;
  472. BY_HANDLE_FILE_INFORMATION fiBuf2;
  473. GetFileInformationByHandle( hFile1, &fiBuf1 );
  474. GetFileInformationByHandle( hFile2, &fiBuf2 );
  475. CloseHandle(hFile1);
  476. CloseHandle(hFile2);
  477. return (fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
  478. fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
  479. #else
  480. struct stat fileStat1, fileStat2;
  481. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  482. {
  483. // see if the files are the same file
  484. // check the device inode and size
  485. if(fileStat2.st_dev == fileStat1.st_dev &&
  486. fileStat2.st_ino == fileStat1.st_ino &&
  487. fileStat2.st_size == fileStat1.st_size
  488. )
  489. {
  490. return true;
  491. }
  492. }
  493. return false;
  494. #endif
  495. }
  496. // return true if the file exists
  497. bool cmSystemTools::FileExists(const char* filename)
  498. {
  499. struct stat fs;
  500. if (stat(filename, &fs) != 0)
  501. {
  502. return false;
  503. }
  504. else
  505. {
  506. return true;
  507. }
  508. }
  509. // Return a capitalized string (i.e the first letter is uppercased, all other
  510. // are lowercased)
  511. std::string cmSystemTools::Capitalized(const std::string& s)
  512. {
  513. std::string n;
  514. n.resize(s.size());
  515. n[0] = toupper(s[0]);
  516. for (size_t i = 1; i < s.size(); i++)
  517. {
  518. n[i] = tolower(s[i]);
  519. }
  520. return n;
  521. }
  522. // Return a lower case string
  523. std::string cmSystemTools::LowerCase(const std::string& s)
  524. {
  525. std::string n;
  526. n.resize(s.size());
  527. for (size_t i = 0; i < s.size(); i++)
  528. {
  529. n[i] = tolower(s[i]);
  530. }
  531. return n;
  532. }
  533. // Return a lower case string
  534. std::string cmSystemTools::UpperCase(const std::string& s)
  535. {
  536. std::string n;
  537. n.resize(s.size());
  538. for (size_t i = 0; i < s.size(); i++)
  539. {
  540. n[i] = toupper(s[i]);
  541. }
  542. return n;
  543. }
  544. // convert windows slashes to unix slashes
  545. void cmSystemTools::ConvertToUnixSlashes(std::string& path)
  546. {
  547. std::string::size_type pos = 0;
  548. while((pos = path.find('\\', pos)) != std::string::npos)
  549. {
  550. path[pos] = '/';
  551. pos++;
  552. }
  553. // remove any trailing slash
  554. if(path.size() && path[path.size()-1] == '/')
  555. {
  556. path = path.substr(0, path.size()-1);
  557. }
  558. // if there is a tilda ~ then replace it with HOME
  559. if(path.find("~") == 0)
  560. {
  561. if (getenv("HOME"))
  562. {
  563. path = std::string(getenv("HOME")) + path.substr(1);
  564. }
  565. }
  566. // if there is a /tmp_mnt in a path get rid of it!
  567. // stupid sgi's
  568. if(path.find("/tmp_mnt") == 0)
  569. {
  570. path = path.substr(8);
  571. }
  572. }
  573. // change // to /, and escape any spaces in the path
  574. std::string cmSystemTools::ConvertToUnixOutputPath(const char* path)
  575. {
  576. std::string ret = path;
  577. // remove // except at the beginning might be a cygwin drive
  578. std::string::size_type pos = 1;
  579. while((pos = ret.find("//", pos)) != std::string::npos)
  580. {
  581. ret.erase(pos, 1);
  582. }
  583. // now escape spaces if there is a space in the path
  584. if(ret.find(" ") != std::string::npos)
  585. {
  586. std::string result = "";
  587. char lastch = 1;
  588. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  589. {
  590. // if it is already escaped then don't try to escape it again
  591. if(*ch == ' ' && lastch != '\\')
  592. {
  593. result += '\\';
  594. }
  595. result += *ch;
  596. lastch = *ch;
  597. }
  598. ret = result;
  599. }
  600. return ret;
  601. }
  602. std::string cmSystemTools::EscapeSpaces(const char* str)
  603. {
  604. #if defined(_WIN32) && !defined(__CYGWIN__)
  605. std::string result;
  606. // if there are spaces
  607. std::string temp = str;
  608. if (temp.find(" ") != std::string::npos &&
  609. temp.find("\"")==std::string::npos)
  610. {
  611. result = "\"";
  612. result += str;
  613. result += "\"";
  614. return result;
  615. }
  616. return str;
  617. #else
  618. std::string result = "";
  619. for(const char* ch = str; *ch != '\0'; ++ch)
  620. {
  621. if(*ch == ' ')
  622. {
  623. result += '\\';
  624. }
  625. result += *ch;
  626. }
  627. return result;
  628. #endif
  629. }
  630. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  631. {
  632. #if defined(_WIN32) && !defined(__CYGWIN__)
  633. return cmSystemTools::ConvertToWindowsOutputPath(path);
  634. #else
  635. return cmSystemTools::ConvertToUnixOutputPath(path);
  636. #endif
  637. }
  638. // remove double slashes not at the start
  639. std::string cmSystemTools::ConvertToWindowsOutputPath(const char* path)
  640. {
  641. std::string ret = path;
  642. std::string::size_type pos = 0;
  643. // first convert all of the slashes
  644. while((pos = ret.find('/', pos)) != std::string::npos)
  645. {
  646. ret[pos] = '\\';
  647. pos++;
  648. }
  649. // check for really small paths
  650. if(ret.size() < 2)
  651. {
  652. return ret;
  653. }
  654. // now clean up a bit and remove double slashes
  655. // Only if it is not the first position in the path which is a network
  656. // path on windows
  657. pos = 1; // start at position 1
  658. while((pos = ret.find("\\\\", pos)) != std::string::npos)
  659. {
  660. ret.erase(pos, 1);
  661. }
  662. // now double quote the path if it has spaces in it
  663. // and is not already double quoted
  664. if(ret.find(" ") != std::string::npos
  665. && ret[0] != '\"')
  666. {
  667. std::string result;
  668. result = "\"" + ret + "\"";
  669. ret = result;
  670. }
  671. return ret;
  672. }
  673. inline void RemoveComments(char* ptr)
  674. {
  675. while(*ptr)
  676. {
  677. if(*ptr == '#')
  678. {
  679. *ptr = 0;
  680. break;
  681. }
  682. ++ptr;
  683. }
  684. }
  685. bool cmSystemTools::ParseFunction(std::ifstream& fin,
  686. std::string& name,
  687. std::vector<std::string>& arguments,
  688. const char* filename,
  689. bool& parseError)
  690. {
  691. parseError = false;
  692. name = "";
  693. arguments = std::vector<std::string>();
  694. const int BUFFER_SIZE = 4096;
  695. char inbuffer[BUFFER_SIZE];
  696. if(!fin)
  697. {
  698. return false;
  699. }
  700. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  701. {
  702. RemoveComments(inbuffer);
  703. cmRegularExpression blankLine("^[ \t\r]*$");
  704. // cmRegularExpression comment("^[ \t]*#.*$");
  705. cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t\r]*$");
  706. cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
  707. cmRegularExpression lastLine("^(.*)\\)[ \t\r]*$");
  708. // check for blank line or comment
  709. if(blankLine.find(inbuffer) )
  710. {
  711. return false;
  712. }
  713. // look for a oneline fun(arg arg2)
  714. else if(oneLiner.find(inbuffer))
  715. {
  716. // the arguments are the second match
  717. std::string args = oneLiner.match(2);
  718. name = oneLiner.match(1);
  719. // break up the arguments
  720. cmSystemTools::GetArguments(args, arguments);
  721. return true;
  722. }
  723. // look for a start of a multiline with no trailing ")" fun(arg arg2
  724. else if(multiLine.find(inbuffer))
  725. {
  726. name = multiLine.match(1);
  727. std::string args = multiLine.match(2);
  728. cmSystemTools::GetArguments(args, arguments);
  729. // Read lines until the closing paren is hit
  730. bool done = false;
  731. while(!done)
  732. {
  733. // read lines until the end paren is found
  734. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  735. {
  736. RemoveComments(inbuffer);
  737. // Check for comment lines and ignore them.
  738. if(blankLine.find(inbuffer))
  739. { continue; }
  740. // Is this the last line?
  741. if(lastLine.find(inbuffer))
  742. {
  743. done = true;
  744. std::string args = lastLine.match(1);
  745. cmSystemTools::GetArguments(args, arguments);
  746. }
  747. else
  748. {
  749. std::string line = inbuffer;
  750. cmSystemTools::GetArguments(line, arguments);
  751. }
  752. }
  753. else
  754. {
  755. parseError = true;
  756. cmSystemTools::Error("Parse error in read function missing end )\nIn File: ",
  757. filename, "\nCurrent line:", inbuffer);
  758. return false;
  759. }
  760. }
  761. return true;
  762. }
  763. else
  764. {
  765. parseError = true;
  766. cmSystemTools::Error("Parse error in read function\nIn file:",
  767. filename, "\nCurrent line:", inbuffer);
  768. return false;
  769. }
  770. }
  771. return false;
  772. }
  773. void cmSystemTools::GetArguments(std::string& line,
  774. std::vector<std::string>& arguments)
  775. {
  776. // Match a normal argument (not quoted, no spaces).
  777. cmRegularExpression normalArgument("[ \t]*(([^ \t\r\\]|[\\].)+)[ \t\r]*");
  778. // Match a quoted argument (surrounded by double quotes, spaces allowed).
  779. cmRegularExpression quotedArgument("[ \t]*(\"([^\"\\]|[\\].)*\")[ \t\r]*");
  780. bool done = false;
  781. while(!done)
  782. {
  783. std::string arg;
  784. std::string::size_type endpos=0;
  785. bool foundQuoted = quotedArgument.find(line.c_str());
  786. bool foundNormal = normalArgument.find(line.c_str());
  787. if(foundQuoted && foundNormal)
  788. {
  789. // Both matches were found. Take the earlier one.
  790. // Favor double-quoted version if there is a tie.
  791. if(normalArgument.start(1) < quotedArgument.start(1))
  792. {
  793. arg = normalArgument.match(1);
  794. endpos = normalArgument.end(1);
  795. }
  796. else
  797. {
  798. arg = quotedArgument.match(1);
  799. endpos = quotedArgument.end(1);
  800. // Strip off the double quotes on the ends.
  801. arg = arg.substr(1, arg.length()-2);
  802. }
  803. }
  804. else if (foundQuoted)
  805. {
  806. arg = quotedArgument.match(1);
  807. endpos = quotedArgument.end(1);
  808. // Strip off the double quotes on the ends.
  809. arg = arg.substr(1, arg.length()-2);
  810. }
  811. else if(foundNormal)
  812. {
  813. arg = normalArgument.match(1);
  814. endpos = normalArgument.end(1);
  815. }
  816. else
  817. {
  818. done = true;
  819. }
  820. if(!done)
  821. {
  822. arguments.push_back(cmSystemTools::RemoveEscapes(arg.c_str()));
  823. line = line.substr(endpos, line.length() - endpos);
  824. }
  825. }
  826. }
  827. std::string cmSystemTools::RemoveEscapes(const char* s)
  828. {
  829. std::string result = "";
  830. for(const char* ch = s; *ch; ++ch)
  831. {
  832. if(*ch == '\\' && *(ch+1) != ';')
  833. {
  834. ++ch;
  835. switch (*ch)
  836. {
  837. case '\\': result.insert(result.end(), '\\'); break;
  838. case '"': result.insert(result.end(), '"'); break;
  839. case ' ': result.insert(result.end(), ' '); break;
  840. case 't': result.insert(result.end(), '\t'); break;
  841. case 'n': result.insert(result.end(), '\n'); break;
  842. case 'r': result.insert(result.end(), '\r'); break;
  843. case '0': result.insert(result.end(), '\0'); break;
  844. case '\0':
  845. {
  846. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  847. return result;
  848. }
  849. default:
  850. {
  851. std::string chStr(1, *ch);
  852. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  853. "\nin argument ", s);
  854. }
  855. }
  856. }
  857. else
  858. {
  859. result.insert(result.end(), *ch);
  860. }
  861. }
  862. return result;
  863. }
  864. void cmSystemTools::Error(const char* m1, const char* m2,
  865. const char* m3, const char* m4)
  866. {
  867. std::string message = "CMake Error: ";
  868. if(m1)
  869. {
  870. message += m1;
  871. }
  872. if(m2)
  873. {
  874. message += m2;
  875. }
  876. if(m3)
  877. {
  878. message += m3;
  879. }
  880. if(m4)
  881. {
  882. message += m4;
  883. }
  884. cmSystemTools::s_ErrorOccured = true;
  885. cmSystemTools::Message(message.c_str(),"Error");
  886. }
  887. void cmSystemTools::SetErrorCallback(ErrorCallback f)
  888. {
  889. s_ErrorCallback = f;
  890. }
  891. void cmSystemTools::Message(const char* m1, const char *title)
  892. {
  893. if(s_DisableMessages)
  894. {
  895. return;
  896. }
  897. if(s_ErrorCallback)
  898. {
  899. (*s_ErrorCallback)(m1, title, s_DisableMessages);
  900. return;
  901. }
  902. else
  903. {
  904. std::cerr << m1 << std::endl;
  905. }
  906. }
  907. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  908. const char* destination)
  909. {
  910. if(cmSystemTools::FilesDiffer(source, destination))
  911. {
  912. cmSystemTools::cmCopyFile(source, destination);
  913. return true;
  914. }
  915. return false;
  916. }
  917. bool cmSystemTools::FilesDiffer(const char* source,
  918. const char* destination)
  919. {
  920. struct stat statSource;
  921. if (stat(source, &statSource) != 0)
  922. {
  923. return true;
  924. }
  925. struct stat statDestination;
  926. if (stat(destination, &statDestination) != 0)
  927. {
  928. return true;
  929. }
  930. if(statSource.st_size != statDestination.st_size)
  931. {
  932. return true;
  933. }
  934. if(statSource.st_size == 0)
  935. {
  936. return false;
  937. }
  938. #if defined(_WIN32) || defined(__CYGWIN__)
  939. std::ifstream finSource(source,
  940. std::ios::binary | std::ios::in);
  941. std::ifstream finDestination(destination,
  942. std::ios::binary | std::ios::in);
  943. #else
  944. std::ifstream finSource(source);
  945. std::ifstream finDestination(destination);
  946. #endif
  947. if(!finSource || !finDestination)
  948. {
  949. return true;
  950. }
  951. char* source_buf = new char[statSource.st_size];
  952. char* dest_buf = new char[statSource.st_size];
  953. finSource.read(source_buf, statSource.st_size);
  954. finDestination.read(dest_buf, statSource.st_size);
  955. if(statSource.st_size != finSource.gcount() ||
  956. statSource.st_size != finDestination.gcount())
  957. {
  958. std::strstream msg;
  959. msg << "FilesDiffer failed to read files (allocated: "
  960. << statSource.st_size << ", read source: " << finSource.gcount()
  961. << ", read dest: " << finDestination.gcount() << std::ends;
  962. cmSystemTools::Error(msg.str());
  963. delete [] msg.str();
  964. delete [] source_buf;
  965. delete [] dest_buf;
  966. return false;
  967. }
  968. int ret = memcmp((const void*)source_buf,
  969. (const void*)dest_buf,
  970. statSource.st_size);
  971. delete [] dest_buf;
  972. delete [] source_buf;
  973. return ret != 0;
  974. }
  975. /**
  976. * Copy a file named by "source" to the file named by "destination".
  977. */
  978. void cmSystemTools::cmCopyFile(const char* source,
  979. const char* destination)
  980. {
  981. const int bufferSize = 4096;
  982. char buffer[bufferSize];
  983. // If destination is a directory, try to create a file with the same
  984. // name as the source in that directory.
  985. std::string new_destination;
  986. if(cmSystemTools::FileExists(destination) &&
  987. cmSystemTools::FileIsDirectory(destination))
  988. {
  989. new_destination = destination;
  990. cmSystemTools::ConvertToUnixSlashes(new_destination);
  991. new_destination += '/';
  992. std::string source_name = source;
  993. new_destination += cmSystemTools::GetFilenameName(source_name);
  994. destination = new_destination.c_str();
  995. }
  996. // Create destination directory
  997. std::string destination_dir = destination;
  998. destination_dir = cmSystemTools::GetFilenamePath(destination_dir);
  999. cmSystemTools::MakeDirectory(destination_dir.c_str());
  1000. // Open files
  1001. #if defined(_WIN32) || defined(__CYGWIN__)
  1002. std::ifstream fin(source,
  1003. std::ios::binary | std::ios::in);
  1004. #else
  1005. std::ifstream fin(source);
  1006. #endif
  1007. if(!fin)
  1008. {
  1009. cmSystemTools::Error("CopyFile failed to open input file \"",
  1010. source, "\"");
  1011. return;
  1012. }
  1013. #if defined(_WIN32) || defined(__CYGWIN__)
  1014. std::ofstream fout(destination,
  1015. std::ios::binary | std::ios::out | std::ios::trunc);
  1016. #else
  1017. std::ofstream fout(destination,
  1018. std::ios::out | std::ios::trunc);
  1019. #endif
  1020. if(!fout)
  1021. {
  1022. cmSystemTools::Error("CopyFile failed to open output file \"",
  1023. destination, "\"");
  1024. return;
  1025. }
  1026. // This copy loop is very sensitive on certain platforms with
  1027. // slightly broken stream libraries (like HPUX). Normally, it is
  1028. // incorrect to not check the error condition on the fin.read()
  1029. // before using the data, but the fin.gcount() will be zero if an
  1030. // error occurred. Therefore, the loop should be safe everywhere.
  1031. while(fin)
  1032. {
  1033. fin.read(buffer, bufferSize);
  1034. if(fin.gcount())
  1035. {
  1036. fout.write(buffer, fin.gcount());
  1037. }
  1038. }
  1039. fin.close();
  1040. fout.close();
  1041. // More checks
  1042. struct stat statSource, statDestination;
  1043. if (stat(source, &statSource) != 0 ||
  1044. stat(destination, &statDestination) != 0)
  1045. {
  1046. cmSystemTools::Error("CopyFile failed to copy files!");
  1047. }
  1048. if (statSource.st_size != statDestination.st_size)
  1049. {
  1050. std::strstream msg;
  1051. msg << "CopyFile failed to copy files (sizes differ, source: "
  1052. << statSource.st_size << " , dest: " << statDestination.st_size
  1053. << std::ends;
  1054. cmSystemTools::Error(msg.str());
  1055. delete [] msg.str();
  1056. }
  1057. }
  1058. // return true if the file exists
  1059. long int cmSystemTools::ModifiedTime(const char* filename)
  1060. {
  1061. struct stat fs;
  1062. if (stat(filename, &fs) != 0)
  1063. {
  1064. return 0;
  1065. }
  1066. else
  1067. {
  1068. return (long int)fs.st_mtime;
  1069. }
  1070. }
  1071. bool cmSystemTools::RemoveFile(const char* source)
  1072. {
  1073. return unlink(source) != 0 ? false : true;
  1074. }
  1075. bool cmSystemTools::IsOn(const char* val)
  1076. {
  1077. if (!val)
  1078. {
  1079. return false;
  1080. }
  1081. std::basic_string<char> v = val;
  1082. for(std::basic_string<char>::iterator c = v.begin();
  1083. c != v.end(); c++)
  1084. {
  1085. *c = toupper(*c);
  1086. }
  1087. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  1088. }
  1089. bool cmSystemTools::IsOff(const char* val)
  1090. {
  1091. if (!val || strlen(val) == 0)
  1092. {
  1093. return true;
  1094. }
  1095. std::basic_string<char> v = val;
  1096. for(std::basic_string<char>::iterator c = v.begin();
  1097. c != v.end(); c++)
  1098. {
  1099. *c = toupper(*c);
  1100. }
  1101. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  1102. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  1103. }
  1104. bool cmSystemTools::RunCommand(const char* command,
  1105. std::string& output,
  1106. const char* dir,
  1107. bool verbose)
  1108. {
  1109. int foo;
  1110. return cmSystemTools::RunCommand(command, output, foo, dir, verbose);
  1111. }
  1112. #if defined(WIN32) && !defined(__CYGWIN__)
  1113. // use this for shell commands like echo and dir
  1114. bool RunCommandViaSystem(const char* command,
  1115. const char* dir,
  1116. std::string& output,
  1117. int& retVal,
  1118. bool verbose)
  1119. {
  1120. const int BUFFER_SIZE = 4096;
  1121. char buffer[BUFFER_SIZE];
  1122. std::string commandInDir;
  1123. if(dir)
  1124. {
  1125. commandInDir = "cd ";
  1126. commandInDir += dir;
  1127. commandInDir += " && ";
  1128. commandInDir += command;
  1129. }
  1130. else
  1131. {
  1132. commandInDir = command;
  1133. }
  1134. command = commandInDir.c_str();
  1135. std::string commandToFile = command;
  1136. commandToFile += " > ";
  1137. std::string tempFile;
  1138. tempFile += _tempnam(0, "cmake");
  1139. commandToFile += tempFile;
  1140. retVal = system(commandToFile.c_str());
  1141. std::ifstream fin(tempFile.c_str());
  1142. if(!fin)
  1143. {
  1144. if(verbose)
  1145. {
  1146. std::string errormsg = "RunCommand produced no output: command: \"";
  1147. errormsg += command;
  1148. errormsg += "\"";
  1149. errormsg += "\nOutput file: ";
  1150. errormsg += tempFile;
  1151. cmSystemTools::Error(errormsg.c_str());
  1152. }
  1153. fin.close();
  1154. cmSystemTools::RemoveFile(tempFile.c_str());
  1155. return false;
  1156. }
  1157. bool multiLine = false;
  1158. while(fin)
  1159. {
  1160. fin.getline(buffer, BUFFER_SIZE);
  1161. output += buffer;
  1162. if(multiLine)
  1163. {
  1164. output += "\n";
  1165. }
  1166. multiLine = true;
  1167. }
  1168. fin.close();
  1169. cmSystemTools::RemoveFile(tempFile.c_str());
  1170. return true;
  1171. }
  1172. #endif // endif WIN32 not CYGWIN
  1173. // run a command unix uses popen (easy)
  1174. // windows uses system and ShortPath
  1175. bool cmSystemTools::RunCommand(const char* command,
  1176. std::string& output,
  1177. int &retVal,
  1178. const char* dir,
  1179. bool verbose)
  1180. {
  1181. if(s_DisableRunCommandOutput)
  1182. {
  1183. verbose = false;
  1184. }
  1185. #if defined(WIN32) && !defined(__CYGWIN__)
  1186. // if the command does not start with a quote, then
  1187. // try to find the program, and if the program can not be
  1188. // found use system to run the command as it must be a built in
  1189. // shell command like echo or dir
  1190. int count = 0;
  1191. if(command[0] == '\"')
  1192. {
  1193. // count the number of quotes
  1194. for(const char* s = command; *s != 0; ++s)
  1195. {
  1196. if(*s == '\"')
  1197. {
  1198. count++;
  1199. if(count > 2)
  1200. {
  1201. break;
  1202. }
  1203. }
  1204. }
  1205. // if there are more than two double quotes use
  1206. // GetShortPathName, the cmd.exe program in windows which
  1207. // is used by system fails to execute if there are more than
  1208. // one set of quotes in the arguments
  1209. if(count > 2)
  1210. {
  1211. cmRegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  1212. if(quoted.find(command))
  1213. {
  1214. std::string shortCmd;
  1215. std::string cmd = quoted.match(1);
  1216. std::string args = quoted.match(2);
  1217. if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  1218. {
  1219. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  1220. return false;
  1221. }
  1222. shortCmd += " ";
  1223. shortCmd += args;
  1224. return RunCommandViaSystem(shortCmd.c_str(), dir,
  1225. output, retVal, verbose);
  1226. }
  1227. else
  1228. {
  1229. cmSystemTools::Error("Could not parse command line with quotes ",
  1230. command);
  1231. }
  1232. }
  1233. }
  1234. // if there is only one set of quotes or no quotes then just run the command
  1235. return RunCommandViaSystem(command, dir, output, retVal, verbose);
  1236. #else
  1237. // if only popen worked on windows.....
  1238. std::string commandInDir;
  1239. if(dir)
  1240. {
  1241. commandInDir = "cd ";
  1242. commandInDir += dir;
  1243. commandInDir += " && ";
  1244. commandInDir += command;
  1245. }
  1246. else
  1247. {
  1248. commandInDir = command;
  1249. }
  1250. command = commandInDir.c_str();
  1251. const int BUFFER_SIZE = 4096;
  1252. char buffer[BUFFER_SIZE];
  1253. if(verbose)
  1254. {
  1255. std::cout << "running " << command << std::endl;
  1256. }
  1257. fflush(stdout);
  1258. fflush(stderr);
  1259. FILE* cpipe = popen(command, "r");
  1260. if(!cpipe)
  1261. {
  1262. return false;
  1263. }
  1264. fgets(buffer, BUFFER_SIZE, cpipe);
  1265. while(!feof(cpipe))
  1266. {
  1267. if(verbose)
  1268. {
  1269. std::cout << buffer << std::flush;
  1270. }
  1271. output += buffer;
  1272. fgets(buffer, BUFFER_SIZE, cpipe);
  1273. }
  1274. retVal = pclose(cpipe);
  1275. if (WIFEXITED(retVal))
  1276. {
  1277. retVal = WEXITSTATUS(retVal);
  1278. return true;
  1279. }
  1280. if (WIFSIGNALED(retVal))
  1281. {
  1282. retVal = WTERMSIG(retVal);
  1283. std::strstream error;
  1284. error << "\nProcess terminated due to ";
  1285. switch (retVal)
  1286. {
  1287. #ifdef SIGKILL
  1288. case SIGKILL:
  1289. error << "SIGKILL";
  1290. break;
  1291. #endif
  1292. #ifdef SIGFPE
  1293. case SIGFPE:
  1294. error << "SIGFPE";
  1295. break;
  1296. #endif
  1297. #ifdef SIGBUS
  1298. case SIGBUS:
  1299. error << "SIGBUS";
  1300. break;
  1301. #endif
  1302. #ifdef SIGSEGV
  1303. case SIGSEGV:
  1304. error << "SIGSEGV";
  1305. break;
  1306. #endif
  1307. default:
  1308. error << "signal " << retVal;
  1309. break;
  1310. }
  1311. error << std::ends;
  1312. output += error.str();
  1313. error.rdbuf()->freeze(0);
  1314. }
  1315. return false;
  1316. #endif
  1317. }
  1318. /**
  1319. * Find the file the given name. Searches the given path and then
  1320. * the system search path. Returns the full path to the file if it is
  1321. * found. Otherwise, the empty string is returned.
  1322. */
  1323. std::string cmSystemTools::FindFile(const char* name,
  1324. const std::vector<std::string>& userPaths)
  1325. {
  1326. // Add the system search path to our path.
  1327. std::vector<std::string> path = userPaths;
  1328. cmSystemTools::GetPath(path);
  1329. std::string tryPath;
  1330. for(std::vector<std::string>::const_iterator p = path.begin();
  1331. p != path.end(); ++p)
  1332. {
  1333. tryPath = *p;
  1334. tryPath += "/";
  1335. tryPath += name;
  1336. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1337. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1338. {
  1339. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1340. }
  1341. }
  1342. // Couldn't find the file.
  1343. return "";
  1344. }
  1345. /**
  1346. * Find the executable with the given name. Searches the given path and then
  1347. * the system search path. Returns the full path to the executable if it is
  1348. * found. Otherwise, the empty string is returned.
  1349. */
  1350. std::string cmSystemTools::FindProgram(const char* name,
  1351. const std::vector<std::string>& userPaths,
  1352. bool no_system_path)
  1353. {
  1354. // See if the executable exists as written.
  1355. if(cmSystemTools::FileExists(name) &&
  1356. !cmSystemTools::FileIsDirectory(name))
  1357. {
  1358. return cmSystemTools::CollapseFullPath(name);
  1359. }
  1360. std::string tryPath = name;
  1361. tryPath += cmSystemTools::GetExecutableExtension();
  1362. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1363. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1364. {
  1365. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1366. }
  1367. // Add the system search path to our path.
  1368. std::vector<std::string> path = userPaths;
  1369. if (!no_system_path)
  1370. {
  1371. cmSystemTools::GetPath(path);
  1372. }
  1373. for(std::vector<std::string>::const_iterator p = path.begin();
  1374. p != path.end(); ++p)
  1375. {
  1376. tryPath = *p;
  1377. tryPath += "/";
  1378. tryPath += name;
  1379. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1380. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1381. {
  1382. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1383. }
  1384. #ifdef _WIN32
  1385. tryPath += ".com";
  1386. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1387. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1388. {
  1389. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1390. }
  1391. tryPath = *p;
  1392. tryPath += "/";
  1393. tryPath += name;
  1394. #endif
  1395. tryPath += cmSystemTools::GetExecutableExtension();
  1396. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1397. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1398. {
  1399. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1400. }
  1401. }
  1402. // Couldn't find the program.
  1403. return "";
  1404. }
  1405. /**
  1406. * Find the library with the given name. Searches the given path and then
  1407. * the system search path. Returns the full path to the library if it is
  1408. * found. Otherwise, the empty string is returned.
  1409. */
  1410. std::string cmSystemTools::FindLibrary(const char* name,
  1411. const std::vector<std::string>& userPaths)
  1412. {
  1413. // See if the executable exists as written.
  1414. if(cmSystemTools::FileExists(name))
  1415. {
  1416. return cmSystemTools::CollapseFullPath(name);
  1417. }
  1418. // Add the system search path to our path.
  1419. std::vector<std::string> path = userPaths;
  1420. cmSystemTools::GetPath(path);
  1421. std::string tryPath;
  1422. for(std::vector<std::string>::const_iterator p = path.begin();
  1423. p != path.end(); ++p)
  1424. {
  1425. #if defined(_WIN32) && !defined(__CYGWIN__)
  1426. tryPath = *p;
  1427. tryPath += "/";
  1428. tryPath += name;
  1429. tryPath += ".lib";
  1430. if(cmSystemTools::FileExists(tryPath.c_str()))
  1431. {
  1432. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1433. }
  1434. #else
  1435. tryPath = *p;
  1436. tryPath += "/lib";
  1437. tryPath += name;
  1438. tryPath += ".so";
  1439. if(cmSystemTools::FileExists(tryPath.c_str()))
  1440. {
  1441. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1442. }
  1443. tryPath = *p;
  1444. tryPath += "/lib";
  1445. tryPath += name;
  1446. tryPath += ".a";
  1447. if(cmSystemTools::FileExists(tryPath.c_str()))
  1448. {
  1449. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1450. }
  1451. tryPath = *p;
  1452. tryPath += "/lib";
  1453. tryPath += name;
  1454. tryPath += ".sl";
  1455. if(cmSystemTools::FileExists(tryPath.c_str()))
  1456. {
  1457. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1458. }
  1459. #endif
  1460. }
  1461. // Couldn't find the library.
  1462. return "";
  1463. }
  1464. bool cmSystemTools::FileIsDirectory(const char* name)
  1465. {
  1466. struct stat fs;
  1467. if(stat(name, &fs) == 0)
  1468. {
  1469. #if _WIN32
  1470. return ((fs.st_mode & _S_IFDIR) != 0);
  1471. #else
  1472. return S_ISDIR(fs.st_mode);
  1473. #endif
  1474. }
  1475. else
  1476. {
  1477. return false;
  1478. }
  1479. }
  1480. int cmSystemTools::ChangeDirectory(const char *dir)
  1481. {
  1482. return Chdir(dir);
  1483. }
  1484. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1485. {
  1486. char buf[2048];
  1487. std::string path = Getcwd(buf, 2048);
  1488. return path;
  1489. }
  1490. /**
  1491. * Given the path to a program executable, get the directory part of the path with the
  1492. * file stripped off. If there is no directory part, the empty string is returned.
  1493. */
  1494. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1495. {
  1496. std::string dir, file;
  1497. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1498. return dir;
  1499. }
  1500. /**
  1501. * Given the path to a program executable, get the directory part of the path
  1502. * with the file stripped off. If there is no directory part, the empty
  1503. * string is returned.
  1504. */
  1505. void cmSystemTools::SplitProgramPath(const char* in_name,
  1506. std::string& dir,
  1507. std::string& file)
  1508. {
  1509. dir = in_name;
  1510. file = "";
  1511. cmSystemTools::ConvertToUnixSlashes(dir);
  1512. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1513. {
  1514. std::string::size_type slashPos = dir.rfind("/");
  1515. if(slashPos != std::string::npos)
  1516. {
  1517. file = dir.substr(slashPos+1);
  1518. dir = dir.substr(0, slashPos);
  1519. }
  1520. else
  1521. {
  1522. file = dir;
  1523. dir = "";
  1524. }
  1525. }
  1526. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1527. {
  1528. std::string oldDir = in_name;
  1529. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1530. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1531. oldDir.c_str(), "\nDirectory not found: ",
  1532. dir.c_str());
  1533. dir = in_name;
  1534. return;
  1535. }
  1536. }
  1537. /**
  1538. * Given a path to a file or directory, convert it to a full path.
  1539. * This collapses away relative paths. The full path is returned.
  1540. */
  1541. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1542. {
  1543. std::string dir, file;
  1544. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1545. #ifdef _WIN32
  1546. // Ultra-hack warning:
  1547. // This changes to the target directory, saves the working directory,
  1548. // and then changes back to the original working directory.
  1549. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1550. if(dir != "") { Chdir(dir.c_str()); }
  1551. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1552. Chdir(cwd.c_str());
  1553. cmSystemTools::ConvertToUnixSlashes(newDir);
  1554. std::string newPath = newDir+"/"+file;
  1555. return newPath;
  1556. #else
  1557. # ifdef MAXPATHLEN
  1558. char resolved_name[MAXPATHLEN];
  1559. # else
  1560. # ifdef PATH_MAX
  1561. char resolved_name[PATH_MAX];
  1562. # else
  1563. char resolved_name[5024];
  1564. # endif
  1565. # endif
  1566. if(dir != "")
  1567. {
  1568. realpath(dir.c_str(), resolved_name);
  1569. dir = resolved_name;
  1570. }
  1571. else
  1572. {
  1573. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1574. }
  1575. if(file == "")
  1576. {
  1577. return dir;
  1578. }
  1579. return dir + "/" + file;
  1580. #endif
  1581. }
  1582. /**
  1583. * Return path of a full filename (no trailing slashes).
  1584. * Warning: returned path is converted to Unix slashes format.
  1585. */
  1586. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1587. {
  1588. std::string fn = filename;
  1589. cmSystemTools::ConvertToUnixSlashes(fn);
  1590. std::string::size_type slash_pos = fn.rfind("/");
  1591. if(slash_pos != std::string::npos)
  1592. {
  1593. return fn.substr(0, slash_pos);
  1594. }
  1595. else
  1596. {
  1597. return "";
  1598. }
  1599. }
  1600. /**
  1601. * Return file name of a full filename (i.e. file name without path).
  1602. */
  1603. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1604. {
  1605. std::string fn = filename;
  1606. cmSystemTools::ConvertToUnixSlashes(fn);
  1607. std::string::size_type slash_pos = fn.rfind("/");
  1608. if(slash_pos != std::string::npos)
  1609. {
  1610. return fn.substr(slash_pos + 1);
  1611. }
  1612. else
  1613. {
  1614. return filename;
  1615. }
  1616. }
  1617. /**
  1618. * Return file extension of a full filename (dot included).
  1619. * Warning: this is the longest extension (for example: .tar.gz)
  1620. */
  1621. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1622. {
  1623. std::string name = cmSystemTools::GetFilenameName(filename);
  1624. std::string::size_type dot_pos = name.find(".");
  1625. if(dot_pos != std::string::npos)
  1626. {
  1627. return name.substr(dot_pos);
  1628. }
  1629. else
  1630. {
  1631. return "";
  1632. }
  1633. }
  1634. /**
  1635. * Return file name without extension of a full filename (i.e. without path).
  1636. * Warning: it considers the longest extension (for example: .tar.gz)
  1637. */
  1638. std::string cmSystemTools::GetFilenameNameWithoutExtension(const std::string& filename)
  1639. {
  1640. std::string name = cmSystemTools::GetFilenameName(filename);
  1641. std::string::size_type dot_pos = name.find(".");
  1642. if(dot_pos != std::string::npos)
  1643. {
  1644. return name.substr(0, dot_pos);
  1645. }
  1646. else
  1647. {
  1648. return name;
  1649. }
  1650. }
  1651. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1652. std::vector<std::string>& files)
  1653. {
  1654. cmDirectory d;
  1655. cmRegularExpression reg(regexp);
  1656. if (d.Load(directory))
  1657. {
  1658. size_t numf;
  1659. unsigned int i;
  1660. numf = d.GetNumberOfFiles();
  1661. for (i = 0; i < numf; i++)
  1662. {
  1663. std::string fname = d.GetFile(i);
  1664. if (reg.find(fname))
  1665. {
  1666. files.push_back(fname);
  1667. }
  1668. }
  1669. }
  1670. }
  1671. void cmSystemTools::GlobDirs(const char *fullPath,
  1672. std::vector<std::string>& files)
  1673. {
  1674. std::string path = fullPath;
  1675. std::string::size_type pos = path.find("/*");
  1676. if(pos == std::string::npos)
  1677. {
  1678. files.push_back(fullPath);
  1679. return;
  1680. }
  1681. std::string startPath = path.substr(0, pos);
  1682. std::string finishPath = path.substr(pos+2);
  1683. cmDirectory d;
  1684. if (d.Load(startPath.c_str()))
  1685. {
  1686. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1687. {
  1688. if((std::string(d.GetFile(i)) != ".")
  1689. && (std::string(d.GetFile(i)) != ".."))
  1690. {
  1691. std::string fname = startPath;
  1692. fname +="/";
  1693. fname += d.GetFile(i);
  1694. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1695. {
  1696. fname += finishPath;
  1697. cmSystemTools::GlobDirs(fname.c_str(), files);
  1698. }
  1699. }
  1700. }
  1701. }
  1702. }
  1703. void cmSystemTools::ExpandListArguments(std::vector<std::string> const& arguments,
  1704. std::vector<std::string>& newargs)
  1705. {
  1706. std::vector<std::string>::const_iterator i;
  1707. std::string newarg;
  1708. for(i = arguments.begin();i != arguments.end(); ++i)
  1709. {
  1710. // if there are no ; in the name then just copy the current string
  1711. if(i->find(';') == std::string::npos)
  1712. {
  1713. newargs.push_back(*i);
  1714. }
  1715. else
  1716. {
  1717. std::string::size_type start = 0;
  1718. std::string::size_type endpos = 0;
  1719. const std::string::size_type size = i->size();
  1720. // break up ; separated sections of the string into separate strings
  1721. while(endpos != size)
  1722. {
  1723. endpos = i->find(';', start);
  1724. if(endpos == std::string::npos)
  1725. {
  1726. endpos = i->size();
  1727. }
  1728. else
  1729. {
  1730. // skip right over escaped ; ( \; )
  1731. while((endpos != std::string::npos)
  1732. && (endpos > 0)
  1733. && ((*i)[endpos-1] == '\\') )
  1734. {
  1735. endpos = i->find(';', endpos+1);
  1736. }
  1737. if(endpos == std::string::npos)
  1738. {
  1739. endpos = i->size();
  1740. }
  1741. }
  1742. std::string::size_type len = endpos - start;
  1743. if (len > 0)
  1744. {
  1745. // check for a closing ] after the start position
  1746. if(i->find('[', start) == std::string::npos)
  1747. {
  1748. // if there is no [ in the string then keep it
  1749. newarg = i->substr(start, len);
  1750. }
  1751. else
  1752. {
  1753. int opencount = 0;
  1754. int closecount = 0;
  1755. for(std::string::size_type j = start; j < endpos; ++j)
  1756. {
  1757. if(i->at(j) == '[')
  1758. {
  1759. ++opencount;
  1760. }
  1761. else if (i->at(j) == ']')
  1762. {
  1763. ++closecount;
  1764. }
  1765. }
  1766. if(opencount != closecount)
  1767. {
  1768. // skip this one
  1769. endpos = i->find(';', endpos+1);
  1770. if(endpos == std::string::npos)
  1771. {
  1772. endpos = i->size();
  1773. }
  1774. len = endpos - start;
  1775. }
  1776. newarg = i->substr(start, len);
  1777. }
  1778. std::string::size_type pos = newarg.find("\\;");
  1779. if(pos != std::string::npos)
  1780. {
  1781. newarg.erase(pos, 1);
  1782. }
  1783. newargs.push_back(newarg);
  1784. }
  1785. start = endpos+1;
  1786. }
  1787. }
  1788. }
  1789. }
  1790. bool cmSystemTools::GetShortPath(const char* path, std::string& shortPath)
  1791. {
  1792. #if defined(WIN32) && !defined(__CYGWIN__)
  1793. const int size = int(strlen(path)) +1; // size of return
  1794. char *buffer = new char[size]; // create a buffer
  1795. buffer[0] = 0;
  1796. int ret = GetShortPathName(path, buffer, size);
  1797. if(buffer[0] == 0 || ret > size)
  1798. {
  1799. if(ret < size)
  1800. {
  1801. LPVOID lpMsgBuf;
  1802. FormatMessage(
  1803. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1804. FORMAT_MESSAGE_FROM_SYSTEM |
  1805. FORMAT_MESSAGE_IGNORE_INSERTS,
  1806. NULL,
  1807. GetLastError(),
  1808. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  1809. (LPTSTR) &lpMsgBuf,
  1810. 0,
  1811. NULL
  1812. );
  1813. cmSystemTools::Error((LPCTSTR)lpMsgBuf);
  1814. LocalFree( lpMsgBuf );
  1815. }
  1816. cmSystemTools::Error("Unable to get a short path: ", path);
  1817. return false;
  1818. }
  1819. else
  1820. {
  1821. shortPath = buffer;
  1822. delete [] buffer;
  1823. return true;
  1824. }
  1825. #else
  1826. shortPath = path;
  1827. return true;
  1828. #endif
  1829. }