cmSystemTools.cxx 49 KB

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