SystemTools.hxx.in 34 KB

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