cmSystemTools.cxx 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900
  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. else
  317. {
  318. if(RegSetValueEx(hKey,
  319. (LPTSTR)valuename.c_str(),
  320. 0,
  321. REG_SZ,
  322. (CONST BYTE *)value,
  323. (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
  324. {
  325. return true;
  326. }
  327. }
  328. #endif
  329. return false;
  330. }
  331. // Delete a registry value.
  332. // Example :
  333. // HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
  334. // => will delete the data of the "default" value of the key
  335. // HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
  336. // => will delete the data of the "Root" value of the key
  337. bool cmSystemTools::DeleteRegistryValue(const char *key)
  338. {
  339. #if defined(_WIN32) && !defined(__CYGWIN__)
  340. std::string primary = key;
  341. std::string second;
  342. std::string valuename;
  343. size_t start = primary.find("\\");
  344. if (start == std::string::npos)
  345. {
  346. return false;
  347. }
  348. size_t valuenamepos = primary.find(";");
  349. if (valuenamepos != std::string::npos)
  350. {
  351. valuename = primary.substr(valuenamepos+1);
  352. }
  353. second = primary.substr(start+1, valuenamepos-start-1);
  354. primary = primary.substr(0, start);
  355. HKEY primaryKey;
  356. if (primary == "HKEY_CURRENT_USER")
  357. {
  358. primaryKey = HKEY_CURRENT_USER;
  359. }
  360. if (primary == "HKEY_CURRENT_CONFIG")
  361. {
  362. primaryKey = HKEY_CURRENT_CONFIG;
  363. }
  364. if (primary == "HKEY_CLASSES_ROOT")
  365. {
  366. primaryKey = HKEY_CLASSES_ROOT;
  367. }
  368. if (primary == "HKEY_LOCAL_MACHINE")
  369. {
  370. primaryKey = HKEY_LOCAL_MACHINE;
  371. }
  372. if (primary == "HKEY_USERS")
  373. {
  374. primaryKey = HKEY_USERS;
  375. }
  376. HKEY hKey;
  377. if(RegOpenKeyEx(primaryKey,
  378. second.c_str(),
  379. 0,
  380. KEY_WRITE,
  381. &hKey) != ERROR_SUCCESS)
  382. {
  383. return false;
  384. }
  385. else
  386. {
  387. if(RegDeleteValue(hKey,
  388. (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
  389. {
  390. return true;
  391. }
  392. }
  393. #endif
  394. return false;
  395. }
  396. // replace replace with with as many times as it shows up in source.
  397. // write the result into source.
  398. void cmSystemTools::ExpandRegistryValues(std::string& source)
  399. {
  400. #if defined(_WIN32) && !defined(__CYGWIN__)
  401. // Regular expression to match anything inside [...] that begins in HKEY.
  402. // Note that there is a special rule for regular expressions to match a
  403. // close square-bracket inside a list delimited by square brackets.
  404. // The "[^]]" part of this expression will match any character except
  405. // a close square-bracket. The ']' character must be the first in the
  406. // list of characters inside the [^...] block of the expression.
  407. cmRegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  408. // check for black line or comment
  409. while (regEntry.find(source))
  410. {
  411. // the arguments are the second match
  412. std::string key = regEntry.match(1);
  413. std::string val;
  414. if (ReadRegistryValue(key.c_str(), val))
  415. {
  416. std::string reg = "[";
  417. reg += key + "]";
  418. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  419. }
  420. else
  421. {
  422. std::string reg = "[";
  423. reg += key + "]";
  424. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  425. }
  426. }
  427. #endif
  428. }
  429. std::string cmSystemTools::EscapeQuotes(const char* str)
  430. {
  431. std::string result = "";
  432. for(const char* ch = str; *ch != '\0'; ++ch)
  433. {
  434. if(*ch == '"')
  435. {
  436. result += '\\';
  437. }
  438. result += *ch;
  439. }
  440. return result;
  441. }
  442. bool cmSystemTools::SameFile(const char* file1, const char* file2)
  443. {
  444. struct stat fileStat1, fileStat2;
  445. if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
  446. {
  447. // see if the files are the same file
  448. // check the device inode and size
  449. if(fileStat2.st_dev == fileStat1.st_dev &&
  450. fileStat2.st_ino == fileStat1.st_ino &&
  451. fileStat2.st_size == fileStat1.st_size
  452. )
  453. {
  454. return true;
  455. }
  456. }
  457. return false;
  458. }
  459. // return true if the file exists
  460. bool cmSystemTools::FileExists(const char* filename)
  461. {
  462. struct stat fs;
  463. if (stat(filename, &fs) != 0)
  464. {
  465. return false;
  466. }
  467. else
  468. {
  469. return true;
  470. }
  471. }
  472. // Return a capitalized string (i.e the first letter is uppercased, all other
  473. // are lowercased)
  474. std::string cmSystemTools::Capitalized(const std::string& s)
  475. {
  476. std::string n;
  477. n.resize(s.size());
  478. n[0] = toupper(s[0]);
  479. for (size_t i = 1; i < s.size(); i++)
  480. {
  481. n[i] = tolower(s[i]);
  482. }
  483. return n;
  484. }
  485. // Return a lower case string
  486. std::string cmSystemTools::LowerCase(const std::string& s)
  487. {
  488. std::string n;
  489. n.resize(s.size());
  490. for (size_t i = 0; i < s.size(); i++)
  491. {
  492. n[i] = tolower(s[i]);
  493. }
  494. return n;
  495. }
  496. // Return a lower case string
  497. std::string cmSystemTools::UpperCase(const std::string& s)
  498. {
  499. std::string n;
  500. n.resize(s.size());
  501. for (size_t i = 0; i < s.size(); i++)
  502. {
  503. n[i] = toupper(s[i]);
  504. }
  505. return n;
  506. }
  507. // convert windows slashes to unix slashes
  508. void cmSystemTools::ConvertToUnixSlashes(std::string& path)
  509. {
  510. std::string::size_type pos = 0;
  511. while((pos = path.find('\\', pos)) != std::string::npos)
  512. {
  513. path[pos] = '/';
  514. pos++;
  515. }
  516. // remove any trailing slash
  517. if(path.size() && path[path.size()-1] == '/')
  518. {
  519. path = path.substr(0, path.size()-1);
  520. }
  521. // if there is a tilda ~ then replace it with HOME
  522. if(path.find("~") == 0)
  523. {
  524. if (getenv("HOME"))
  525. {
  526. path = std::string(getenv("HOME")) + path.substr(1);
  527. }
  528. }
  529. // if there is a /tmp_mnt in a path get rid of it!
  530. // stupid sgi's
  531. if(path.find("/tmp_mnt") == 0)
  532. {
  533. path = path.substr(8);
  534. }
  535. }
  536. // change // to /, and escape any spaces in the path
  537. std::string cmSystemTools::ConvertToUnixOutputPath(const char* path)
  538. {
  539. std::string ret = path;
  540. // remove // except at the beginning might be a cygwin drive
  541. std::string::size_type pos = 1;
  542. while((pos = ret.find("//", pos)) != std::string::npos)
  543. {
  544. ret.erase(pos, 1);
  545. }
  546. // now escape spaces if there is a space in the path
  547. if(ret.find(" ") != std::string::npos)
  548. {
  549. std::string result = "";
  550. char lastch = 1;
  551. for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
  552. {
  553. // if it is already escaped then don't try to escape it again
  554. if(*ch == ' ' && lastch != '\\')
  555. {
  556. result += '\\';
  557. }
  558. result += *ch;
  559. lastch = *ch;
  560. }
  561. ret = result;
  562. }
  563. return ret;
  564. }
  565. std::string cmSystemTools::EscapeSpaces(const char* str)
  566. {
  567. #if defined(_WIN32) && !defined(__CYGWIN__)
  568. std::string result;
  569. // if there are spaces
  570. std::string temp = str;
  571. if (temp.find(" ") != std::string::npos &&
  572. temp.find("\"")==std::string::npos)
  573. {
  574. result = "\"";
  575. result += str;
  576. result += "\"";
  577. return result;
  578. }
  579. return str;
  580. #else
  581. std::string result = "";
  582. for(const char* ch = str; *ch != '\0'; ++ch)
  583. {
  584. if(*ch == ' ')
  585. {
  586. result += '\\';
  587. }
  588. result += *ch;
  589. }
  590. return result;
  591. #endif
  592. }
  593. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  594. {
  595. #if defined(_WIN32) && !defined(__CYGWIN__)
  596. return cmSystemTools::ConvertToWindowsOutputPath(path);
  597. #else
  598. return cmSystemTools::ConvertToUnixOutputPath(path);
  599. #endif
  600. }
  601. // remove double slashes not at the start
  602. std::string cmSystemTools::ConvertToWindowsOutputPath(const char* path)
  603. {
  604. std::string ret = path;
  605. std::string::size_type pos = 0;
  606. // first convert all of the slashes
  607. while((pos = ret.find('/', pos)) != std::string::npos)
  608. {
  609. ret[pos] = '\\';
  610. pos++;
  611. }
  612. // check for really small paths
  613. if(ret.size() < 2)
  614. {
  615. return ret;
  616. }
  617. // now clean up a bit and remove double slashes
  618. // Only if it is not the first position in the path which is a network
  619. // path on windows
  620. pos = 1; // start at position 1
  621. while((pos = ret.find("\\\\", pos)) != std::string::npos)
  622. {
  623. ret.erase(pos, 1);
  624. }
  625. // now double quote the path if it has spaces in it
  626. // and is not already double quoted
  627. if(ret.find(" ") != std::string::npos
  628. && ret[0] != '\"')
  629. {
  630. std::string result;
  631. result = "\"" + ret + "\"";
  632. ret = result;
  633. }
  634. return ret;
  635. }
  636. bool cmSystemTools::ParseFunction(std::ifstream& fin,
  637. std::string& name,
  638. std::vector<std::string>& arguments,
  639. const char* filename,
  640. bool& parseError)
  641. {
  642. parseError = false;
  643. name = "";
  644. arguments = std::vector<std::string>();
  645. const int BUFFER_SIZE = 4096;
  646. char inbuffer[BUFFER_SIZE];
  647. if(!fin)
  648. {
  649. return false;
  650. }
  651. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  652. {
  653. cmRegularExpression blankLine("^[ \t\r]*$");
  654. cmRegularExpression comment("^[ \t]*#.*$");
  655. cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t\r]*$");
  656. cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
  657. cmRegularExpression lastLine("^(.*)\\)[ \t\r]*$");
  658. // check for black line or comment
  659. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  660. {
  661. return false;
  662. }
  663. // look for a oneline fun(arg arg2)
  664. else if(oneLiner.find(inbuffer))
  665. {
  666. // the arguments are the second match
  667. std::string args = oneLiner.match(2);
  668. name = oneLiner.match(1);
  669. // break up the arguments
  670. cmSystemTools::GetArguments(args, arguments);
  671. return true;
  672. }
  673. // look for a start of a multiline with no trailing ")" fun(arg arg2
  674. else if(multiLine.find(inbuffer))
  675. {
  676. name = multiLine.match(1);
  677. std::string args = multiLine.match(2);
  678. cmSystemTools::GetArguments(args, arguments);
  679. // Read lines until the closing paren is hit
  680. bool done = false;
  681. while(!done)
  682. {
  683. // read lines until the end paren is found
  684. if(fin.getline(inbuffer, BUFFER_SIZE ) )
  685. {
  686. // Check for comment lines and ignore them.
  687. if(blankLine.find(inbuffer) || comment.find(inbuffer))
  688. { continue; }
  689. // Is this the last line?
  690. if(lastLine.find(inbuffer))
  691. {
  692. done = true;
  693. std::string args = lastLine.match(1);
  694. cmSystemTools::GetArguments(args, arguments);
  695. }
  696. else
  697. {
  698. std::string line = inbuffer;
  699. cmSystemTools::GetArguments(line, arguments);
  700. }
  701. }
  702. else
  703. {
  704. parseError = true;
  705. cmSystemTools::Error("Parse error in read function missing end )\nIn File: ",
  706. filename, "\nCurrent line:", inbuffer);
  707. return false;
  708. }
  709. }
  710. return true;
  711. }
  712. else
  713. {
  714. parseError = true;
  715. cmSystemTools::Error("Parse error in read function\nIn file:",
  716. filename, "\nCurrent line:", inbuffer);
  717. return false;
  718. }
  719. }
  720. return false;
  721. }
  722. void cmSystemTools::GetArguments(std::string& line,
  723. std::vector<std::string>& arguments)
  724. {
  725. // Match a normal argument (not quoted, no spaces).
  726. cmRegularExpression normalArgument("[ \t]*(([^ \t\r\\]|[\\].)+)[ \t\r]*");
  727. // Match a quoted argument (surrounded by double quotes, spaces allowed).
  728. cmRegularExpression quotedArgument("[ \t]*(\"([^\"\\]|[\\].)*\")[ \t\r]*");
  729. bool done = false;
  730. while(!done)
  731. {
  732. std::string arg;
  733. std::string::size_type endpos;
  734. bool foundQuoted = quotedArgument.find(line.c_str());
  735. bool foundNormal = normalArgument.find(line.c_str());
  736. if(foundQuoted && foundNormal)
  737. {
  738. // Both matches were found. Take the earlier one.
  739. // Favor double-quoted version if there is a tie.
  740. if(normalArgument.start(1) < quotedArgument.start(1))
  741. {
  742. arg = normalArgument.match(1);
  743. endpos = normalArgument.end(1);
  744. }
  745. else
  746. {
  747. arg = quotedArgument.match(1);
  748. endpos = quotedArgument.end(1);
  749. // Strip off the double quotes on the ends.
  750. arg = arg.substr(1, arg.length()-2);
  751. }
  752. }
  753. else if (foundQuoted)
  754. {
  755. arg = quotedArgument.match(1);
  756. endpos = quotedArgument.end(1);
  757. // Strip off the double quotes on the ends.
  758. arg = arg.substr(1, arg.length()-2);
  759. }
  760. else if(foundNormal)
  761. {
  762. arg = normalArgument.match(1);
  763. endpos = normalArgument.end(1);
  764. }
  765. else
  766. {
  767. done = true;
  768. }
  769. if(!done)
  770. {
  771. arguments.push_back(cmSystemTools::RemoveEscapes(arg.c_str()));
  772. line = line.substr(endpos, line.length() - endpos);
  773. }
  774. }
  775. }
  776. std::string cmSystemTools::RemoveEscapes(const char* s)
  777. {
  778. std::string result = "";
  779. for(const char* ch = s; *ch; ++ch)
  780. {
  781. if(*ch == '\\')
  782. {
  783. ++ch;
  784. switch (*ch)
  785. {
  786. case '\\': result.insert(result.end(), '\\'); break;
  787. case '"': result.insert(result.end(), '"'); break;
  788. case ' ': result.insert(result.end(), ' '); break;
  789. case 't': result.insert(result.end(), '\t'); break;
  790. case 'n': result.insert(result.end(), '\n'); break;
  791. case 'r': result.insert(result.end(), '\r'); break;
  792. case '0': result.insert(result.end(), '\0'); break;
  793. case '\0':
  794. {
  795. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  796. return result;
  797. }
  798. default:
  799. {
  800. std::string chStr(1, *ch);
  801. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  802. "\nin argument ", s);
  803. }
  804. }
  805. }
  806. else
  807. {
  808. result.insert(result.end(), *ch);
  809. }
  810. }
  811. return result;
  812. }
  813. void cmSystemTools::Error(const char* m1, const char* m2,
  814. const char* m3, const char* m4)
  815. {
  816. std::string message = "CMake Error: ";
  817. if(m1)
  818. {
  819. message += m1;
  820. }
  821. if(m2)
  822. {
  823. message += m2;
  824. }
  825. if(m3)
  826. {
  827. message += m3;
  828. }
  829. if(m4)
  830. {
  831. message += m4;
  832. }
  833. cmSystemTools::s_ErrorOccured = true;
  834. cmSystemTools::Message(message.c_str(),"Error");
  835. }
  836. void cmSystemTools::SetErrorCallback(ErrorCallback f)
  837. {
  838. s_ErrorCallback = f;
  839. }
  840. void cmSystemTools::Message(const char* m1, const char *title)
  841. {
  842. if(s_DisableMessages)
  843. {
  844. return;
  845. }
  846. if(s_ErrorCallback)
  847. {
  848. (*s_ErrorCallback)(m1, title, s_DisableMessages);
  849. return;
  850. }
  851. else
  852. {
  853. std::cerr << m1 << std::endl;
  854. }
  855. }
  856. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  857. const char* destination)
  858. {
  859. if(cmSystemTools::FilesDiffer(source, destination))
  860. {
  861. cmSystemTools::cmCopyFile(source, destination);
  862. return true;
  863. }
  864. return false;
  865. }
  866. bool cmSystemTools::FilesDiffer(const char* source,
  867. const char* destination)
  868. {
  869. struct stat statSource;
  870. if (stat(source, &statSource) != 0)
  871. {
  872. return true;
  873. }
  874. struct stat statDestination;
  875. if (stat(destination, &statDestination) != 0)
  876. {
  877. return true;
  878. }
  879. if(statSource.st_size != statDestination.st_size)
  880. {
  881. return true;
  882. }
  883. #if defined(_WIN32) || defined(__CYGWIN__)
  884. std::ifstream finSource(source,
  885. std::ios::binary | std::ios::in);
  886. std::ifstream finDestination(destination,
  887. std::ios::binary | std::ios::in);
  888. #else
  889. std::ifstream finSource(source);
  890. std::ifstream finDestination(destination);
  891. #endif
  892. if(!finSource || !finDestination)
  893. {
  894. return true;
  895. }
  896. char* source_buf = new char[statSource.st_size];
  897. if (!source_buf)
  898. {
  899. cmSystemTools::Error("FilesDiffer failed to allocate memory for source!");
  900. return false;
  901. }
  902. char* dest_buf = new char[statSource.st_size];
  903. if (!dest_buf)
  904. {
  905. cmSystemTools::Error("FilesDiffer failed to allocate memory for dest!");
  906. delete [] source_buf;
  907. return false;
  908. }
  909. finSource.read(source_buf, statSource.st_size);
  910. finDestination.read(dest_buf, statSource.st_size);
  911. if(statSource.st_size != finSource.gcount() ||
  912. statSource.st_size != finDestination.gcount())
  913. {
  914. char msg[256];
  915. sprintf(msg, "FilesDiffer failed to read files (allocated: %lu, source: %lu, dest: %lu)", statSource.st_size, finSource.gcount(), finDestination.gcount());
  916. cmSystemTools::Error(msg);
  917. delete [] source_buf;
  918. delete [] dest_buf;
  919. return false;
  920. }
  921. finSource.close();
  922. finDestination.close();
  923. int ret = memcmp((const void*)source_buf,
  924. (const void*)dest_buf,
  925. statSource.st_size);
  926. delete [] dest_buf;
  927. delete [] source_buf;
  928. return ret != 0;
  929. }
  930. /**
  931. * Copy a file named by "source" to the file named by "destination".
  932. */
  933. void cmSystemTools::cmCopyFile(const char* source,
  934. const char* destination)
  935. {
  936. const int bufferSize = 4096;
  937. char buffer[bufferSize];
  938. // If destination is a directory, try to create a file with the same
  939. // name as the source in that directory.
  940. std::string new_destination;
  941. if(cmSystemTools::FileExists(destination) &&
  942. cmSystemTools::FileIsDirectory(destination))
  943. {
  944. new_destination = destination;
  945. cmSystemTools::ConvertToUnixSlashes(new_destination);
  946. new_destination += '/';
  947. std::string source_name = source;
  948. new_destination += cmSystemTools::GetFilenameName(source_name);
  949. destination = new_destination.c_str();
  950. }
  951. // Create destination directory
  952. std::string destination_dir = destination;
  953. destination_dir = cmSystemTools::GetFilenamePath(destination_dir);
  954. cmSystemTools::MakeDirectory(destination_dir.c_str());
  955. // Open files
  956. #if defined(_WIN32) || defined(__CYGWIN__)
  957. std::ifstream fin(source,
  958. std::ios::binary | std::ios::in);
  959. #else
  960. std::ifstream fin(source);
  961. #endif
  962. if(!fin)
  963. {
  964. cmSystemTools::Error("CopyFile failed to open input file \"",
  965. source, "\"");
  966. return;
  967. }
  968. #if defined(_WIN32) || defined(__CYGWIN__)
  969. std::ofstream fout(destination,
  970. std::ios::binary | std::ios::out | std::ios::trunc);
  971. #else
  972. std::ofstream fout(destination,
  973. std::ios::out | std::ios::trunc);
  974. #endif
  975. if(!fout)
  976. {
  977. cmSystemTools::Error("CopyFile failed to open output file \"",
  978. destination, "\"");
  979. return;
  980. }
  981. // This copy loop is very sensitive on certain platforms with
  982. // slightly broken stream libraries (like HPUX). Normally, it is
  983. // incorrect to not check the error condition on the fin.read()
  984. // before using the data, but the fin.gcount() will be zero if an
  985. // error occurred. Therefore, the loop should be safe everywhere.
  986. while(fin)
  987. {
  988. fin.read(buffer, bufferSize);
  989. if(fin.gcount())
  990. {
  991. fout.write(buffer, fin.gcount());
  992. }
  993. }
  994. fin.close();
  995. fout.close();
  996. // More checks
  997. struct stat statSource, statDestination;
  998. if (stat(source, &statSource) != 0 ||
  999. stat(destination, &statDestination) != 0)
  1000. {
  1001. cmSystemTools::Error("CopyFile failed to copy files!");
  1002. }
  1003. if (statSource.st_size != statDestination.st_size)
  1004. {
  1005. char msg[256];
  1006. sprintf(msg, "CopyFile failed to copy files (sizes differ, source: %lu, dest: %lu)", statSource.st_size, statDestination.st_size);
  1007. cmSystemTools::Error(msg);
  1008. }
  1009. }
  1010. // return true if the file exists
  1011. long int cmSystemTools::ModifiedTime(const char* filename)
  1012. {
  1013. struct stat fs;
  1014. if (stat(filename, &fs) != 0)
  1015. {
  1016. return 0;
  1017. }
  1018. else
  1019. {
  1020. return (long int)fs.st_mtime;
  1021. }
  1022. }
  1023. bool cmSystemTools::RemoveFile(const char* source)
  1024. {
  1025. return unlink(source) != 0 ? false : true;
  1026. }
  1027. bool cmSystemTools::IsOn(const char* val)
  1028. {
  1029. if (!val)
  1030. {
  1031. return false;
  1032. }
  1033. std::basic_string<char> v = val;
  1034. for(std::basic_string<char>::iterator c = v.begin();
  1035. c != v.end(); c++)
  1036. {
  1037. *c = toupper(*c);
  1038. }
  1039. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  1040. }
  1041. bool cmSystemTools::IsOff(const char* val)
  1042. {
  1043. if (!val || strlen(val) == 0)
  1044. {
  1045. return true;
  1046. }
  1047. std::basic_string<char> v = val;
  1048. for(std::basic_string<char>::iterator c = v.begin();
  1049. c != v.end(); c++)
  1050. {
  1051. *c = toupper(*c);
  1052. }
  1053. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  1054. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  1055. }
  1056. bool cmSystemTools::RunCommand(const char* command,
  1057. std::string& output,
  1058. const char* dir,
  1059. bool verbose)
  1060. {
  1061. int foo;
  1062. return cmSystemTools::RunCommand(command, output, foo, dir, verbose);
  1063. }
  1064. #if defined(WIN32) && !defined(__CYGWIN__)
  1065. // use this for shell commands like echo and dir
  1066. bool RunCommandViaSystem(const char* command,
  1067. const char* dir,
  1068. std::string& output,
  1069. int& retVal,
  1070. bool verbose)
  1071. {
  1072. const int BUFFER_SIZE = 4096;
  1073. char buffer[BUFFER_SIZE];
  1074. std::string commandInDir;
  1075. if(dir)
  1076. {
  1077. commandInDir = "cd ";
  1078. commandInDir += dir;
  1079. commandInDir += " && ";
  1080. commandInDir += command;
  1081. }
  1082. else
  1083. {
  1084. commandInDir = command;
  1085. }
  1086. command = commandInDir.c_str();
  1087. std::string commandToFile = command;
  1088. commandToFile += " > ";
  1089. std::string tempFile;
  1090. tempFile += _tempnam(0, "cmake");
  1091. commandToFile += tempFile;
  1092. retVal = system(commandToFile.c_str());
  1093. std::ifstream fin(tempFile.c_str());
  1094. if(!fin)
  1095. {
  1096. if(verbose)
  1097. {
  1098. std::string errormsg = "RunCommand produced no output: command: \"";
  1099. errormsg += command;
  1100. errormsg += "\"";
  1101. errormsg += "\nOutput file: ";
  1102. errormsg += tempFile;
  1103. cmSystemTools::Error(errormsg.c_str());
  1104. }
  1105. fin.close();
  1106. cmSystemTools::RemoveFile(tempFile.c_str());
  1107. return false;
  1108. }
  1109. bool multiLine = false;
  1110. while(fin)
  1111. {
  1112. fin.getline(buffer, BUFFER_SIZE);
  1113. output += buffer;
  1114. if(multiLine)
  1115. {
  1116. output += "\n";
  1117. }
  1118. multiLine = true;
  1119. }
  1120. fin.close();
  1121. cmSystemTools::RemoveFile(tempFile.c_str());
  1122. return true;
  1123. }
  1124. #endif // endif WIN32 not CYGWIN
  1125. // run a command unix uses popen (easy)
  1126. // windows uses system and ShortPath
  1127. bool cmSystemTools::RunCommand(const char* command,
  1128. std::string& output,
  1129. int &retVal,
  1130. const char* dir,
  1131. bool verbose)
  1132. {
  1133. if(s_DisableRunCommandOutput)
  1134. {
  1135. verbose = false;
  1136. }
  1137. #if defined(WIN32) && !defined(__CYGWIN__)
  1138. // if the command does not start with a quote, then
  1139. // try to find the program, and if the program can not be
  1140. // found use system to run the command as it must be a built in
  1141. // shell command like echo or dir
  1142. int count = 0;
  1143. if(command[0] == '\"')
  1144. {
  1145. // count the number of quotes
  1146. for(const char* s = command; *s != 0; ++s)
  1147. {
  1148. if(*s == '\"')
  1149. {
  1150. count++;
  1151. if(count > 2)
  1152. {
  1153. break;
  1154. }
  1155. }
  1156. }
  1157. // if there are more than two double quotes use
  1158. // GetShortPathName, the cmd.exe program in windows which
  1159. // is used by system fails to execute if there are more than
  1160. // one set of quotes in the arguments
  1161. if(count > 2)
  1162. {
  1163. cmRegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  1164. if(quoted.find(command))
  1165. {
  1166. std::string shortCmd;
  1167. std::string cmd = quoted.match(1);
  1168. std::string args = quoted.match(2);
  1169. if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  1170. {
  1171. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  1172. return false;
  1173. }
  1174. shortCmd += " ";
  1175. shortCmd += args;
  1176. return RunCommandViaSystem(shortCmd.c_str(), dir,
  1177. output, retVal, verbose);
  1178. }
  1179. else
  1180. {
  1181. cmSystemTools::Error("Could not parse command line with quotes ",
  1182. command);
  1183. }
  1184. }
  1185. }
  1186. // if there is only one set of quotes or no quotes then just run the command
  1187. return RunCommandViaSystem(command, dir, output, retVal, verbose);
  1188. #else
  1189. // if only popen worked on windows.....
  1190. std::string commandInDir;
  1191. if(dir)
  1192. {
  1193. commandInDir = "cd ";
  1194. commandInDir += dir;
  1195. commandInDir += " && ";
  1196. commandInDir += command;
  1197. }
  1198. else
  1199. {
  1200. commandInDir = command;
  1201. }
  1202. command = commandInDir.c_str();
  1203. const int BUFFER_SIZE = 4096;
  1204. char buffer[BUFFER_SIZE];
  1205. if(verbose)
  1206. {
  1207. std::cout << "running " << command << std::endl;
  1208. }
  1209. fflush(stdout);
  1210. fflush(stderr);
  1211. FILE* cpipe = popen(command, "r");
  1212. if(!cpipe)
  1213. {
  1214. return false;
  1215. }
  1216. fgets(buffer, BUFFER_SIZE, cpipe);
  1217. while(!feof(cpipe))
  1218. {
  1219. if(verbose)
  1220. {
  1221. std::cout << buffer << std::flush;
  1222. }
  1223. output += buffer;
  1224. fgets(buffer, BUFFER_SIZE, cpipe);
  1225. }
  1226. retVal = pclose(cpipe);
  1227. retVal = WEXITSTATUS(retVal);
  1228. return true;
  1229. #endif
  1230. }
  1231. /**
  1232. * Find the file the given name. Searches the given path and then
  1233. * the system search path. Returns the full path to the file if it is
  1234. * found. Otherwise, the empty string is returned.
  1235. */
  1236. std::string cmSystemTools::FindFile(const char* name,
  1237. const std::vector<std::string>& userPaths)
  1238. {
  1239. // Add the system search path to our path.
  1240. std::vector<std::string> path = userPaths;
  1241. cmSystemTools::GetPath(path);
  1242. std::string tryPath;
  1243. for(std::vector<std::string>::const_iterator p = path.begin();
  1244. p != path.end(); ++p)
  1245. {
  1246. tryPath = *p;
  1247. tryPath += "/";
  1248. tryPath += name;
  1249. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1250. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1251. {
  1252. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1253. }
  1254. }
  1255. // Couldn't find the file.
  1256. return "";
  1257. }
  1258. /**
  1259. * Find the executable with the given name. Searches the given path and then
  1260. * the system search path. Returns the full path to the executable if it is
  1261. * found. Otherwise, the empty string is returned.
  1262. */
  1263. std::string cmSystemTools::FindProgram(const char* name,
  1264. const std::vector<std::string>& userPaths)
  1265. {
  1266. // See if the executable exists as written.
  1267. if(cmSystemTools::FileExists(name) &&
  1268. !cmSystemTools::FileIsDirectory(name))
  1269. {
  1270. return cmSystemTools::CollapseFullPath(name);
  1271. }
  1272. std::string tryPath = name;
  1273. tryPath += cmSystemTools::GetExecutableExtension();
  1274. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1275. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1276. {
  1277. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1278. }
  1279. // Add the system search path to our path.
  1280. std::vector<std::string> path = userPaths;
  1281. cmSystemTools::GetPath(path);
  1282. for(std::vector<std::string>::const_iterator p = path.begin();
  1283. p != path.end(); ++p)
  1284. {
  1285. tryPath = *p;
  1286. tryPath += "/";
  1287. tryPath += name;
  1288. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1289. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1290. {
  1291. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1292. }
  1293. #ifdef _WIN32
  1294. tryPath += ".com";
  1295. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1296. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1297. {
  1298. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1299. }
  1300. tryPath = *p;
  1301. tryPath += "/";
  1302. tryPath += name;
  1303. #endif
  1304. tryPath += cmSystemTools::GetExecutableExtension();
  1305. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1306. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1307. {
  1308. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1309. }
  1310. }
  1311. // Couldn't find the program.
  1312. return "";
  1313. }
  1314. /**
  1315. * Find the library with the given name. Searches the given path and then
  1316. * the system search path. Returns the full path to the library if it is
  1317. * found. Otherwise, the empty string is returned.
  1318. */
  1319. std::string cmSystemTools::FindLibrary(const char* name,
  1320. const std::vector<std::string>& userPaths)
  1321. {
  1322. // See if the executable exists as written.
  1323. if(cmSystemTools::FileExists(name))
  1324. {
  1325. return cmSystemTools::CollapseFullPath(name);
  1326. }
  1327. // Add the system search path to our path.
  1328. std::vector<std::string> path = userPaths;
  1329. cmSystemTools::GetPath(path);
  1330. std::string tryPath;
  1331. for(std::vector<std::string>::const_iterator p = path.begin();
  1332. p != path.end(); ++p)
  1333. {
  1334. #if defined(_WIN32) && !defined(__CYGWIN__)
  1335. tryPath = *p;
  1336. tryPath += "/";
  1337. tryPath += name;
  1338. tryPath += ".lib";
  1339. if(cmSystemTools::FileExists(tryPath.c_str()))
  1340. {
  1341. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1342. }
  1343. #else
  1344. tryPath = *p;
  1345. tryPath += "/lib";
  1346. tryPath += name;
  1347. tryPath += ".so";
  1348. if(cmSystemTools::FileExists(tryPath.c_str()))
  1349. {
  1350. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1351. }
  1352. tryPath = *p;
  1353. tryPath += "/lib";
  1354. tryPath += name;
  1355. tryPath += ".a";
  1356. if(cmSystemTools::FileExists(tryPath.c_str()))
  1357. {
  1358. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1359. }
  1360. tryPath = *p;
  1361. tryPath += "/lib";
  1362. tryPath += name;
  1363. tryPath += ".sl";
  1364. if(cmSystemTools::FileExists(tryPath.c_str()))
  1365. {
  1366. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1367. }
  1368. #endif
  1369. }
  1370. // Couldn't find the library.
  1371. return "";
  1372. }
  1373. bool cmSystemTools::FileIsDirectory(const char* name)
  1374. {
  1375. struct stat fs;
  1376. if(stat(name, &fs) == 0)
  1377. {
  1378. #if _WIN32
  1379. return ((fs.st_mode & _S_IFDIR) != 0);
  1380. #else
  1381. return S_ISDIR(fs.st_mode);
  1382. #endif
  1383. }
  1384. else
  1385. {
  1386. return false;
  1387. }
  1388. }
  1389. int cmSystemTools::ChangeDirectory(const char *dir)
  1390. {
  1391. return Chdir(dir);
  1392. }
  1393. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1394. {
  1395. char buf[2048];
  1396. std::string path = Getcwd(buf, 2048);
  1397. return path;
  1398. }
  1399. /**
  1400. * Given the path to a program executable, get the directory part of the path with the
  1401. * file stripped off. If there is no directory part, the empty string is returned.
  1402. */
  1403. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1404. {
  1405. std::string dir, file;
  1406. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1407. return dir;
  1408. }
  1409. /**
  1410. * Given the path to a program executable, get the directory part of the path
  1411. * with the file stripped off. If there is no directory part, the empty
  1412. * string is returned.
  1413. */
  1414. void cmSystemTools::SplitProgramPath(const char* in_name,
  1415. std::string& dir,
  1416. std::string& file)
  1417. {
  1418. dir = in_name;
  1419. file = "";
  1420. cmSystemTools::ConvertToUnixSlashes(dir);
  1421. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1422. {
  1423. std::string::size_type slashPos = dir.rfind("/");
  1424. if(slashPos != std::string::npos)
  1425. {
  1426. file = dir.substr(slashPos+1);
  1427. dir = dir.substr(0, slashPos);
  1428. }
  1429. else
  1430. {
  1431. file = dir;
  1432. dir = "";
  1433. }
  1434. }
  1435. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1436. {
  1437. std::string oldDir = in_name;
  1438. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1439. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1440. oldDir.c_str(), "\nDirectory not found: ",
  1441. dir.c_str());
  1442. dir = in_name;
  1443. return;
  1444. }
  1445. }
  1446. /**
  1447. * Given a path to a file or directory, convert it to a full path.
  1448. * This collapses away relative paths. The full path is returned.
  1449. */
  1450. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1451. {
  1452. std::string dir, file;
  1453. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1454. #ifdef _WIN32
  1455. // Ultra-hack warning:
  1456. // This changes to the target directory, saves the working directory,
  1457. // and then changes back to the original working directory.
  1458. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1459. if(dir != "") { Chdir(dir.c_str()); }
  1460. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1461. Chdir(cwd.c_str());
  1462. cmSystemTools::ConvertToUnixSlashes(newDir);
  1463. std::string newPath = newDir+"/"+file;
  1464. return newPath;
  1465. #else
  1466. # ifdef MAXPATHLEN
  1467. char resolved_name[MAXPATHLEN];
  1468. # else
  1469. # ifdef PATH_MAX
  1470. char resolved_name[PATH_MAX];
  1471. # else
  1472. char resolved_name[5024];
  1473. # endif
  1474. # endif
  1475. if(dir != "")
  1476. {
  1477. realpath(dir.c_str(), resolved_name);
  1478. dir = resolved_name;
  1479. }
  1480. else
  1481. {
  1482. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1483. }
  1484. if(file == "")
  1485. {
  1486. return dir;
  1487. }
  1488. return dir + "/" + file;
  1489. #endif
  1490. }
  1491. /**
  1492. * Return path of a full filename (no trailing slashes).
  1493. * Warning: returned path is converted to Unix slashes format.
  1494. */
  1495. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1496. {
  1497. std::string fn = filename;
  1498. cmSystemTools::ConvertToUnixSlashes(fn);
  1499. std::string::size_type slash_pos = fn.rfind("/");
  1500. if(slash_pos != std::string::npos)
  1501. {
  1502. return fn.substr(0, slash_pos);
  1503. }
  1504. else
  1505. {
  1506. return "";
  1507. }
  1508. }
  1509. /**
  1510. * Return file name of a full filename (i.e. file name without path).
  1511. */
  1512. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1513. {
  1514. std::string fn = filename;
  1515. cmSystemTools::ConvertToUnixSlashes(fn);
  1516. std::string::size_type slash_pos = fn.rfind("/");
  1517. if(slash_pos != std::string::npos)
  1518. {
  1519. return fn.substr(slash_pos + 1);
  1520. }
  1521. else
  1522. {
  1523. return filename;
  1524. }
  1525. }
  1526. /**
  1527. * Return file extension of a full filename (dot included).
  1528. * Warning: this is the longest extension (for example: .tar.gz)
  1529. */
  1530. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1531. {
  1532. std::string name = cmSystemTools::GetFilenameName(filename);
  1533. std::string::size_type dot_pos = name.find(".");
  1534. if(dot_pos != std::string::npos)
  1535. {
  1536. return name.substr(dot_pos);
  1537. }
  1538. else
  1539. {
  1540. return "";
  1541. }
  1542. }
  1543. /**
  1544. * Return file extension of a full filename (dot included).
  1545. */
  1546. std::string cmSystemTools::GetFilenameShortestExtension(const std::string& filename)
  1547. {
  1548. std::string name = cmSystemTools::GetFilenameName(filename);
  1549. std::string::size_type dot_pos = name.rfind(".");
  1550. if(dot_pos != std::string::npos)
  1551. {
  1552. return name.substr(dot_pos);
  1553. }
  1554. else
  1555. {
  1556. return "";
  1557. }
  1558. }
  1559. /**
  1560. * Return file name without extension of a full filename (i.e. without path).
  1561. * Warning: it considers the longest extension (for example: .tar.gz)
  1562. */
  1563. std::string cmSystemTools::GetFilenameNameWithoutExtension(const std::string& filename)
  1564. {
  1565. std::string name = cmSystemTools::GetFilenameName(filename);
  1566. std::string::size_type dot_pos = name.find(".");
  1567. if(dot_pos != std::string::npos)
  1568. {
  1569. return name.substr(0, dot_pos);
  1570. }
  1571. else
  1572. {
  1573. return name;
  1574. }
  1575. }
  1576. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1577. std::vector<std::string>& files)
  1578. {
  1579. cmDirectory d;
  1580. cmRegularExpression reg(regexp);
  1581. if (d.Load(directory))
  1582. {
  1583. size_t numf;
  1584. unsigned int i;
  1585. numf = d.GetNumberOfFiles();
  1586. for (i = 0; i < numf; i++)
  1587. {
  1588. std::string fname = d.GetFile(i);
  1589. if (reg.find(fname))
  1590. {
  1591. files.push_back(fname);
  1592. }
  1593. }
  1594. }
  1595. }
  1596. void cmSystemTools::GlobDirs(const char *fullPath,
  1597. std::vector<std::string>& files)
  1598. {
  1599. std::string path = fullPath;
  1600. std::string::size_type pos = path.find("/*");
  1601. if(pos == std::string::npos)
  1602. {
  1603. files.push_back(fullPath);
  1604. return;
  1605. }
  1606. std::string startPath = path.substr(0, pos);
  1607. std::string finishPath = path.substr(pos+2);
  1608. cmDirectory d;
  1609. if (d.Load(startPath.c_str()))
  1610. {
  1611. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1612. {
  1613. if((std::string(d.GetFile(i)) != ".")
  1614. && (std::string(d.GetFile(i)) != ".."))
  1615. {
  1616. std::string fname = startPath;
  1617. fname +="/";
  1618. fname += d.GetFile(i);
  1619. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1620. {
  1621. fname += finishPath;
  1622. cmSystemTools::GlobDirs(fname.c_str(), files);
  1623. }
  1624. }
  1625. }
  1626. }
  1627. }
  1628. void cmSystemTools::ExpandListArguments(std::vector<std::string> const& arguments,
  1629. std::vector<std::string>& newargs)
  1630. {
  1631. std::vector<std::string>::const_iterator i;
  1632. for(i = arguments.begin();i != arguments.end(); ++i)
  1633. {
  1634. // if there are no ; in the name then just copy the current string
  1635. if(i->find(';') == std::string::npos)
  1636. {
  1637. newargs.push_back(*i);
  1638. }
  1639. else
  1640. {
  1641. std::string::size_type start = 0;
  1642. std::string::size_type endpos = 0;
  1643. const std::string::size_type size = i->size();
  1644. // break up ; separated sections of the string into separate strings
  1645. while(endpos != size)
  1646. {
  1647. endpos = i->find(';', start);
  1648. if(endpos == std::string::npos)
  1649. {
  1650. endpos = i->size();
  1651. }
  1652. std::string::size_type len = endpos - start;
  1653. if (len > 0)
  1654. {
  1655. // check for a closing ] after the start position
  1656. if(i->find('[', start) == std::string::npos)
  1657. {
  1658. // if there is no [ in the string then keep it
  1659. newargs.push_back(i->substr(start, len));
  1660. }
  1661. else
  1662. {
  1663. int opencount = 0;
  1664. int closecount = 0;
  1665. for(std::string::size_type j = start; j < endpos; ++j)
  1666. {
  1667. if(i->at(j) == '[')
  1668. {
  1669. ++opencount;
  1670. }
  1671. else if (i->at(j) == ']')
  1672. {
  1673. ++closecount;
  1674. }
  1675. }
  1676. if(opencount != closecount)
  1677. {
  1678. // skip this one
  1679. endpos = i->find(';', endpos+1);
  1680. if(endpos == std::string::npos)
  1681. {
  1682. endpos = i->size();
  1683. }
  1684. len = endpos - start;
  1685. }
  1686. newargs.push_back(i->substr(start, len));
  1687. }
  1688. }
  1689. start = endpos+1;
  1690. }
  1691. }
  1692. }
  1693. }
  1694. bool cmSystemTools::GetShortPath(const char* path, std::string& shortPath)
  1695. {
  1696. #if defined(WIN32) && !defined(__CYGWIN__)
  1697. const int size = int(strlen(path)) +1; // size of return
  1698. char *buffer = new char[size]; // create a buffer
  1699. buffer[0] = 0;
  1700. int ret = GetShortPathName(path, buffer, size);
  1701. if(buffer[0] == 0 || ret > size)
  1702. {
  1703. if(ret < size)
  1704. {
  1705. LPVOID lpMsgBuf;
  1706. FormatMessage(
  1707. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1708. FORMAT_MESSAGE_FROM_SYSTEM |
  1709. FORMAT_MESSAGE_IGNORE_INSERTS,
  1710. NULL,
  1711. GetLastError(),
  1712. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  1713. (LPTSTR) &lpMsgBuf,
  1714. 0,
  1715. NULL
  1716. );
  1717. cmSystemTools::Error((LPCTSTR)lpMsgBuf);
  1718. LocalFree( lpMsgBuf );
  1719. }
  1720. cmSystemTools::Error("Unable to get a short path: ", path);
  1721. return false;
  1722. }
  1723. else
  1724. {
  1725. shortPath = buffer;
  1726. delete [] buffer;
  1727. return true;
  1728. }
  1729. #else
  1730. shortPath = path;
  1731. return true;
  1732. #endif
  1733. }