cmSystemTools.cxx 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  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. bool cmSystemTools::ParseFunction(std::ifstream& fin,
  674. std::string& name,
  675. std::vector<std::string>& arguments,
  676. const char* filename,
  677. bool& parseError)
  678. {
  679. parseError = false;
  680. name = "";
  681. arguments = std::vector<std::string>();
  682. const int BUFFER_SIZE = 4096;
  683. char inbuffer[BUFFER_SIZE];
  684. if(!fin)
  685. {
  686. return false;
  687. }
  688. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  689. {
  690. cmRegularExpression blankLine("^[ \t\r]*$");
  691. cmRegularExpression comment("^[ \t]*#.*$");
  692. cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t\r]*$");
  693. cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
  694. cmRegularExpression lastLine("^(.*)\\)[ \t\r]*$");
  695. // check for black line or comment
  696. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  697. {
  698. return false;
  699. }
  700. // look for a oneline fun(arg arg2)
  701. else if(oneLiner.find(inbuffer))
  702. {
  703. // the arguments are the second match
  704. std::string args = oneLiner.match(2);
  705. name = oneLiner.match(1);
  706. // break up the arguments
  707. cmSystemTools::GetArguments(args, arguments);
  708. return true;
  709. }
  710. // look for a start of a multiline with no trailing ")" fun(arg arg2
  711. else if(multiLine.find(inbuffer))
  712. {
  713. name = multiLine.match(1);
  714. std::string args = multiLine.match(2);
  715. cmSystemTools::GetArguments(args, arguments);
  716. // Read lines until the closing paren is hit
  717. bool done = false;
  718. while(!done)
  719. {
  720. // read lines until the end paren is found
  721. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  722. {
  723. // Check for comment lines and ignore them.
  724. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  725. { continue; }
  726. // Is this the last line?
  727. if(lastLine.find(inbuffer))
  728. {
  729. done = true;
  730. std::string args = lastLine.match(1);
  731. cmSystemTools::GetArguments(args, arguments);
  732. }
  733. else
  734. {
  735. std::string line = inbuffer;
  736. cmSystemTools::GetArguments(line, arguments);
  737. }
  738. }
  739. else
  740. {
  741. parseError = true;
  742. cmSystemTools::Error("Parse error in read function missing end )\nIn File: ",
  743. filename, "\nCurrent line:", inbuffer);
  744. return false;
  745. }
  746. }
  747. return true;
  748. }
  749. else
  750. {
  751. parseError = true;
  752. cmSystemTools::Error("Parse error in read function\nIn file:",
  753. filename, "\nCurrent line:", inbuffer);
  754. return false;
  755. }
  756. }
  757. return false;
  758. }
  759. void cmSystemTools::GetArguments(std::string& line,
  760. std::vector<std::string>& arguments)
  761. {
  762. // Match a normal argument (not quoted, no spaces).
  763. cmRegularExpression normalArgument("[ \t]*(([^ \t\r\\]|[\\].)+)[ \t\r]*");
  764. // Match a quoted argument (surrounded by double quotes, spaces allowed).
  765. cmRegularExpression quotedArgument("[ \t]*(\"([^\"\\]|[\\].)*\")[ \t\r]*");
  766. bool done = false;
  767. while(!done)
  768. {
  769. std::string arg;
  770. std::string::size_type endpos=0;
  771. bool foundQuoted = quotedArgument.find(line.c_str());
  772. bool foundNormal = normalArgument.find(line.c_str());
  773. if(foundQuoted && foundNormal)
  774. {
  775. // Both matches were found. Take the earlier one.
  776. // Favor double-quoted version if there is a tie.
  777. if(normalArgument.start(1) < quotedArgument.start(1))
  778. {
  779. arg = normalArgument.match(1);
  780. endpos = normalArgument.end(1);
  781. }
  782. else
  783. {
  784. arg = quotedArgument.match(1);
  785. endpos = quotedArgument.end(1);
  786. // Strip off the double quotes on the ends.
  787. arg = arg.substr(1, arg.length()-2);
  788. }
  789. }
  790. else if (foundQuoted)
  791. {
  792. arg = quotedArgument.match(1);
  793. endpos = quotedArgument.end(1);
  794. // Strip off the double quotes on the ends.
  795. arg = arg.substr(1, arg.length()-2);
  796. }
  797. else if(foundNormal)
  798. {
  799. arg = normalArgument.match(1);
  800. endpos = normalArgument.end(1);
  801. }
  802. else
  803. {
  804. done = true;
  805. }
  806. if(!done)
  807. {
  808. arguments.push_back(cmSystemTools::RemoveEscapes(arg.c_str()));
  809. line = line.substr(endpos, line.length() - endpos);
  810. }
  811. }
  812. }
  813. std::string cmSystemTools::RemoveEscapes(const char* s)
  814. {
  815. std::string result = "";
  816. for(const char* ch = s; *ch; ++ch)
  817. {
  818. if(*ch == '\\' && *(ch+1) != ';')
  819. {
  820. ++ch;
  821. switch (*ch)
  822. {
  823. case '\\': result.insert(result.end(), '\\'); break;
  824. case '"': result.insert(result.end(), '"'); break;
  825. case ' ': result.insert(result.end(), ' '); break;
  826. case 't': result.insert(result.end(), '\t'); break;
  827. case 'n': result.insert(result.end(), '\n'); break;
  828. case 'r': result.insert(result.end(), '\r'); break;
  829. case '0': result.insert(result.end(), '\0'); break;
  830. case '\0':
  831. {
  832. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  833. return result;
  834. }
  835. default:
  836. {
  837. std::string chStr(1, *ch);
  838. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  839. "\nin argument ", s);
  840. }
  841. }
  842. }
  843. else
  844. {
  845. result.insert(result.end(), *ch);
  846. }
  847. }
  848. return result;
  849. }
  850. void cmSystemTools::Error(const char* m1, const char* m2,
  851. const char* m3, const char* m4)
  852. {
  853. std::string message = "CMake Error: ";
  854. if(m1)
  855. {
  856. message += m1;
  857. }
  858. if(m2)
  859. {
  860. message += m2;
  861. }
  862. if(m3)
  863. {
  864. message += m3;
  865. }
  866. if(m4)
  867. {
  868. message += m4;
  869. }
  870. cmSystemTools::s_ErrorOccured = true;
  871. cmSystemTools::Message(message.c_str(),"Error");
  872. }
  873. void cmSystemTools::SetErrorCallback(ErrorCallback f)
  874. {
  875. s_ErrorCallback = f;
  876. }
  877. void cmSystemTools::Message(const char* m1, const char *title)
  878. {
  879. if(s_DisableMessages)
  880. {
  881. return;
  882. }
  883. if(s_ErrorCallback)
  884. {
  885. (*s_ErrorCallback)(m1, title, s_DisableMessages);
  886. return;
  887. }
  888. else
  889. {
  890. std::cerr << m1 << std::endl;
  891. }
  892. }
  893. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  894. const char* destination)
  895. {
  896. if(cmSystemTools::FilesDiffer(source, destination))
  897. {
  898. cmSystemTools::cmCopyFile(source, destination);
  899. return true;
  900. }
  901. return false;
  902. }
  903. bool cmSystemTools::FilesDiffer(const char* source,
  904. const char* destination)
  905. {
  906. struct stat statSource;
  907. if (stat(source, &statSource) != 0)
  908. {
  909. return true;
  910. }
  911. struct stat statDestination;
  912. if (stat(destination, &statDestination) != 0)
  913. {
  914. return true;
  915. }
  916. if(statSource.st_size != statDestination.st_size)
  917. {
  918. return true;
  919. }
  920. if(statSource.st_size == 0)
  921. {
  922. return false;
  923. }
  924. #if defined(_WIN32) || defined(__CYGWIN__)
  925. std::ifstream finSource(source,
  926. std::ios::binary | std::ios::in);
  927. std::ifstream finDestination(destination,
  928. std::ios::binary | std::ios::in);
  929. #else
  930. std::ifstream finSource(source);
  931. std::ifstream finDestination(destination);
  932. #endif
  933. if(!finSource || !finDestination)
  934. {
  935. return true;
  936. }
  937. char* source_buf = new char[statSource.st_size];
  938. char* dest_buf = new char[statSource.st_size];
  939. finSource.read(source_buf, statSource.st_size);
  940. finDestination.read(dest_buf, statSource.st_size);
  941. if(statSource.st_size != finSource.gcount() ||
  942. statSource.st_size != finDestination.gcount())
  943. {
  944. std::strstream msg;
  945. msg << "FilesDiffer failed to read files (allocated: "
  946. << statSource.st_size << ", read source: " << finSource.gcount()
  947. << ", read dest: " << finDestination.gcount() << std::ends;
  948. cmSystemTools::Error(msg.str());
  949. delete [] msg.str();
  950. delete [] source_buf;
  951. delete [] dest_buf;
  952. return false;
  953. }
  954. int ret = memcmp((const void*)source_buf,
  955. (const void*)dest_buf,
  956. statSource.st_size);
  957. delete [] dest_buf;
  958. delete [] source_buf;
  959. return ret != 0;
  960. }
  961. /**
  962. * Copy a file named by "source" to the file named by "destination".
  963. */
  964. void cmSystemTools::cmCopyFile(const char* source,
  965. const char* destination)
  966. {
  967. const int bufferSize = 4096;
  968. char buffer[bufferSize];
  969. // If destination is a directory, try to create a file with the same
  970. // name as the source in that directory.
  971. std::string new_destination;
  972. if(cmSystemTools::FileExists(destination) &&
  973. cmSystemTools::FileIsDirectory(destination))
  974. {
  975. new_destination = destination;
  976. cmSystemTools::ConvertToUnixSlashes(new_destination);
  977. new_destination += '/';
  978. std::string source_name = source;
  979. new_destination += cmSystemTools::GetFilenameName(source_name);
  980. destination = new_destination.c_str();
  981. }
  982. // Create destination directory
  983. std::string destination_dir = destination;
  984. destination_dir = cmSystemTools::GetFilenamePath(destination_dir);
  985. cmSystemTools::MakeDirectory(destination_dir.c_str());
  986. // Open files
  987. #if defined(_WIN32) || defined(__CYGWIN__)
  988. std::ifstream fin(source,
  989. std::ios::binary | std::ios::in);
  990. #else
  991. std::ifstream fin(source);
  992. #endif
  993. if(!fin)
  994. {
  995. cmSystemTools::Error("CopyFile failed to open input file \"",
  996. source, "\"");
  997. return;
  998. }
  999. #if defined(_WIN32) || defined(__CYGWIN__)
  1000. std::ofstream fout(destination,
  1001. std::ios::binary | std::ios::out | std::ios::trunc);
  1002. #else
  1003. std::ofstream fout(destination,
  1004. std::ios::out | std::ios::trunc);
  1005. #endif
  1006. if(!fout)
  1007. {
  1008. cmSystemTools::Error("CopyFile failed to open output file \"",
  1009. destination, "\"");
  1010. return;
  1011. }
  1012. // This copy loop is very sensitive on certain platforms with
  1013. // slightly broken stream libraries (like HPUX). Normally, it is
  1014. // incorrect to not check the error condition on the fin.read()
  1015. // before using the data, but the fin.gcount() will be zero if an
  1016. // error occurred. Therefore, the loop should be safe everywhere.
  1017. while(fin)
  1018. {
  1019. fin.read(buffer, bufferSize);
  1020. if(fin.gcount())
  1021. {
  1022. fout.write(buffer, fin.gcount());
  1023. }
  1024. }
  1025. fin.close();
  1026. fout.close();
  1027. // More checks
  1028. struct stat statSource, statDestination;
  1029. if (stat(source, &statSource) != 0 ||
  1030. stat(destination, &statDestination) != 0)
  1031. {
  1032. cmSystemTools::Error("CopyFile failed to copy files!");
  1033. }
  1034. if (statSource.st_size != statDestination.st_size)
  1035. {
  1036. std::strstream msg;
  1037. msg << "CopyFile failed to copy files (sizes differ, source: "
  1038. << statSource.st_size << " , dest: " << statDestination.st_size
  1039. << std::ends;
  1040. cmSystemTools::Error(msg.str());
  1041. delete [] msg.str();
  1042. }
  1043. }
  1044. // return true if the file exists
  1045. long int cmSystemTools::ModifiedTime(const char* filename)
  1046. {
  1047. struct stat fs;
  1048. if (stat(filename, &fs) != 0)
  1049. {
  1050. return 0;
  1051. }
  1052. else
  1053. {
  1054. return (long int)fs.st_mtime;
  1055. }
  1056. }
  1057. bool cmSystemTools::RemoveFile(const char* source)
  1058. {
  1059. return unlink(source) != 0 ? false : true;
  1060. }
  1061. bool cmSystemTools::IsOn(const char* val)
  1062. {
  1063. if (!val)
  1064. {
  1065. return false;
  1066. }
  1067. std::basic_string<char> v = val;
  1068. for(std::basic_string<char>::iterator c = v.begin();
  1069. c != v.end(); c++)
  1070. {
  1071. *c = toupper(*c);
  1072. }
  1073. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  1074. }
  1075. bool cmSystemTools::IsOff(const char* val)
  1076. {
  1077. if (!val || strlen(val) == 0)
  1078. {
  1079. return true;
  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 == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  1088. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  1089. }
  1090. bool cmSystemTools::RunCommand(const char* command,
  1091. std::string& output,
  1092. const char* dir,
  1093. bool verbose)
  1094. {
  1095. int foo;
  1096. return cmSystemTools::RunCommand(command, output, foo, dir, verbose);
  1097. }
  1098. #if defined(WIN32) && !defined(__CYGWIN__)
  1099. // use this for shell commands like echo and dir
  1100. bool RunCommandViaSystem(const char* command,
  1101. const char* dir,
  1102. std::string& output,
  1103. int& retVal,
  1104. bool verbose)
  1105. {
  1106. const int BUFFER_SIZE = 4096;
  1107. char buffer[BUFFER_SIZE];
  1108. std::string commandInDir;
  1109. if(dir)
  1110. {
  1111. commandInDir = "cd ";
  1112. commandInDir += dir;
  1113. commandInDir += " && ";
  1114. commandInDir += command;
  1115. }
  1116. else
  1117. {
  1118. commandInDir = command;
  1119. }
  1120. command = commandInDir.c_str();
  1121. std::string commandToFile = command;
  1122. commandToFile += " > ";
  1123. std::string tempFile;
  1124. tempFile += _tempnam(0, "cmake");
  1125. commandToFile += tempFile;
  1126. retVal = system(commandToFile.c_str());
  1127. std::ifstream fin(tempFile.c_str());
  1128. if(!fin)
  1129. {
  1130. if(verbose)
  1131. {
  1132. std::string errormsg = "RunCommand produced no output: command: \"";
  1133. errormsg += command;
  1134. errormsg += "\"";
  1135. errormsg += "\nOutput file: ";
  1136. errormsg += tempFile;
  1137. cmSystemTools::Error(errormsg.c_str());
  1138. }
  1139. fin.close();
  1140. cmSystemTools::RemoveFile(tempFile.c_str());
  1141. return false;
  1142. }
  1143. bool multiLine = false;
  1144. while(fin)
  1145. {
  1146. fin.getline(buffer, BUFFER_SIZE);
  1147. output += buffer;
  1148. if(multiLine)
  1149. {
  1150. output += "\n";
  1151. }
  1152. multiLine = true;
  1153. }
  1154. fin.close();
  1155. cmSystemTools::RemoveFile(tempFile.c_str());
  1156. return true;
  1157. }
  1158. #endif // endif WIN32 not CYGWIN
  1159. // run a command unix uses popen (easy)
  1160. // windows uses system and ShortPath
  1161. bool cmSystemTools::RunCommand(const char* command,
  1162. std::string& output,
  1163. int &retVal,
  1164. const char* dir,
  1165. bool verbose)
  1166. {
  1167. if(s_DisableRunCommandOutput)
  1168. {
  1169. verbose = false;
  1170. }
  1171. #if defined(WIN32) && !defined(__CYGWIN__)
  1172. // if the command does not start with a quote, then
  1173. // try to find the program, and if the program can not be
  1174. // found use system to run the command as it must be a built in
  1175. // shell command like echo or dir
  1176. int count = 0;
  1177. if(command[0] == '\"')
  1178. {
  1179. // count the number of quotes
  1180. for(const char* s = command; *s != 0; ++s)
  1181. {
  1182. if(*s == '\"')
  1183. {
  1184. count++;
  1185. if(count > 2)
  1186. {
  1187. break;
  1188. }
  1189. }
  1190. }
  1191. // if there are more than two double quotes use
  1192. // GetShortPathName, the cmd.exe program in windows which
  1193. // is used by system fails to execute if there are more than
  1194. // one set of quotes in the arguments
  1195. if(count > 2)
  1196. {
  1197. cmRegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  1198. if(quoted.find(command))
  1199. {
  1200. std::string shortCmd;
  1201. std::string cmd = quoted.match(1);
  1202. std::string args = quoted.match(2);
  1203. if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  1204. {
  1205. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  1206. return false;
  1207. }
  1208. shortCmd += " ";
  1209. shortCmd += args;
  1210. return RunCommandViaSystem(shortCmd.c_str(), dir,
  1211. output, retVal, verbose);
  1212. }
  1213. else
  1214. {
  1215. cmSystemTools::Error("Could not parse command line with quotes ",
  1216. command);
  1217. }
  1218. }
  1219. }
  1220. // if there is only one set of quotes or no quotes then just run the command
  1221. return RunCommandViaSystem(command, dir, output, retVal, verbose);
  1222. #else
  1223. // if only popen worked on windows.....
  1224. std::string commandInDir;
  1225. if(dir)
  1226. {
  1227. commandInDir = "cd ";
  1228. commandInDir += dir;
  1229. commandInDir += " && ";
  1230. commandInDir += command;
  1231. }
  1232. else
  1233. {
  1234. commandInDir = command;
  1235. }
  1236. command = commandInDir.c_str();
  1237. const int BUFFER_SIZE = 4096;
  1238. char buffer[BUFFER_SIZE];
  1239. if(verbose)
  1240. {
  1241. std::cout << "running " << command << std::endl;
  1242. }
  1243. fflush(stdout);
  1244. fflush(stderr);
  1245. FILE* cpipe = popen(command, "r");
  1246. if(!cpipe)
  1247. {
  1248. return false;
  1249. }
  1250. fgets(buffer, BUFFER_SIZE, cpipe);
  1251. while(!feof(cpipe))
  1252. {
  1253. if(verbose)
  1254. {
  1255. std::cout << buffer << std::flush;
  1256. }
  1257. output += buffer;
  1258. fgets(buffer, BUFFER_SIZE, cpipe);
  1259. }
  1260. retVal = pclose(cpipe);
  1261. retVal = WEXITSTATUS(retVal);
  1262. return true;
  1263. #endif
  1264. }
  1265. /**
  1266. * Find the file the given name. Searches the given path and then
  1267. * the system search path. Returns the full path to the file if it is
  1268. * found. Otherwise, the empty string is returned.
  1269. */
  1270. std::string cmSystemTools::FindFile(const char* name,
  1271. const std::vector<std::string>& userPaths)
  1272. {
  1273. // Add the system search path to our path.
  1274. std::vector<std::string> path = userPaths;
  1275. cmSystemTools::GetPath(path);
  1276. std::string tryPath;
  1277. for(std::vector<std::string>::const_iterator p = path.begin();
  1278. p != path.end(); ++p)
  1279. {
  1280. tryPath = *p;
  1281. tryPath += "/";
  1282. tryPath += name;
  1283. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1284. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1285. {
  1286. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1287. }
  1288. }
  1289. // Couldn't find the file.
  1290. return "";
  1291. }
  1292. /**
  1293. * Find the executable with the given name. Searches the given path and then
  1294. * the system search path. Returns the full path to the executable if it is
  1295. * found. Otherwise, the empty string is returned.
  1296. */
  1297. std::string cmSystemTools::FindProgram(const char* name,
  1298. const std::vector<std::string>& userPaths,
  1299. bool no_system_path)
  1300. {
  1301. // See if the executable exists as written.
  1302. if(cmSystemTools::FileExists(name) &&
  1303. !cmSystemTools::FileIsDirectory(name))
  1304. {
  1305. return cmSystemTools::CollapseFullPath(name);
  1306. }
  1307. std::string tryPath = name;
  1308. tryPath += cmSystemTools::GetExecutableExtension();
  1309. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1310. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1311. {
  1312. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1313. }
  1314. // Add the system search path to our path.
  1315. std::vector<std::string> path = userPaths;
  1316. if (!no_system_path)
  1317. {
  1318. cmSystemTools::GetPath(path);
  1319. }
  1320. for(std::vector<std::string>::const_iterator p = path.begin();
  1321. p != path.end(); ++p)
  1322. {
  1323. tryPath = *p;
  1324. tryPath += "/";
  1325. tryPath += name;
  1326. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1327. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1328. {
  1329. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1330. }
  1331. #ifdef _WIN32
  1332. tryPath += ".com";
  1333. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1334. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1335. {
  1336. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1337. }
  1338. tryPath = *p;
  1339. tryPath += "/";
  1340. tryPath += name;
  1341. #endif
  1342. tryPath += cmSystemTools::GetExecutableExtension();
  1343. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1344. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1345. {
  1346. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1347. }
  1348. }
  1349. // Couldn't find the program.
  1350. return "";
  1351. }
  1352. /**
  1353. * Find the library with the given name. Searches the given path and then
  1354. * the system search path. Returns the full path to the library if it is
  1355. * found. Otherwise, the empty string is returned.
  1356. */
  1357. std::string cmSystemTools::FindLibrary(const char* name,
  1358. const std::vector<std::string>& userPaths)
  1359. {
  1360. // See if the executable exists as written.
  1361. if(cmSystemTools::FileExists(name))
  1362. {
  1363. return cmSystemTools::CollapseFullPath(name);
  1364. }
  1365. // Add the system search path to our path.
  1366. std::vector<std::string> path = userPaths;
  1367. cmSystemTools::GetPath(path);
  1368. std::string tryPath;
  1369. for(std::vector<std::string>::const_iterator p = path.begin();
  1370. p != path.end(); ++p)
  1371. {
  1372. #if defined(_WIN32) && !defined(__CYGWIN__)
  1373. tryPath = *p;
  1374. tryPath += "/";
  1375. tryPath += name;
  1376. tryPath += ".lib";
  1377. if(cmSystemTools::FileExists(tryPath.c_str()))
  1378. {
  1379. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1380. }
  1381. #else
  1382. tryPath = *p;
  1383. tryPath += "/lib";
  1384. tryPath += name;
  1385. tryPath += ".so";
  1386. if(cmSystemTools::FileExists(tryPath.c_str()))
  1387. {
  1388. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1389. }
  1390. tryPath = *p;
  1391. tryPath += "/lib";
  1392. tryPath += name;
  1393. tryPath += ".a";
  1394. if(cmSystemTools::FileExists(tryPath.c_str()))
  1395. {
  1396. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1397. }
  1398. tryPath = *p;
  1399. tryPath += "/lib";
  1400. tryPath += name;
  1401. tryPath += ".sl";
  1402. if(cmSystemTools::FileExists(tryPath.c_str()))
  1403. {
  1404. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1405. }
  1406. #endif
  1407. }
  1408. // Couldn't find the library.
  1409. return "";
  1410. }
  1411. bool cmSystemTools::FileIsDirectory(const char* name)
  1412. {
  1413. struct stat fs;
  1414. if(stat(name, &fs) == 0)
  1415. {
  1416. #if _WIN32
  1417. return ((fs.st_mode & _S_IFDIR) != 0);
  1418. #else
  1419. return S_ISDIR(fs.st_mode);
  1420. #endif
  1421. }
  1422. else
  1423. {
  1424. return false;
  1425. }
  1426. }
  1427. int cmSystemTools::ChangeDirectory(const char *dir)
  1428. {
  1429. return Chdir(dir);
  1430. }
  1431. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1432. {
  1433. char buf[2048];
  1434. std::string path = Getcwd(buf, 2048);
  1435. return path;
  1436. }
  1437. /**
  1438. * Given the path to a program executable, get the directory part of the path with the
  1439. * file stripped off. If there is no directory part, the empty string is returned.
  1440. */
  1441. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1442. {
  1443. std::string dir, file;
  1444. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1445. return dir;
  1446. }
  1447. /**
  1448. * Given the path to a program executable, get the directory part of the path
  1449. * with the file stripped off. If there is no directory part, the empty
  1450. * string is returned.
  1451. */
  1452. void cmSystemTools::SplitProgramPath(const char* in_name,
  1453. std::string& dir,
  1454. std::string& file)
  1455. {
  1456. dir = in_name;
  1457. file = "";
  1458. cmSystemTools::ConvertToUnixSlashes(dir);
  1459. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1460. {
  1461. std::string::size_type slashPos = dir.rfind("/");
  1462. if(slashPos != std::string::npos)
  1463. {
  1464. file = dir.substr(slashPos+1);
  1465. dir = dir.substr(0, slashPos);
  1466. }
  1467. else
  1468. {
  1469. file = dir;
  1470. dir = "";
  1471. }
  1472. }
  1473. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1474. {
  1475. std::string oldDir = in_name;
  1476. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1477. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1478. oldDir.c_str(), "\nDirectory not found: ",
  1479. dir.c_str());
  1480. dir = in_name;
  1481. return;
  1482. }
  1483. }
  1484. /**
  1485. * Given a path to a file or directory, convert it to a full path.
  1486. * This collapses away relative paths. The full path is returned.
  1487. */
  1488. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1489. {
  1490. std::string dir, file;
  1491. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1492. #ifdef _WIN32
  1493. // Ultra-hack warning:
  1494. // This changes to the target directory, saves the working directory,
  1495. // and then changes back to the original working directory.
  1496. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1497. if(dir != "") { Chdir(dir.c_str()); }
  1498. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1499. Chdir(cwd.c_str());
  1500. cmSystemTools::ConvertToUnixSlashes(newDir);
  1501. std::string newPath = newDir+"/"+file;
  1502. return newPath;
  1503. #else
  1504. # ifdef MAXPATHLEN
  1505. char resolved_name[MAXPATHLEN];
  1506. # else
  1507. # ifdef PATH_MAX
  1508. char resolved_name[PATH_MAX];
  1509. # else
  1510. char resolved_name[5024];
  1511. # endif
  1512. # endif
  1513. if(dir != "")
  1514. {
  1515. realpath(dir.c_str(), resolved_name);
  1516. dir = resolved_name;
  1517. }
  1518. else
  1519. {
  1520. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1521. }
  1522. if(file == "")
  1523. {
  1524. return dir;
  1525. }
  1526. return dir + "/" + file;
  1527. #endif
  1528. }
  1529. /**
  1530. * Return path of a full filename (no trailing slashes).
  1531. * Warning: returned path is converted to Unix slashes format.
  1532. */
  1533. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1534. {
  1535. std::string fn = filename;
  1536. cmSystemTools::ConvertToUnixSlashes(fn);
  1537. std::string::size_type slash_pos = fn.rfind("/");
  1538. if(slash_pos != std::string::npos)
  1539. {
  1540. return fn.substr(0, slash_pos);
  1541. }
  1542. else
  1543. {
  1544. return "";
  1545. }
  1546. }
  1547. /**
  1548. * Return file name of a full filename (i.e. file name without path).
  1549. */
  1550. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1551. {
  1552. std::string fn = filename;
  1553. cmSystemTools::ConvertToUnixSlashes(fn);
  1554. std::string::size_type slash_pos = fn.rfind("/");
  1555. if(slash_pos != std::string::npos)
  1556. {
  1557. return fn.substr(slash_pos + 1);
  1558. }
  1559. else
  1560. {
  1561. return filename;
  1562. }
  1563. }
  1564. /**
  1565. * Return file extension of a full filename (dot included).
  1566. * Warning: this is the longest extension (for example: .tar.gz)
  1567. */
  1568. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1569. {
  1570. std::string name = cmSystemTools::GetFilenameName(filename);
  1571. std::string::size_type dot_pos = name.find(".");
  1572. if(dot_pos != std::string::npos)
  1573. {
  1574. return name.substr(dot_pos);
  1575. }
  1576. else
  1577. {
  1578. return "";
  1579. }
  1580. }
  1581. /**
  1582. * Return file extension of a full filename (dot included).
  1583. */
  1584. std::string cmSystemTools::GetFilenameShortestExtension(const std::string& filename)
  1585. {
  1586. std::string name = cmSystemTools::GetFilenameName(filename);
  1587. std::string::size_type dot_pos = name.rfind(".");
  1588. if(dot_pos != std::string::npos)
  1589. {
  1590. return name.substr(dot_pos);
  1591. }
  1592. else
  1593. {
  1594. return "";
  1595. }
  1596. }
  1597. /**
  1598. * Return file name without extension of a full filename (i.e. without path).
  1599. * Warning: it considers the longest extension (for example: .tar.gz)
  1600. */
  1601. std::string cmSystemTools::GetFilenameNameWithoutExtension(const std::string& filename)
  1602. {
  1603. std::string name = cmSystemTools::GetFilenameName(filename);
  1604. std::string::size_type dot_pos = name.find(".");
  1605. if(dot_pos != std::string::npos)
  1606. {
  1607. return name.substr(0, dot_pos);
  1608. }
  1609. else
  1610. {
  1611. return name;
  1612. }
  1613. }
  1614. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1615. std::vector<std::string>& files)
  1616. {
  1617. cmDirectory d;
  1618. cmRegularExpression reg(regexp);
  1619. if (d.Load(directory))
  1620. {
  1621. size_t numf;
  1622. unsigned int i;
  1623. numf = d.GetNumberOfFiles();
  1624. for (i = 0; i < numf; i++)
  1625. {
  1626. std::string fname = d.GetFile(i);
  1627. if (reg.find(fname))
  1628. {
  1629. files.push_back(fname);
  1630. }
  1631. }
  1632. }
  1633. }
  1634. void cmSystemTools::GlobDirs(const char *fullPath,
  1635. std::vector<std::string>& files)
  1636. {
  1637. std::string path = fullPath;
  1638. std::string::size_type pos = path.find("/*");
  1639. if(pos == std::string::npos)
  1640. {
  1641. files.push_back(fullPath);
  1642. return;
  1643. }
  1644. std::string startPath = path.substr(0, pos);
  1645. std::string finishPath = path.substr(pos+2);
  1646. cmDirectory d;
  1647. if (d.Load(startPath.c_str()))
  1648. {
  1649. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1650. {
  1651. if((std::string(d.GetFile(i)) != ".")
  1652. && (std::string(d.GetFile(i)) != ".."))
  1653. {
  1654. std::string fname = startPath;
  1655. fname +="/";
  1656. fname += d.GetFile(i);
  1657. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1658. {
  1659. fname += finishPath;
  1660. cmSystemTools::GlobDirs(fname.c_str(), files);
  1661. }
  1662. }
  1663. }
  1664. }
  1665. }
  1666. void cmSystemTools::ExpandListArguments(std::vector<std::string> const& arguments,
  1667. std::vector<std::string>& newargs)
  1668. {
  1669. std::vector<std::string>::const_iterator i;
  1670. std::string newarg;
  1671. for(i = arguments.begin();i != arguments.end(); ++i)
  1672. {
  1673. // if there are no ; in the name then just copy the current string
  1674. if(i->find(';') == std::string::npos)
  1675. {
  1676. newargs.push_back(*i);
  1677. }
  1678. else
  1679. {
  1680. std::string::size_type start = 0;
  1681. std::string::size_type endpos = 0;
  1682. const std::string::size_type size = i->size();
  1683. // break up ; separated sections of the string into separate strings
  1684. while(endpos != size)
  1685. {
  1686. endpos = i->find(';', start);
  1687. if(endpos == std::string::npos)
  1688. {
  1689. endpos = i->size();
  1690. }
  1691. else
  1692. {
  1693. // skip right over escaped ; ( \; )
  1694. while((endpos != std::string::npos)
  1695. && (endpos > 0)
  1696. && ((*i)[endpos-1] == '\\') )
  1697. {
  1698. endpos = i->find(';', endpos+1);
  1699. }
  1700. if(endpos == std::string::npos)
  1701. {
  1702. endpos = i->size();
  1703. }
  1704. }
  1705. std::string::size_type len = endpos - start;
  1706. if (len > 0)
  1707. {
  1708. // check for a closing ] after the start position
  1709. if(i->find('[', start) == std::string::npos)
  1710. {
  1711. // if there is no [ in the string then keep it
  1712. newarg = i->substr(start, len);
  1713. }
  1714. else
  1715. {
  1716. int opencount = 0;
  1717. int closecount = 0;
  1718. for(std::string::size_type j = start; j < endpos; ++j)
  1719. {
  1720. if(i->at(j) == '[')
  1721. {
  1722. ++opencount;
  1723. }
  1724. else if (i->at(j) == ']')
  1725. {
  1726. ++closecount;
  1727. }
  1728. }
  1729. if(opencount != closecount)
  1730. {
  1731. // skip this one
  1732. endpos = i->find(';', endpos+1);
  1733. if(endpos == std::string::npos)
  1734. {
  1735. endpos = i->size();
  1736. }
  1737. len = endpos - start;
  1738. }
  1739. newarg = i->substr(start, len);
  1740. }
  1741. std::string::size_type pos = newarg.find("\\;");
  1742. if(pos != std::string::npos)
  1743. {
  1744. newarg.erase(pos, 1);
  1745. }
  1746. newargs.push_back(newarg);
  1747. }
  1748. start = endpos+1;
  1749. }
  1750. }
  1751. }
  1752. }
  1753. bool cmSystemTools::GetShortPath(const char* path, std::string& shortPath)
  1754. {
  1755. #if defined(WIN32) && !defined(__CYGWIN__)
  1756. const int size = int(strlen(path)) +1; // size of return
  1757. char *buffer = new char[size]; // create a buffer
  1758. buffer[0] = 0;
  1759. int ret = GetShortPathName(path, buffer, size);
  1760. if(buffer[0] == 0 || ret > size)
  1761. {
  1762. if(ret < size)
  1763. {
  1764. LPVOID lpMsgBuf;
  1765. FormatMessage(
  1766. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1767. FORMAT_MESSAGE_FROM_SYSTEM |
  1768. FORMAT_MESSAGE_IGNORE_INSERTS,
  1769. NULL,
  1770. GetLastError(),
  1771. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  1772. (LPTSTR) &lpMsgBuf,
  1773. 0,
  1774. NULL
  1775. );
  1776. cmSystemTools::Error((LPCTSTR)lpMsgBuf);
  1777. LocalFree( lpMsgBuf );
  1778. }
  1779. cmSystemTools::Error("Unable to get a short path: ", path);
  1780. return false;
  1781. }
  1782. else
  1783. {
  1784. shortPath = buffer;
  1785. delete [] buffer;
  1786. return true;
  1787. }
  1788. #else
  1789. shortPath = path;
  1790. return true;
  1791. #endif
  1792. }