SystemTools.hxx.in 34 KB

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