SystemTools.hxx.in 34 KB

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