SystemTools.hxx 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
  3. #ifndef cmsys_SystemTools_hxx
  4. #define cmsys_SystemTools_hxx
  5. #include <cmsys/Configure.hxx>
  6. #include <iosfwd>
  7. #include <map>
  8. #include <string>
  9. #include <vector>
  10. #include <cmsys/String.hxx>
  11. #include <sys/types.h>
  12. // include sys/stat.h after sys/types.h
  13. #include <sys/stat.h>
  14. #if !defined(_WIN32) || defined(__CYGWIN__)
  15. #include <unistd.h> // For access permissions for use with access()
  16. #endif
  17. // Required for va_list
  18. #include <stdarg.h>
  19. // Required for FILE*
  20. #include <stdio.h>
  21. #if !defined(va_list)
  22. // Some compilers move va_list into the std namespace and there is no way to
  23. // tell that this has been done. Playing with things being included before or
  24. // after stdarg.h does not solve things because we do not have control over
  25. // what the user does. This hack solves this problem by moving va_list to our
  26. // own namespace that is local for kwsys.
  27. namespace std {
  28. } // Required for platforms that do not have std namespace
  29. namespace cmsys_VA_LIST {
  30. using namespace std;
  31. typedef va_list hack_va_list;
  32. }
  33. namespace cmsys {
  34. typedef cmsys_VA_LIST::hack_va_list va_list;
  35. }
  36. #endif // va_list
  37. namespace cmsys {
  38. class SystemToolsTranslationMap;
  39. class SystemToolsPathCaseMap;
  40. class SystemToolsEnvMap;
  41. /** \class SystemToolsManager
  42. * \brief Use to make sure SystemTools is initialized before it is used
  43. * and is the last static object destroyed
  44. */
  45. class cmsys_EXPORT SystemToolsManager
  46. {
  47. public:
  48. SystemToolsManager();
  49. ~SystemToolsManager();
  50. };
  51. // This instance will show up in any translation unit that uses
  52. // SystemTools. It will make sure SystemTools is initialized
  53. // before it is used and is the last static object destroyed.
  54. static SystemToolsManager SystemToolsManagerInstance;
  55. // Flags for use with TestFileAccess. Use a typedef in case any operating
  56. // system in the future needs a special type. These are flags that may be
  57. // combined using the | operator.
  58. typedef int TestFilePermissions;
  59. #if defined(_WIN32) && !defined(__CYGWIN__)
  60. // On Windows (VC and Borland), no system header defines these constants...
  61. static const TestFilePermissions TEST_FILE_OK = 0;
  62. static const TestFilePermissions TEST_FILE_READ = 4;
  63. static const TestFilePermissions TEST_FILE_WRITE = 2;
  64. static const TestFilePermissions TEST_FILE_EXECUTE = 1;
  65. #else
  66. // Standard POSIX constants
  67. static const TestFilePermissions TEST_FILE_OK = F_OK;
  68. static const TestFilePermissions TEST_FILE_READ = R_OK;
  69. static const TestFilePermissions TEST_FILE_WRITE = W_OK;
  70. static const TestFilePermissions TEST_FILE_EXECUTE = X_OK;
  71. #endif
  72. /** \class SystemTools
  73. * \brief A collection of useful platform-independent system functions.
  74. */
  75. class cmsys_EXPORT SystemTools
  76. {
  77. public:
  78. /** -----------------------------------------------------------------
  79. * String Manipulation Routines
  80. * -----------------------------------------------------------------
  81. */
  82. /**
  83. * Replace symbols in str that are not valid in C identifiers as
  84. * defined by the 1999 standard, ie. anything except [A-Za-z0-9_].
  85. * They are replaced with `_' and if the first character is a digit
  86. * then an underscore is prepended. Note that this can produce
  87. * identifiers that the standard reserves (_[A-Z].* and __.*).
  88. */
  89. static std::string MakeCidentifier(const std::string& s);
  90. static std::string MakeCindentifier(const std::string& s)
  91. {
  92. return MakeCidentifier(s);
  93. }
  94. /**
  95. * Replace replace all occurrences of the string in the source string.
  96. */
  97. static void ReplaceString(std::string& source, const char* replace,
  98. const char* with);
  99. static void ReplaceString(std::string& source, const std::string& replace,
  100. const std::string& with);
  101. /**
  102. * Return a capitalized string (i.e the first letter is uppercased,
  103. * all other are lowercased).
  104. */
  105. static std::string Capitalized(const std::string&);
  106. /**
  107. * Return a 'capitalized words' string (i.e the first letter of each word
  108. * is uppercased all other are left untouched though).
  109. */
  110. static std::string CapitalizedWords(const std::string&);
  111. /**
  112. * Return a 'uncapitalized words' string (i.e the first letter of each word
  113. * is lowercased all other are left untouched though).
  114. */
  115. static std::string UnCapitalizedWords(const std::string&);
  116. /**
  117. * Return a lower case string
  118. */
  119. static std::string LowerCase(const std::string&);
  120. /**
  121. * Return a lower case string
  122. */
  123. static std::string UpperCase(const std::string&);
  124. /**
  125. * Count char in string
  126. */
  127. static size_t CountChar(const char* str, char c);
  128. /**
  129. * Remove some characters from a string.
  130. * Return a pointer to the new resulting string (allocated with 'new')
  131. */
  132. static char* RemoveChars(const char* str, const char* toremove);
  133. /**
  134. * Remove remove all but 0->9, A->F characters from a string.
  135. * Return a pointer to the new resulting string (allocated with 'new')
  136. */
  137. static char* RemoveCharsButUpperHex(const char* str);
  138. /**
  139. * Replace some characters by another character in a string (in-place)
  140. * Return a pointer to string
  141. */
  142. static char* ReplaceChars(char* str, const char* toreplace,
  143. char replacement);
  144. /**
  145. * Returns true if str1 starts (respectively ends) with str2
  146. */
  147. static bool StringStartsWith(const char* str1, const char* str2);
  148. static bool StringStartsWith(const std::string& str1, const char* str2);
  149. static bool StringEndsWith(const char* str1, const char* str2);
  150. static bool StringEndsWith(const std::string& str1, const char* str2);
  151. /**
  152. * Returns a pointer to the last occurrence of str2 in str1
  153. */
  154. static const char* FindLastString(const char* str1, const char* str2);
  155. /**
  156. * Make a duplicate of the string similar to the strdup C function
  157. * but use new to create the 'new' string, so one can use
  158. * 'delete' to remove it. Returns 0 if the input is empty.
  159. */
  160. static char* DuplicateString(const char* str);
  161. /**
  162. * Return the string cropped to a given length by removing chars in the
  163. * center of the string and replacing them with an ellipsis (...)
  164. */
  165. static std::string CropString(const std::string&, size_t max_len);
  166. /** split a path by separator into an array of strings, default is /.
  167. If isPath is true then the string is treated like a path and if
  168. s starts with a / then the first element of the returned array will
  169. be /, so /foo/bar will be [/, foo, bar]
  170. */
  171. static std::vector<String> SplitString(const std::string& s,
  172. char separator = '/',
  173. bool isPath = false);
  174. /**
  175. * Perform a case-independent string comparison
  176. */
  177. static int Strucmp(const char* s1, const char* s2);
  178. /**
  179. * Split a string on its newlines into multiple lines
  180. * Return false only if the last line stored had no newline
  181. */
  182. static bool Split(const std::string& s, std::vector<std::string>& l);
  183. static bool Split(const std::string& s, std::vector<std::string>& l,
  184. char separator);
  185. /**
  186. * Return string with space added between capitalized words
  187. * (i.e. EatMyShorts becomes Eat My Shorts )
  188. * (note that IEatShorts becomes IEat Shorts)
  189. */
  190. static std::string AddSpaceBetweenCapitalizedWords(const std::string&);
  191. /**
  192. * Append two or more strings and produce new one.
  193. * Programmer must 'delete []' the resulting string, which was allocated
  194. * with 'new'.
  195. * Return 0 if inputs are empty or there was an error
  196. */
  197. static char* AppendStrings(const char* str1, const char* str2);
  198. static char* AppendStrings(const char* str1, const char* str2,
  199. const char* str3);
  200. /**
  201. * Estimate the length of the string that will be produced
  202. * from printing the given format string and arguments. The
  203. * returned length will always be at least as large as the string
  204. * that will result from printing.
  205. * WARNING: since va_arg is called to iterate of the argument list,
  206. * you will not be able to use this 'ap' anymore from the beginning.
  207. * It's up to you to call va_end though.
  208. */
  209. static int EstimateFormatLength(const char* format, va_list ap);
  210. /**
  211. * Escape specific characters in 'str'.
  212. */
  213. static std::string EscapeChars(const char* str, const char* chars_to_escape,
  214. char escape_char = '\\');
  215. /** -----------------------------------------------------------------
  216. * Filename Manipulation Routines
  217. * -----------------------------------------------------------------
  218. */
  219. /**
  220. * Replace Windows file system slashes with Unix-style slashes.
  221. */
  222. static void ConvertToUnixSlashes(std::string& path);
  223. #ifdef _WIN32
  224. /** Calls Encoding::ToWindowsExtendedPath. */
  225. static std::wstring ConvertToWindowsExtendedPath(const std::string&);
  226. #endif
  227. /**
  228. * For windows this calls ConvertToWindowsOutputPath and for unix
  229. * it calls ConvertToUnixOutputPath
  230. */
  231. static std::string ConvertToOutputPath(const std::string&);
  232. /**
  233. * Convert the path to a string that can be used in a unix makefile.
  234. * double slashes are removed, and spaces are escaped.
  235. */
  236. static std::string ConvertToUnixOutputPath(const std::string&);
  237. /**
  238. * Convert the path to string that can be used in a windows project or
  239. * makefile. Double slashes are removed if they are not at the start of
  240. * the string, the slashes are converted to windows style backslashes, and
  241. * if there are spaces in the string it is double quoted.
  242. */
  243. static std::string ConvertToWindowsOutputPath(const std::string&);
  244. /**
  245. * Return true if a path with the given name exists in the current directory.
  246. */
  247. static bool PathExists(const std::string& path);
  248. /**
  249. * Return true if a file exists in the current directory.
  250. * If isFile = true, then make sure the file is a file and
  251. * not a directory. If isFile = false, then return true
  252. * if it is a file or a directory. Note that the file will
  253. * also be checked for read access. (Currently, this check
  254. * for read access is only done on POSIX systems.)
  255. */
  256. static bool FileExists(const char* filename, bool isFile);
  257. static bool FileExists(const std::string& filename, bool isFile);
  258. static bool FileExists(const char* filename);
  259. static bool FileExists(const std::string& filename);
  260. /**
  261. * Test if a file exists and can be accessed with the requested
  262. * permissions. Symbolic links are followed. Returns true if
  263. * the access test was successful.
  264. *
  265. * On POSIX systems (including Cygwin), this maps to the access
  266. * function. On Windows systems, all existing files are
  267. * considered readable, and writable files are considered to
  268. * have the read-only file attribute cleared.
  269. */
  270. static bool TestFileAccess(const char* filename,
  271. TestFilePermissions permissions);
  272. static bool TestFileAccess(const std::string& filename,
  273. TestFilePermissions permissions);
  274. /**
  275. * Cross platform wrapper for stat struct
  276. */
  277. #if defined(_WIN32) && !defined(__CYGWIN__)
  278. #if defined(__BORLANDC__)
  279. typedef struct stati64 Stat_t;
  280. #else
  281. typedef struct _stat64 Stat_t;
  282. #endif
  283. #else
  284. typedef struct stat Stat_t;
  285. #endif
  286. /**
  287. * Cross platform wrapper for stat system call
  288. *
  289. * On Windows this may not work for paths longer than 250 characters
  290. * due to limitations of the underlying '_wstat64' call.
  291. */
  292. static int Stat(const char* path, Stat_t* buf);
  293. static int Stat(const std::string& path, Stat_t* buf);
  294. /**
  295. * Converts Cygwin path to Win32 path. Uses dictionary container for
  296. * caching and calls to cygwin_conv_to_win32_path from Cygwin dll
  297. * for actual translation. Returns true on success, else false.
  298. */
  299. #ifdef __CYGWIN__
  300. static bool PathCygwinToWin32(const char* path, char* win32_path);
  301. #endif
  302. /**
  303. * Return file length
  304. */
  305. static unsigned long FileLength(const std::string& filename);
  306. /**
  307. Change the modification time or create a file
  308. */
  309. static bool Touch(const std::string& filename, bool create);
  310. /**
  311. * Compare file modification times.
  312. * Return true for successful comparison and false for error.
  313. * When true is returned, result has -1, 0, +1 for
  314. * f1 older, same, or newer than f2.
  315. */
  316. static bool FileTimeCompare(const std::string& f1, const std::string& f2,
  317. int* result);
  318. /**
  319. * Get the file extension (including ".") needed for an executable
  320. * on the current platform ("" for unix, ".exe" for Windows).
  321. */
  322. static const char* GetExecutableExtension();
  323. /**
  324. * Given a path on a Windows machine, return the actual case of
  325. * the path as it exists on disk. Path components that do not
  326. * exist on disk are returned unchanged. Relative paths are always
  327. * returned unchanged. Drive letters are always made upper case.
  328. * This does nothing on non-Windows systems but return the path.
  329. */
  330. static std::string GetActualCaseForPath(const std::string& path);
  331. /**
  332. * Given the path to a program executable, get the directory part of
  333. * the path with the file stripped off. If there is no directory
  334. * part, the empty string is returned.
  335. */
  336. static std::string GetProgramPath(const std::string&);
  337. static bool SplitProgramPath(const std::string& in_name, std::string& dir,
  338. std::string& file, bool errorReport = true);
  339. /**
  340. * Given argv[0] for a unix program find the full path to a running
  341. * executable. argv0 can be null for windows WinMain programs
  342. * in this case GetModuleFileName will be used to find the path
  343. * to the running executable. If argv0 is not a full path,
  344. * then this will try to find the full path. If the path is not
  345. * found false is returned, if found true is returned. An error
  346. * message of the attempted paths is stored in errorMsg.
  347. * exeName is the name of the executable.
  348. * buildDir is a possibly null path to the build directory.
  349. * installPrefix is a possibly null pointer to the install directory.
  350. */
  351. static bool FindProgramPath(const char* argv0, std::string& pathOut,
  352. std::string& errorMsg, const char* exeName = 0,
  353. const char* buildDir = 0,
  354. const char* installPrefix = 0);
  355. /**
  356. * Given a path to a file or directory, convert it to a full path.
  357. * This collapses away relative paths relative to the cwd argument
  358. * (which defaults to the current working directory). The full path
  359. * is returned.
  360. */
  361. static std::string CollapseFullPath(const std::string& in_relative);
  362. static std::string CollapseFullPath(const std::string& in_relative,
  363. const char* in_base);
  364. static std::string CollapseFullPath(const std::string& in_relative,
  365. const std::string& in_base);
  366. /**
  367. * Get the real path for a given path, removing all symlinks. In
  368. * the event of an error (non-existent path, permissions issue,
  369. * etc.) the original path is returned if errorMessage pointer is
  370. * NULL. Otherwise empty string is returned and errorMessage
  371. * contains error description.
  372. */
  373. static std::string GetRealPath(const std::string& path,
  374. std::string* errorMessage = 0);
  375. /**
  376. * Split a path name into its root component and the rest of the
  377. * path. The root component is one of the following:
  378. * "/" = UNIX full path
  379. * "c:/" = Windows full path (can be any drive letter)
  380. * "c:" = Windows drive-letter relative path (can be any drive letter)
  381. * "//" = Network path
  382. * "~/" = Home path for current user
  383. * "~u/" = Home path for user 'u'
  384. * "" = Relative path
  385. *
  386. * A pointer to the rest of the path after the root component is
  387. * returned. The root component is stored in the "root" string if
  388. * given.
  389. */
  390. static const char* SplitPathRootComponent(const std::string& p,
  391. std::string* root = 0);
  392. /**
  393. * Split a path name into its basic components. The first component
  394. * always exists and is the root returned by SplitPathRootComponent.
  395. * The remaining components form the path. If there is a trailing
  396. * slash then the last component is the empty string. The
  397. * components can be recombined as "c[0]c[1]/c[2]/.../c[n]" to
  398. * produce the original path. Home directory references are
  399. * automatically expanded if expand_home_dir is true and this
  400. * platform supports them.
  401. *
  402. * This does *not* normalize the input path. All components are
  403. * preserved, including empty ones. Typically callers should use
  404. * this only on paths that have already been normalized.
  405. */
  406. static void SplitPath(const std::string& p,
  407. std::vector<std::string>& components,
  408. bool expand_home_dir = true);
  409. /**
  410. * Join components of a path name into a single string. See
  411. * SplitPath for the format of the components.
  412. *
  413. * This does *not* normalize the input path. All components are
  414. * preserved, including empty ones. Typically callers should use
  415. * this only on paths that have already been normalized.
  416. */
  417. static std::string JoinPath(const std::vector<std::string>& components);
  418. static std::string JoinPath(std::vector<std::string>::const_iterator first,
  419. std::vector<std::string>::const_iterator last);
  420. /**
  421. * Compare a path or components of a path.
  422. */
  423. static bool ComparePath(const std::string& c1, const std::string& c2);
  424. /**
  425. * Return path of a full filename (no trailing slashes)
  426. */
  427. static std::string GetFilenamePath(const std::string&);
  428. /**
  429. * Return file name of a full filename (i.e. file name without path)
  430. */
  431. static std::string GetFilenameName(const std::string&);
  432. /**
  433. * Return longest file extension of a full filename (dot included)
  434. */
  435. static std::string GetFilenameExtension(const std::string&);
  436. /**
  437. * Return shortest file extension of a full filename (dot included)
  438. */
  439. static std::string GetFilenameLastExtension(const std::string& filename);
  440. /**
  441. * Return file name without extension of a full filename
  442. */
  443. static std::string GetFilenameWithoutExtension(const std::string&);
  444. /**
  445. * Return file name without its last (shortest) extension
  446. */
  447. static std::string GetFilenameWithoutLastExtension(const std::string&);
  448. /**
  449. * Return whether the path represents a full path (not relative)
  450. */
  451. static bool FileIsFullPath(const std::string&);
  452. static bool FileIsFullPath(const char*);
  453. /**
  454. * For windows return the short path for the given path,
  455. * Unix just a pass through
  456. */
  457. static bool GetShortPath(const std::string& path, std::string& result);
  458. /**
  459. * Read line from file. Make sure to get everything. Due to a buggy stream
  460. * library on the HP and another on Mac OS X, we need this very carefully
  461. * written version of getline. Returns true if any data were read before the
  462. * end-of-file was reached. If the has_newline argument is specified, it will
  463. * be true when the line read had a newline character.
  464. */
  465. static bool GetLineFromStream(std::istream& istr, std::string& line,
  466. bool* has_newline = 0, long sizeLimit = -1);
  467. /**
  468. * Get the parent directory of the directory or file
  469. */
  470. static std::string GetParentDirectory(const std::string& fileOrDir);
  471. /**
  472. * Check if the given file or directory is in subdirectory of dir
  473. */
  474. static bool IsSubDirectory(const std::string& fileOrDir,
  475. const std::string& dir);
  476. /** -----------------------------------------------------------------
  477. * File Manipulation Routines
  478. * -----------------------------------------------------------------
  479. */
  480. /**
  481. * Open a file considering unicode.
  482. */
  483. static FILE* Fopen(const std::string& file, const char* mode);
  484. /**
  485. * Visual C++ does not define mode_t (note that Borland does, however).
  486. */
  487. #if defined(_MSC_VER)
  488. typedef unsigned short mode_t;
  489. #endif
  490. /**
  491. * Make a new directory if it is not there. This function
  492. * can make a full path even if none of the directories existed
  493. * prior to calling this function.
  494. */
  495. static bool MakeDirectory(const char* path, const mode_t* mode = 0);
  496. static bool MakeDirectory(const std::string& path, const mode_t* mode = 0);
  497. /**
  498. * Copy the source file to the destination file only
  499. * if the two files differ.
  500. */
  501. static bool CopyFileIfDifferent(const std::string& source,
  502. const std::string& destination);
  503. /**
  504. * Compare the contents of two files. Return true if different
  505. */
  506. static bool FilesDiffer(const std::string& source,
  507. const std::string& destination);
  508. /**
  509. * Return true if the two files are the same file
  510. */
  511. static bool SameFile(const std::string& file1, const std::string& file2);
  512. /**
  513. * Copy a file.
  514. */
  515. static bool CopyFileAlways(const std::string& source,
  516. const std::string& destination);
  517. /**
  518. * Copy a file. If the "always" argument is true the file is always
  519. * copied. If it is false, the file is copied only if it is new or
  520. * has changed.
  521. */
  522. static bool CopyAFile(const std::string& source,
  523. const std::string& destination, bool always = true);
  524. /**
  525. * Copy content directory to another directory with all files and
  526. * subdirectories. If the "always" argument is true all files are
  527. * always copied. If it is false, only files that have changed or
  528. * are new are copied.
  529. */
  530. static bool CopyADirectory(const std::string& source,
  531. const std::string& destination,
  532. bool always = true);
  533. /**
  534. * Remove a file
  535. */
  536. static bool RemoveFile(const std::string& source);
  537. /**
  538. * Remove a directory
  539. */
  540. static bool RemoveADirectory(const std::string& source);
  541. /**
  542. * Get the maximum full file path length
  543. */
  544. static size_t GetMaximumFilePathLength();
  545. /**
  546. * Find a file in the system PATH, with optional extra paths
  547. */
  548. static std::string FindFile(
  549. const std::string& name,
  550. const std::vector<std::string>& path = std::vector<std::string>(),
  551. bool no_system_path = false);
  552. /**
  553. * Find a directory in the system PATH, with optional extra paths
  554. */
  555. static std::string FindDirectory(
  556. const std::string& name,
  557. const std::vector<std::string>& path = std::vector<std::string>(),
  558. bool no_system_path = false);
  559. /**
  560. * Find an executable in the system PATH, with optional extra paths
  561. */
  562. static std::string FindProgram(
  563. const char* name,
  564. const std::vector<std::string>& path = std::vector<std::string>(),
  565. bool no_system_path = false);
  566. static std::string FindProgram(
  567. const std::string& name,
  568. const std::vector<std::string>& path = std::vector<std::string>(),
  569. bool no_system_path = false);
  570. static std::string FindProgram(
  571. const std::vector<std::string>& names,
  572. const std::vector<std::string>& path = std::vector<std::string>(),
  573. bool no_system_path = false);
  574. /**
  575. * Find a library in the system PATH, with optional extra paths
  576. */
  577. static std::string FindLibrary(const std::string& name,
  578. const std::vector<std::string>& path);
  579. /**
  580. * Return true if the file is a directory
  581. */
  582. static bool FileIsDirectory(const std::string& name);
  583. /**
  584. * Return true if the file is a symlink
  585. */
  586. static bool FileIsSymlink(const std::string& name);
  587. /**
  588. * Return true if the file is a FIFO
  589. */
  590. static bool FileIsFIFO(const std::string& name);
  591. /**
  592. * Return true if the file has a given signature (first set of bytes)
  593. */
  594. static bool FileHasSignature(const char* filename, const char* signature,
  595. long offset = 0);
  596. /**
  597. * Attempt to detect and return the type of a file.
  598. * Up to 'length' bytes are read from the file, if more than 'percent_bin' %
  599. * of the bytes are non-textual elements, the file is considered binary,
  600. * otherwise textual. Textual elements are bytes in the ASCII [0x20, 0x7E]
  601. * range, but also \\n, \\r, \\t.
  602. * The algorithm is simplistic, and should probably check for usual file
  603. * extensions, 'magic' signature, unicode, etc.
  604. */
  605. enum FileTypeEnum
  606. {
  607. FileTypeUnknown,
  608. FileTypeBinary,
  609. FileTypeText
  610. };
  611. static SystemTools::FileTypeEnum DetectFileType(const char* filename,
  612. unsigned long length = 256,
  613. double percent_bin = 0.05);
  614. /**
  615. * Create a symbolic link if the platform supports it. Returns whether
  616. * creation succeeded.
  617. */
  618. static bool CreateSymlink(const std::string& origName,
  619. const std::string& newName);
  620. /**
  621. * Read the contents of a symbolic link. Returns whether reading
  622. * succeeded.
  623. */
  624. static bool ReadSymlink(const std::string& newName, std::string& origName);
  625. /**
  626. * Try to locate the file 'filename' in the directory 'dir'.
  627. * If 'filename' is a fully qualified filename, the basename of the file is
  628. * used to check for its existence in 'dir'.
  629. * If 'dir' is not a directory, GetFilenamePath() is called on 'dir' to
  630. * get its directory first (thus, you can pass a filename as 'dir', as
  631. * a convenience).
  632. * 'filename_found' is assigned the fully qualified name/path of the file
  633. * if it is found (not touched otherwise).
  634. * If 'try_filename_dirs' is true, try to find the file using the
  635. * components of its path, i.e. if we are looking for c:/foo/bar/bill.txt,
  636. * first look for bill.txt in 'dir', then in 'dir'/bar, then in 'dir'/foo/bar
  637. * etc.
  638. * Return true if the file was found, false otherwise.
  639. */
  640. static bool LocateFileInDir(const char* filename, const char* dir,
  641. std::string& filename_found,
  642. int try_filename_dirs = 0);
  643. /** compute the relative path from local to remote. local must
  644. be a directory. remote can be a file or a directory.
  645. Both remote and local must be full paths. Basically, if
  646. you are in directory local and you want to access the file in remote
  647. what is the relative path to do that. For example:
  648. /a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
  649. from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
  650. */
  651. static std::string RelativePath(const std::string& local,
  652. const std::string& remote);
  653. /**
  654. * Return file's modified time
  655. */
  656. static long int ModifiedTime(const std::string& filename);
  657. /**
  658. * Return file's creation time (Win32: works only for NTFS, not FAT)
  659. */
  660. static long int CreationTime(const std::string& filename);
  661. /**
  662. * Get and set permissions of the file. If honor_umask is set, the umask
  663. * is queried and applied to the given permissions. Returns false if
  664. * failure.
  665. *
  666. * WARNING: A non-thread-safe method is currently used to get the umask
  667. * if a honor_umask parameter is set to true.
  668. */
  669. static bool GetPermissions(const char* file, mode_t& mode);
  670. static bool GetPermissions(const std::string& file, mode_t& mode);
  671. static bool SetPermissions(const char* file, mode_t mode,
  672. bool honor_umask = false);
  673. static bool SetPermissions(const std::string& file, mode_t mode,
  674. bool honor_umask = false);
  675. /** -----------------------------------------------------------------
  676. * Time Manipulation Routines
  677. * -----------------------------------------------------------------
  678. */
  679. /** Get current time in seconds since Posix Epoch (Jan 1, 1970). */
  680. static double GetTime();
  681. /**
  682. * Get current date/time
  683. */
  684. static std::string GetCurrentDateTime(const char* format);
  685. /** -----------------------------------------------------------------
  686. * Registry Manipulation Routines
  687. * -----------------------------------------------------------------
  688. */
  689. /**
  690. * Specify access to the 32-bit or 64-bit application view of
  691. * registry values. The default is to match the currently running
  692. * binary type.
  693. */
  694. enum KeyWOW64
  695. {
  696. KeyWOW64_Default,
  697. KeyWOW64_32,
  698. KeyWOW64_64
  699. };
  700. /**
  701. * Get a list of subkeys.
  702. */
  703. static bool GetRegistrySubKeys(const std::string& key,
  704. std::vector<std::string>& subkeys,
  705. KeyWOW64 view = KeyWOW64_Default);
  706. /**
  707. * Read a registry value
  708. */
  709. static bool ReadRegistryValue(const std::string& key, std::string& value,
  710. KeyWOW64 view = KeyWOW64_Default);
  711. /**
  712. * Write a registry value
  713. */
  714. static bool WriteRegistryValue(const std::string& key,
  715. const std::string& value,
  716. KeyWOW64 view = KeyWOW64_Default);
  717. /**
  718. * Delete a registry value
  719. */
  720. static bool DeleteRegistryValue(const std::string& key,
  721. KeyWOW64 view = KeyWOW64_Default);
  722. /** -----------------------------------------------------------------
  723. * Environment Manipulation Routines
  724. * -----------------------------------------------------------------
  725. */
  726. /**
  727. * Add the paths from the environment variable PATH to the
  728. * string vector passed in. If env is set then the value
  729. * of env will be used instead of PATH.
  730. */
  731. static void GetPath(std::vector<std::string>& path, const char* env = 0);
  732. /**
  733. * Read an environment variable
  734. */
  735. static const char* GetEnv(const char* key);
  736. static const char* GetEnv(const std::string& key);
  737. static bool GetEnv(const char* key, std::string& result);
  738. static bool GetEnv(const std::string& key, std::string& result);
  739. static bool HasEnv(const char* key);
  740. static bool HasEnv(const std::string& key);
  741. /** Put a string into the environment
  742. of the form var=value */
  743. static bool PutEnv(const std::string& env);
  744. /** Remove a string from the environment.
  745. Input is of the form "var" or "var=value" (value is ignored). */
  746. static bool UnPutEnv(const std::string& env);
  747. /**
  748. * Get current working directory CWD
  749. */
  750. static std::string GetCurrentWorkingDirectory(bool collapse = true);
  751. /**
  752. * Change directory to the directory specified
  753. */
  754. static int ChangeDirectory(const std::string& dir);
  755. /**
  756. * Get the result of strerror(errno)
  757. */
  758. static std::string GetLastSystemError();
  759. /**
  760. * When building DEBUG with MSVC, this enables a hook that prevents
  761. * error dialogs from popping up if the program is being run from
  762. * DART.
  763. */
  764. static void EnableMSVCDebugHook();
  765. /**
  766. * Get the width of the terminal window. The code may or may not work, so
  767. * make sure you have some reasonable defaults prepared if the code returns
  768. * some bogus size.
  769. */
  770. static int GetTerminalWidth();
  771. /**
  772. * Add an entry in the path translation table.
  773. */
  774. static void AddTranslationPath(const std::string& dir,
  775. const std::string& refdir);
  776. /**
  777. * If dir is different after CollapseFullPath is called,
  778. * Then insert it into the path translation table
  779. */
  780. static void AddKeepPath(const std::string& dir);
  781. /**
  782. * Update path by going through the Path Translation table;
  783. */
  784. static void CheckTranslationPath(std::string& path);
  785. /**
  786. * Delay the execution for a specified amount of time specified
  787. * in milliseconds
  788. */
  789. static void Delay(unsigned int msec);
  790. /**
  791. * Get the operating system name and version
  792. * This is implemented for Win32 only for the moment
  793. */
  794. static std::string GetOperatingSystemNameAndVersion();
  795. /** -----------------------------------------------------------------
  796. * URL Manipulation Routines
  797. * -----------------------------------------------------------------
  798. */
  799. /**
  800. * Parse a character string :
  801. * protocol://dataglom
  802. * and fill protocol as appropriate.
  803. * Return false if the URL does not have the required form, true otherwise.
  804. */
  805. static bool ParseURLProtocol(const std::string& URL, std::string& protocol,
  806. std::string& dataglom);
  807. /**
  808. * Parse a string (a URL without protocol prefix) with the form:
  809. * protocol://[[username[':'password]'@']hostname[':'dataport]]'/'[datapath]
  810. * and fill protocol, username, password, hostname, dataport, and datapath
  811. * when values are found.
  812. * Return true if the string matches the format; false otherwise.
  813. */
  814. static bool ParseURL(const std::string& URL, std::string& protocol,
  815. std::string& username, std::string& password,
  816. std::string& hostname, std::string& dataport,
  817. std::string& datapath);
  818. private:
  819. /**
  820. * Allocate the stl map that serve as the Path Translation table.
  821. */
  822. static void ClassInitialize();
  823. /**
  824. * Deallocate the stl map that serve as the Path Translation table.
  825. */
  826. static void ClassFinalize();
  827. /**
  828. * This method prevents warning on SGI
  829. */
  830. SystemToolsManager* GetSystemToolsManager()
  831. {
  832. return &SystemToolsManagerInstance;
  833. }
  834. /**
  835. * Actual implementation of ReplaceString.
  836. */
  837. static void ReplaceString(std::string& source, const char* replace,
  838. size_t replaceSize, const std::string& with);
  839. /**
  840. * Actual implementation of FileIsFullPath.
  841. */
  842. static bool FileIsFullPath(const char*, size_t);
  843. /**
  844. * Find a filename (file or directory) in the system PATH, with
  845. * optional extra paths.
  846. */
  847. static std::string FindName(
  848. const std::string& name,
  849. const std::vector<std::string>& path = std::vector<std::string>(),
  850. bool no_system_path = false);
  851. static const char* GetEnvImpl(const char* key);
  852. /**
  853. * Path translation table from dir to refdir
  854. * Each time 'dir' will be found it will be replace by 'refdir'
  855. */
  856. static SystemToolsTranslationMap* TranslationMap;
  857. #ifdef _WIN32
  858. static std::string GetActualCaseForPathCached(std::string const& path);
  859. static SystemToolsPathCaseMap* PathCaseMap;
  860. static SystemToolsEnvMap* EnvMap;
  861. #endif
  862. #ifdef __CYGWIN__
  863. static SystemToolsTranslationMap* Cyg2Win32Map;
  864. #endif
  865. friend class SystemToolsManager;
  866. };
  867. } // namespace cmsys
  868. #endif