cmSystemTools.cxx 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  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. std::ifstream finSource(source);
  884. std::ifstream finDestination(destination);
  885. if(!finSource || !finDestination)
  886. {
  887. return true;
  888. }
  889. const int buffer_length = 4096;
  890. char bufferSource[buffer_length];
  891. char bufferDest[buffer_length];
  892. while(finSource && finDestination)
  893. {
  894. if(finSource.getline(bufferSource, buffer_length, '\n')
  895. || finSource.gcount())
  896. {
  897. if(finDestination.getline(bufferDest, buffer_length, '\n')
  898. || finDestination.gcount())
  899. {
  900. // both if statements passed
  901. if(finSource.eof())
  902. {
  903. if(!finDestination.eof())
  904. {
  905. return true;
  906. }
  907. if(finSource.gcount() != finDestination.gcount())
  908. {
  909. return true;
  910. }
  911. if(strncmp(bufferSource, bufferDest, finSource.gcount()) != 0)
  912. {
  913. return true;
  914. }
  915. }
  916. else if(finSource.fail())
  917. {
  918. if(!finDestination.fail())
  919. {
  920. return true;
  921. }
  922. if(strcmp(bufferSource, bufferDest) != 0)
  923. {
  924. return true;
  925. }
  926. finSource.clear(finSource.rdstate() & ~std::ios::failbit);
  927. finDestination.clear(finDestination.rdstate() & ~std::ios::failbit);
  928. }
  929. else
  930. {
  931. if(strcmp(bufferSource, bufferDest) != 0)
  932. {
  933. return true;
  934. }
  935. }
  936. }
  937. else
  938. {
  939. return true;
  940. }
  941. }
  942. }
  943. return false;
  944. }
  945. /**
  946. * Copy a file named by "source" to the file named by "destination".
  947. */
  948. void cmSystemTools::cmCopyFile(const char* source,
  949. const char* destination)
  950. {
  951. const int bufferSize = 4096;
  952. char buffer[bufferSize];
  953. std::ifstream fin(source,
  954. #ifdef _WIN32
  955. std::ios::binary |
  956. #endif
  957. std::ios::in);
  958. if(!fin)
  959. {
  960. cmSystemTools::Error("CopyFile failed to open input file \"",
  961. source, "\"");
  962. return;
  963. }
  964. // If destination is a directory, try to create a file with the same
  965. // name as the source in that directory.
  966. const char* dest = destination;
  967. std::string new_destination;
  968. if(cmSystemTools::FileExists(destination) &&
  969. cmSystemTools::FileIsDirectory(destination))
  970. {
  971. new_destination = destination;
  972. cmSystemTools::ConvertToUnixSlashes(new_destination);
  973. new_destination += '/';
  974. std::string source_name = source;
  975. new_destination += cmSystemTools::GetFilenameName(source_name);
  976. dest = new_destination.c_str();
  977. }
  978. // Create destination directory
  979. std::string destination_dir = dest;
  980. destination_dir = cmSystemTools::GetFilenamePath(destination_dir);
  981. cmSystemTools::MakeDirectory(destination_dir.c_str());
  982. std::ofstream fout(dest,
  983. #ifdef _WIN32
  984. std::ios::binary |
  985. #endif
  986. std::ios::out | std::ios::trunc);
  987. if(!fout)
  988. {
  989. cmSystemTools::Error("CopyFile failed to open output file \"",
  990. dest, "\"");
  991. return;
  992. }
  993. // This copy loop is very sensitive on certain platforms with
  994. // slightly broken stream libraries (like HPUX). Normally, it is
  995. // incorrect to not check the error condition on the fin.read()
  996. // before using the data, but the fin.gcount() will be zero if an
  997. // error occurred. Therefore, the loop should be safe everywhere.
  998. while(fin)
  999. {
  1000. fin.read(buffer, bufferSize);
  1001. if(fin.gcount())
  1002. {
  1003. fout.write(buffer, fin.gcount());
  1004. }
  1005. }
  1006. }
  1007. // return true if the file exists
  1008. long int cmSystemTools::ModifiedTime(const char* filename)
  1009. {
  1010. struct stat fs;
  1011. if (stat(filename, &fs) != 0)
  1012. {
  1013. return 0;
  1014. }
  1015. else
  1016. {
  1017. return (long int)fs.st_mtime;
  1018. }
  1019. }
  1020. bool cmSystemTools::RemoveFile(const char* source)
  1021. {
  1022. return unlink(source) != 0 ? false : true;
  1023. }
  1024. bool cmSystemTools::IsOn(const char* val)
  1025. {
  1026. if (!val)
  1027. {
  1028. return false;
  1029. }
  1030. std::basic_string<char> v = val;
  1031. for(std::basic_string<char>::iterator c = v.begin();
  1032. c != v.end(); c++)
  1033. {
  1034. *c = toupper(*c);
  1035. }
  1036. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  1037. }
  1038. bool cmSystemTools::IsOff(const char* val)
  1039. {
  1040. if (!val || strlen(val) == 0)
  1041. {
  1042. return true;
  1043. }
  1044. std::basic_string<char> v = val;
  1045. for(std::basic_string<char>::iterator c = v.begin();
  1046. c != v.end(); c++)
  1047. {
  1048. *c = toupper(*c);
  1049. }
  1050. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  1051. v == "N" || v == "NOTFOUND" || v == "IGNORE");
  1052. }
  1053. bool cmSystemTools::RunCommand(const char* command,
  1054. std::string& output,
  1055. const char* dir,
  1056. bool verbose)
  1057. {
  1058. int foo;
  1059. return cmSystemTools::RunCommand(command, output, foo, dir, verbose);
  1060. }
  1061. #if defined(WIN32) && !defined(__CYGWIN__)
  1062. // use this for shell commands like echo and dir
  1063. bool RunCommandViaSystem(const char* command,
  1064. const char* dir,
  1065. std::string& output,
  1066. int& retVal,
  1067. bool verbose)
  1068. {
  1069. const int BUFFER_SIZE = 4096;
  1070. char buffer[BUFFER_SIZE];
  1071. std::string commandInDir;
  1072. if(dir)
  1073. {
  1074. commandInDir = "cd ";
  1075. commandInDir += dir;
  1076. commandInDir += " && ";
  1077. commandInDir += command;
  1078. }
  1079. else
  1080. {
  1081. commandInDir = command;
  1082. }
  1083. command = commandInDir.c_str();
  1084. std::string commandToFile = command;
  1085. commandToFile += " > ";
  1086. std::string tempFile;
  1087. tempFile += _tempnam(0, "cmake");
  1088. commandToFile += tempFile;
  1089. retVal = system(commandToFile.c_str());
  1090. std::ifstream fin(tempFile.c_str());
  1091. if(!fin)
  1092. {
  1093. if(verbose)
  1094. {
  1095. std::string errormsg = "RunCommand produced no output: command: \"";
  1096. errormsg += command;
  1097. errormsg += "\"";
  1098. errormsg += "\nOutput file: ";
  1099. errormsg += tempFile;
  1100. cmSystemTools::Error(errormsg.c_str());
  1101. }
  1102. fin.close();
  1103. cmSystemTools::RemoveFile(tempFile.c_str());
  1104. return false;
  1105. }
  1106. bool multiLine = false;
  1107. while(fin)
  1108. {
  1109. fin.getline(buffer, BUFFER_SIZE);
  1110. output += buffer;
  1111. if(multiLine)
  1112. {
  1113. output += "\n";
  1114. }
  1115. multiLine = true;
  1116. }
  1117. fin.close();
  1118. cmSystemTools::RemoveFile(tempFile.c_str());
  1119. return true;
  1120. }
  1121. #endif // endif WIN32 not CYGWIN
  1122. // run a command unix uses popen (easy)
  1123. // windows uses system and ShortPath
  1124. bool cmSystemTools::RunCommand(const char* command,
  1125. std::string& output,
  1126. int &retVal,
  1127. const char* dir,
  1128. bool verbose)
  1129. {
  1130. if(s_DisableRunCommandOutput)
  1131. {
  1132. verbose = false;
  1133. }
  1134. #if defined(WIN32) && !defined(__CYGWIN__)
  1135. // if the command does not start with a quote, then
  1136. // try to find the program, and if the program can not be
  1137. // found use system to run the command as it must be a built in
  1138. // shell command like echo or dir
  1139. int count = 0;
  1140. if(command[0] == '\"')
  1141. {
  1142. // count the number of quotes
  1143. for(const char* s = command; *s != 0; ++s)
  1144. {
  1145. if(*s == '\"')
  1146. {
  1147. count++;
  1148. if(count > 2)
  1149. {
  1150. break;
  1151. }
  1152. }
  1153. }
  1154. // if there are more than two double quotes use
  1155. // GetShortPathName, the cmd.exe program in windows which
  1156. // is used by system fails to execute if there are more than
  1157. // one set of quotes in the arguments
  1158. if(count > 2)
  1159. {
  1160. cmRegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  1161. if(quoted.find(command))
  1162. {
  1163. std::string shortCmd;
  1164. std::string cmd = quoted.match(1);
  1165. std::string args = quoted.match(2);
  1166. if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  1167. {
  1168. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  1169. return false;
  1170. }
  1171. shortCmd += " ";
  1172. shortCmd += args;
  1173. return RunCommandViaSystem(shortCmd.c_str(), dir,
  1174. output, retVal, verbose);
  1175. }
  1176. else
  1177. {
  1178. cmSystemTools::Error("Could not parse command line with quotes ",
  1179. command);
  1180. }
  1181. }
  1182. }
  1183. // if there is only one set of quotes or no quotes then just run the command
  1184. return RunCommandViaSystem(command, dir, output, retVal, verbose);
  1185. #else
  1186. // if only popen worked on windows.....
  1187. std::string commandInDir;
  1188. if(dir)
  1189. {
  1190. commandInDir = "cd ";
  1191. commandInDir += dir;
  1192. commandInDir += " && ";
  1193. commandInDir += command;
  1194. }
  1195. else
  1196. {
  1197. commandInDir = command;
  1198. }
  1199. command = commandInDir.c_str();
  1200. const int BUFFER_SIZE = 4096;
  1201. char buffer[BUFFER_SIZE];
  1202. if(verbose)
  1203. {
  1204. std::cout << "running " << command << std::endl;
  1205. }
  1206. fflush(stdout);
  1207. fflush(stderr);
  1208. FILE* cpipe = popen(command, "r");
  1209. if(!cpipe)
  1210. {
  1211. return false;
  1212. }
  1213. fgets(buffer, BUFFER_SIZE, cpipe);
  1214. while(!feof(cpipe))
  1215. {
  1216. if(verbose)
  1217. {
  1218. std::cout << buffer << std::flush;
  1219. }
  1220. output += buffer;
  1221. fgets(buffer, BUFFER_SIZE, cpipe);
  1222. }
  1223. retVal = pclose(cpipe);
  1224. retVal = WEXITSTATUS(retVal);
  1225. return true;
  1226. #endif
  1227. }
  1228. /**
  1229. * Find the file the given name. Searches the given path and then
  1230. * the system search path. Returns the full path to the file if it is
  1231. * found. Otherwise, the empty string is returned.
  1232. */
  1233. std::string cmSystemTools::FindFile(const char* name,
  1234. const std::vector<std::string>& userPaths)
  1235. {
  1236. // Add the system search path to our path.
  1237. std::vector<std::string> path = userPaths;
  1238. cmSystemTools::GetPath(path);
  1239. std::string tryPath;
  1240. for(std::vector<std::string>::const_iterator p = path.begin();
  1241. p != path.end(); ++p)
  1242. {
  1243. tryPath = *p;
  1244. tryPath += "/";
  1245. tryPath += name;
  1246. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1247. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1248. {
  1249. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1250. }
  1251. }
  1252. // Couldn't find the file.
  1253. return "";
  1254. }
  1255. /**
  1256. * Find the executable with the given name. Searches the given path and then
  1257. * the system search path. Returns the full path to the executable if it is
  1258. * found. Otherwise, the empty string is returned.
  1259. */
  1260. std::string cmSystemTools::FindProgram(const char* name,
  1261. const std::vector<std::string>& userPaths)
  1262. {
  1263. // See if the executable exists as written.
  1264. if(cmSystemTools::FileExists(name) &&
  1265. !cmSystemTools::FileIsDirectory(name))
  1266. {
  1267. return cmSystemTools::CollapseFullPath(name);
  1268. }
  1269. std::string tryPath = name;
  1270. tryPath += cmSystemTools::GetExecutableExtension();
  1271. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1272. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1273. {
  1274. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1275. }
  1276. // Add the system search path to our path.
  1277. std::vector<std::string> path = userPaths;
  1278. cmSystemTools::GetPath(path);
  1279. for(std::vector<std::string>::const_iterator p = path.begin();
  1280. p != path.end(); ++p)
  1281. {
  1282. tryPath = *p;
  1283. tryPath += "/";
  1284. tryPath += name;
  1285. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1286. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1287. {
  1288. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1289. }
  1290. #ifdef _WIN32
  1291. tryPath += ".com";
  1292. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1293. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1294. {
  1295. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1296. }
  1297. tryPath = *p;
  1298. tryPath += "/";
  1299. tryPath += name;
  1300. #endif
  1301. tryPath += cmSystemTools::GetExecutableExtension();
  1302. if(cmSystemTools::FileExists(tryPath.c_str()) &&
  1303. !cmSystemTools::FileIsDirectory(tryPath.c_str()))
  1304. {
  1305. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1306. }
  1307. }
  1308. // Couldn't find the program.
  1309. return "";
  1310. }
  1311. /**
  1312. * Find the library with the given name. Searches the given path and then
  1313. * the system search path. Returns the full path to the library if it is
  1314. * found. Otherwise, the empty string is returned.
  1315. */
  1316. std::string cmSystemTools::FindLibrary(const char* name,
  1317. const std::vector<std::string>& userPaths)
  1318. {
  1319. // See if the executable exists as written.
  1320. if(cmSystemTools::FileExists(name))
  1321. {
  1322. return cmSystemTools::CollapseFullPath(name);
  1323. }
  1324. // Add the system search path to our path.
  1325. std::vector<std::string> path = userPaths;
  1326. cmSystemTools::GetPath(path);
  1327. std::string tryPath;
  1328. for(std::vector<std::string>::const_iterator p = path.begin();
  1329. p != path.end(); ++p)
  1330. {
  1331. #if defined(_WIN32) && !defined(__CYGWIN__)
  1332. tryPath = *p;
  1333. tryPath += "/";
  1334. tryPath += name;
  1335. tryPath += ".lib";
  1336. if(cmSystemTools::FileExists(tryPath.c_str()))
  1337. {
  1338. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1339. }
  1340. #else
  1341. tryPath = *p;
  1342. tryPath += "/lib";
  1343. tryPath += name;
  1344. tryPath += ".so";
  1345. if(cmSystemTools::FileExists(tryPath.c_str()))
  1346. {
  1347. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1348. }
  1349. tryPath = *p;
  1350. tryPath += "/lib";
  1351. tryPath += name;
  1352. tryPath += ".a";
  1353. if(cmSystemTools::FileExists(tryPath.c_str()))
  1354. {
  1355. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1356. }
  1357. tryPath = *p;
  1358. tryPath += "/lib";
  1359. tryPath += name;
  1360. tryPath += ".sl";
  1361. if(cmSystemTools::FileExists(tryPath.c_str()))
  1362. {
  1363. return cmSystemTools::CollapseFullPath(tryPath.c_str());
  1364. }
  1365. #endif
  1366. }
  1367. // Couldn't find the library.
  1368. return "";
  1369. }
  1370. bool cmSystemTools::FileIsDirectory(const char* name)
  1371. {
  1372. struct stat fs;
  1373. if(stat(name, &fs) == 0)
  1374. {
  1375. #if _WIN32
  1376. return ((fs.st_mode & _S_IFDIR) != 0);
  1377. #else
  1378. return S_ISDIR(fs.st_mode);
  1379. #endif
  1380. }
  1381. else
  1382. {
  1383. return false;
  1384. }
  1385. }
  1386. int cmSystemTools::ChangeDirectory(const char *dir)
  1387. {
  1388. return Chdir(dir);
  1389. }
  1390. std::string cmSystemTools::GetCurrentWorkingDirectory()
  1391. {
  1392. char buf[2048];
  1393. std::string path = Getcwd(buf, 2048);
  1394. return path;
  1395. }
  1396. /**
  1397. * Given the path to a program executable, get the directory part of the path with the
  1398. * file stripped off. If there is no directory part, the empty string is returned.
  1399. */
  1400. std::string cmSystemTools::GetProgramPath(const char* in_name)
  1401. {
  1402. std::string dir, file;
  1403. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1404. return dir;
  1405. }
  1406. /**
  1407. * Given the path to a program executable, get the directory part of the path
  1408. * with the file stripped off. If there is no directory part, the empty
  1409. * string is returned.
  1410. */
  1411. void cmSystemTools::SplitProgramPath(const char* in_name,
  1412. std::string& dir,
  1413. std::string& file)
  1414. {
  1415. dir = in_name;
  1416. file = "";
  1417. cmSystemTools::ConvertToUnixSlashes(dir);
  1418. if(!cmSystemTools::FileIsDirectory(dir.c_str()))
  1419. {
  1420. std::string::size_type slashPos = dir.rfind("/");
  1421. if(slashPos != std::string::npos)
  1422. {
  1423. file = dir.substr(slashPos+1);
  1424. dir = dir.substr(0, slashPos);
  1425. }
  1426. else
  1427. {
  1428. file = dir;
  1429. dir = "";
  1430. }
  1431. }
  1432. if((dir != "") && !cmSystemTools::FileIsDirectory(dir.c_str()))
  1433. {
  1434. std::string oldDir = in_name;
  1435. cmSystemTools::ConvertToUnixSlashes(oldDir);
  1436. cmSystemTools::Error("Error splitting file name off end of path:\n",
  1437. oldDir.c_str(), "\nDirectory not found: ",
  1438. dir.c_str());
  1439. dir = in_name;
  1440. return;
  1441. }
  1442. }
  1443. /**
  1444. * Given a path to a file or directory, convert it to a full path.
  1445. * This collapses away relative paths. The full path is returned.
  1446. */
  1447. std::string cmSystemTools::CollapseFullPath(const char* in_name)
  1448. {
  1449. std::string dir, file;
  1450. cmSystemTools::SplitProgramPath(in_name, dir, file);
  1451. #ifdef _WIN32
  1452. // Ultra-hack warning:
  1453. // This changes to the target directory, saves the working directory,
  1454. // and then changes back to the original working directory.
  1455. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1456. if(dir != "") { Chdir(dir.c_str()); }
  1457. std::string newDir = cmSystemTools::GetCurrentWorkingDirectory();
  1458. Chdir(cwd.c_str());
  1459. cmSystemTools::ConvertToUnixSlashes(newDir);
  1460. std::string newPath = newDir+"/"+file;
  1461. return newPath;
  1462. #else
  1463. # ifdef MAXPATHLEN
  1464. char resolved_name[MAXPATHLEN];
  1465. # else
  1466. # ifdef PATH_MAX
  1467. char resolved_name[PATH_MAX];
  1468. # else
  1469. char resolved_name[5024];
  1470. # endif
  1471. # endif
  1472. if(dir != "")
  1473. {
  1474. realpath(dir.c_str(), resolved_name);
  1475. dir = resolved_name;
  1476. }
  1477. else
  1478. {
  1479. dir = cmSystemTools::GetCurrentWorkingDirectory();
  1480. }
  1481. if(file == "")
  1482. {
  1483. return dir;
  1484. }
  1485. return dir + "/" + file;
  1486. #endif
  1487. }
  1488. /**
  1489. * Return path of a full filename (no trailing slashes).
  1490. * Warning: returned path is converted to Unix slashes format.
  1491. */
  1492. std::string cmSystemTools::GetFilenamePath(const std::string& filename)
  1493. {
  1494. std::string fn = filename;
  1495. cmSystemTools::ConvertToUnixSlashes(fn);
  1496. std::string::size_type slash_pos = fn.rfind("/");
  1497. if(slash_pos != std::string::npos)
  1498. {
  1499. return fn.substr(0, slash_pos);
  1500. }
  1501. else
  1502. {
  1503. return "";
  1504. }
  1505. }
  1506. /**
  1507. * Return file name of a full filename (i.e. file name without path).
  1508. */
  1509. std::string cmSystemTools::GetFilenameName(const std::string& filename)
  1510. {
  1511. std::string fn = filename;
  1512. cmSystemTools::ConvertToUnixSlashes(fn);
  1513. std::string::size_type slash_pos = fn.rfind("/");
  1514. if(slash_pos != std::string::npos)
  1515. {
  1516. return fn.substr(slash_pos + 1);
  1517. }
  1518. else
  1519. {
  1520. return filename;
  1521. }
  1522. }
  1523. /**
  1524. * Return file extension of a full filename (dot included).
  1525. * Warning: this is the longest extension (for example: .tar.gz)
  1526. */
  1527. std::string cmSystemTools::GetFilenameExtension(const std::string& filename)
  1528. {
  1529. std::string name = cmSystemTools::GetFilenameName(filename);
  1530. std::string::size_type dot_pos = name.find(".");
  1531. if(dot_pos != std::string::npos)
  1532. {
  1533. return name.substr(dot_pos);
  1534. }
  1535. else
  1536. {
  1537. return "";
  1538. }
  1539. }
  1540. /**
  1541. * Return file extension of a full filename (dot included).
  1542. */
  1543. std::string cmSystemTools::GetFilenameShortestExtension(const std::string& filename)
  1544. {
  1545. std::string name = cmSystemTools::GetFilenameName(filename);
  1546. std::string::size_type dot_pos = name.rfind(".");
  1547. if(dot_pos != std::string::npos)
  1548. {
  1549. return name.substr(dot_pos);
  1550. }
  1551. else
  1552. {
  1553. return "";
  1554. }
  1555. }
  1556. /**
  1557. * Return file name without extension of a full filename (i.e. without path).
  1558. * Warning: it considers the longest extension (for example: .tar.gz)
  1559. */
  1560. std::string cmSystemTools::GetFilenameNameWithoutExtension(const std::string& filename)
  1561. {
  1562. std::string name = cmSystemTools::GetFilenameName(filename);
  1563. std::string::size_type dot_pos = name.find(".");
  1564. if(dot_pos != std::string::npos)
  1565. {
  1566. return name.substr(0, dot_pos);
  1567. }
  1568. else
  1569. {
  1570. return name;
  1571. }
  1572. }
  1573. void cmSystemTools::Glob(const char *directory, const char *regexp,
  1574. std::vector<std::string>& files)
  1575. {
  1576. cmDirectory d;
  1577. cmRegularExpression reg(regexp);
  1578. if (d.Load(directory))
  1579. {
  1580. size_t numf;
  1581. unsigned int i;
  1582. numf = d.GetNumberOfFiles();
  1583. for (i = 0; i < numf; i++)
  1584. {
  1585. std::string fname = d.GetFile(i);
  1586. if (reg.find(fname))
  1587. {
  1588. files.push_back(fname);
  1589. }
  1590. }
  1591. }
  1592. }
  1593. void cmSystemTools::GlobDirs(const char *fullPath,
  1594. std::vector<std::string>& files)
  1595. {
  1596. std::string path = fullPath;
  1597. std::string::size_type pos = path.find("/*");
  1598. if(pos == std::string::npos)
  1599. {
  1600. files.push_back(fullPath);
  1601. return;
  1602. }
  1603. std::string startPath = path.substr(0, pos);
  1604. std::string finishPath = path.substr(pos+2);
  1605. cmDirectory d;
  1606. if (d.Load(startPath.c_str()))
  1607. {
  1608. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1609. {
  1610. if((std::string(d.GetFile(i)) != ".")
  1611. && (std::string(d.GetFile(i)) != ".."))
  1612. {
  1613. std::string fname = startPath;
  1614. fname +="/";
  1615. fname += d.GetFile(i);
  1616. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1617. {
  1618. fname += finishPath;
  1619. cmSystemTools::GlobDirs(fname.c_str(), files);
  1620. }
  1621. }
  1622. }
  1623. }
  1624. }
  1625. void cmSystemTools::ExpandListArguments(std::vector<std::string> const& arguments,
  1626. std::vector<std::string>& newargs)
  1627. {
  1628. std::vector<std::string>::const_iterator i;
  1629. for(i = arguments.begin();i != arguments.end(); ++i)
  1630. {
  1631. // if there are no ; in the name then just copy the current string
  1632. if(i->find(';') == std::string::npos)
  1633. {
  1634. newargs.push_back(*i);
  1635. }
  1636. else
  1637. {
  1638. std::string::size_type start = 0;
  1639. std::string::size_type endpos = 0;
  1640. const std::string::size_type size = i->size();
  1641. // break up ; separated sections of the string into separate strings
  1642. while(endpos != size)
  1643. {
  1644. endpos = i->find(';', start);
  1645. if(endpos == std::string::npos)
  1646. {
  1647. endpos = i->size();
  1648. }
  1649. std::string::size_type len = endpos - start;
  1650. if (len > 0)
  1651. {
  1652. // check for a closing ] after the start position
  1653. if(i->find('[', start) == std::string::npos)
  1654. {
  1655. // if there is no [ in the string then keep it
  1656. newargs.push_back(i->substr(start, len));
  1657. }
  1658. else
  1659. {
  1660. int opencount = 0;
  1661. int closecount = 0;
  1662. for(std::string::size_type j = start; j < endpos; ++j)
  1663. {
  1664. if(i->at(j) == '[')
  1665. {
  1666. ++opencount;
  1667. }
  1668. else if (i->at(j) == ']')
  1669. {
  1670. ++closecount;
  1671. }
  1672. }
  1673. if(opencount != closecount)
  1674. {
  1675. // skip this one
  1676. endpos = i->find(';', endpos+1);
  1677. if(endpos == std::string::npos)
  1678. {
  1679. endpos = i->size();
  1680. }
  1681. len = endpos - start;
  1682. }
  1683. newargs.push_back(i->substr(start, len));
  1684. }
  1685. }
  1686. start = endpos+1;
  1687. }
  1688. }
  1689. }
  1690. }
  1691. bool cmSystemTools::GetShortPath(const char* path, std::string& shortPath)
  1692. {
  1693. #if defined(WIN32) && !defined(__CYGWIN__)
  1694. const int size = int(strlen(path)) +1; // size of return
  1695. char *buffer = new char[size]; // create a buffer
  1696. buffer[0] = 0;
  1697. int ret = GetShortPathName(path, buffer, size);
  1698. if(buffer[0] == 0 || ret > size)
  1699. {
  1700. if(ret < size)
  1701. {
  1702. LPVOID lpMsgBuf;
  1703. FormatMessage(
  1704. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1705. FORMAT_MESSAGE_FROM_SYSTEM |
  1706. FORMAT_MESSAGE_IGNORE_INSERTS,
  1707. NULL,
  1708. GetLastError(),
  1709. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  1710. (LPTSTR) &lpMsgBuf,
  1711. 0,
  1712. NULL
  1713. );
  1714. cmSystemTools::Error((LPCTSTR)lpMsgBuf);
  1715. LocalFree( lpMsgBuf );
  1716. }
  1717. cmSystemTools::Error("Unable to get a short path: ", path);
  1718. return false;
  1719. }
  1720. else
  1721. {
  1722. shortPath = buffer;
  1723. delete [] buffer;
  1724. return true;
  1725. }
  1726. #else
  1727. shortPath = path;
  1728. return true;
  1729. #endif
  1730. }