SystemTools.hxx.in 34 KB

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