file_path.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. // FilePath is a container for pathnames stored in a platform's native string
  5. // type, providing containers for manipulation in according with the
  6. // platform's conventions for pathnames. It supports the following path
  7. // types:
  8. //
  9. // POSIX Windows
  10. // --------------- ----------------------------------
  11. // Fundamental type char[] wchar_t[]
  12. // Encoding unspecified* UTF-16
  13. // Separator / \, tolerant of /
  14. // Drive letters no case-insensitive A-Z followed by :
  15. // Alternate root // (surprise!) \\, for UNC paths
  16. //
  17. // * The encoding need not be specified on POSIX systems, although some
  18. // POSIX-compliant systems do specify an encoding. Mac OS X uses UTF-8.
  19. // Chrome OS also uses UTF-8.
  20. // Linux does not specify an encoding, but in practice, the locale's
  21. // character set may be used.
  22. //
  23. // For more arcane bits of path trivia, see below.
  24. //
  25. // FilePath objects are intended to be used anywhere paths are. An
  26. // application may pass FilePath objects around internally, masking the
  27. // underlying differences between systems, only differing in implementation
  28. // where interfacing directly with the system. For example, a single
  29. // OpenFile(const FilePath &) function may be made available, allowing all
  30. // callers to operate without regard to the underlying implementation. On
  31. // POSIX-like platforms, OpenFile might wrap fopen, and on Windows, it might
  32. // wrap _wfopen_s, perhaps both by calling file_path.value().c_str(). This
  33. // allows each platform to pass pathnames around without requiring conversions
  34. // between encodings, which has an impact on performance, but more imporantly,
  35. // has an impact on correctness on platforms that do not have well-defined
  36. // encodings for pathnames.
  37. //
  38. // Several methods are available to perform common operations on a FilePath
  39. // object, such as determining the parent directory (DirName), isolating the
  40. // final path component (BaseName), and appending a relative pathname string
  41. // to an existing FilePath object (Append). These methods are highly
  42. // recommended over attempting to split and concatenate strings directly.
  43. // These methods are based purely on string manipulation and knowledge of
  44. // platform-specific pathname conventions, and do not consult the filesystem
  45. // at all, making them safe to use without fear of blocking on I/O operations.
  46. // These methods do not function as mutators but instead return distinct
  47. // instances of FilePath objects, and are therefore safe to use on const
  48. // objects. The objects themselves are safe to share between threads.
  49. //
  50. // To aid in initialization of FilePath objects from string literals, a
  51. // FILE_PATH_LITERAL macro is provided, which accounts for the difference
  52. // between char[]-based pathnames on POSIX systems and wchar_t[]-based
  53. // pathnames on Windows.
  54. //
  55. // As a precaution against premature truncation, paths can't contain NULs.
  56. //
  57. // Because a FilePath object should not be instantiated at the global scope,
  58. // instead, use a FilePath::CharType[] and initialize it with
  59. // FILE_PATH_LITERAL. At runtime, a FilePath object can be created from the
  60. // character array. Example:
  61. //
  62. // | const FilePath::CharType kLogFileName[] = FILE_PATH_LITERAL("log.txt");
  63. // |
  64. // | void Function() {
  65. // | FilePath log_file_path(kLogFileName);
  66. // | [...]
  67. // | }
  68. //
  69. // WARNING: FilePaths should ALWAYS be displayed with LTR directionality, even
  70. // when the UI language is RTL. This means you always need to pass filepaths
  71. // through base::i18n::WrapPathWithLTRFormatting() before displaying it in the
  72. // RTL UI.
  73. //
  74. // This is a very common source of bugs, please try to keep this in mind.
  75. //
  76. // ARCANE BITS OF PATH TRIVIA
  77. //
  78. // - A double leading slash is actually part of the POSIX standard. Systems
  79. // are allowed to treat // as an alternate root, as Windows does for UNC
  80. // (network share) paths. Most POSIX systems don't do anything special
  81. // with two leading slashes, but FilePath handles this case properly
  82. // in case it ever comes across such a system. FilePath needs this support
  83. // for Windows UNC paths, anyway.
  84. // References:
  85. // The Open Group Base Specifications Issue 7, sections 3.267 ("Pathname")
  86. // and 4.12 ("Pathname Resolution"), available at:
  87. // http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_267
  88. // http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
  89. //
  90. // - Windows treats c:\\ the same way it treats \\. This was intended to
  91. // allow older applications that require drive letters to support UNC paths
  92. // like \\server\share\path, by permitting c:\\server\share\path as an
  93. // equivalent. Since the OS treats these paths specially, FilePath needs
  94. // to do the same. Since Windows can use either / or \ as the separator,
  95. // FilePath treats c://, c:\\, //, and \\ all equivalently.
  96. // Reference:
  97. // The Old New Thing, "Why is a drive letter permitted in front of UNC
  98. // paths (sometimes)?", available at:
  99. // http://blogs.msdn.com/oldnewthing/archive/2005/11/22/495740.aspx
  100. #ifndef BASE_FILES_FILE_PATH_H_
  101. #define BASE_FILES_FILE_PATH_H_
  102. #include <stddef.h>
  103. #include <functional>
  104. #include <iosfwd>
  105. #include <string>
  106. #include <vector>
  107. #include "base/base_export.h"
  108. #include "base/compiler_specific.h"
  109. #include "base/stl_util.h"
  110. #include "base/strings/string16.h"
  111. #include "base/strings/string_piece.h"
  112. #include "build/build_config.h"
  113. // Windows-style drive letter support and pathname separator characters can be
  114. // enabled and disabled independently, to aid testing. These #defines are
  115. // here so that the same setting can be used in both the implementation and
  116. // in the unit test.
  117. #if defined(OS_WIN)
  118. #define FILE_PATH_USES_DRIVE_LETTERS
  119. #define FILE_PATH_USES_WIN_SEPARATORS
  120. #endif // OS_WIN
  121. // To print path names portably use PRFilePath (based on PRIuS and friends from
  122. // C99 and format_macros.h) like this:
  123. // base::StringPrintf("Path is %" PRFilePath ".\n", path.value().c_str());
  124. #if defined(OS_WIN)
  125. #define PRFilePath "ls"
  126. #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
  127. #define PRFilePath "s"
  128. #endif // OS_WIN
  129. // Macros for string literal initialization of FilePath::CharType[].
  130. #if defined(OS_WIN)
  131. #define FILE_PATH_LITERAL(x) L##x
  132. #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
  133. #define FILE_PATH_LITERAL(x) x
  134. #endif // OS_WIN
  135. namespace base {
  136. class Pickle;
  137. class PickleIterator;
  138. // An abstraction to isolate users from the differences between native
  139. // pathnames on different platforms.
  140. class BASE_EXPORT FilePath {
  141. public:
  142. #if defined(OS_WIN)
  143. // On Windows, for Unicode-aware applications, native pathnames are wchar_t
  144. // arrays encoded in UTF-16.
  145. typedef std::wstring StringType;
  146. #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
  147. // On most platforms, native pathnames are char arrays, and the encoding
  148. // may or may not be specified. On Mac OS X, native pathnames are encoded
  149. // in UTF-8.
  150. typedef std::string StringType;
  151. #endif // OS_WIN
  152. typedef BasicStringPiece<StringType> StringPieceType;
  153. typedef StringType::value_type CharType;
  154. // Null-terminated array of separators used to separate components in
  155. // hierarchical paths. Each character in this array is a valid separator,
  156. // but kSeparators[0] is treated as the canonical separator and will be used
  157. // when composing pathnames.
  158. static const CharType kSeparators[];
  159. // base::size(kSeparators).
  160. static const size_t kSeparatorsLength;
  161. // A special path component meaning "this directory."
  162. static const CharType kCurrentDirectory[];
  163. // A special path component meaning "the parent directory."
  164. static const CharType kParentDirectory[];
  165. // The character used to identify a file extension.
  166. static const CharType kExtensionSeparator;
  167. FilePath();
  168. FilePath(const FilePath& that);
  169. explicit FilePath(StringPieceType path);
  170. ~FilePath();
  171. FilePath& operator=(const FilePath& that);
  172. // Constructs FilePath with the contents of |that|, which is left in valid but
  173. // unspecified state.
  174. FilePath(FilePath&& that) noexcept;
  175. // Replaces the contents with those of |that|, which is left in valid but
  176. // unspecified state.
  177. FilePath& operator=(FilePath&& that) noexcept;
  178. bool operator==(const FilePath& that) const;
  179. bool operator!=(const FilePath& that) const;
  180. // Required for some STL containers and operations
  181. bool operator<(const FilePath& that) const {
  182. return path_ < that.path_;
  183. }
  184. const StringType& value() const { return path_; }
  185. bool empty() const { return path_.empty(); }
  186. void clear() { path_.clear(); }
  187. // Returns true if |character| is in kSeparators.
  188. static bool IsSeparator(CharType character);
  189. // Returns a vector of all of the components of the provided path. It is
  190. // equivalent to calling DirName().value() on the path's root component,
  191. // and BaseName().value() on each child component.
  192. //
  193. // To make sure this is lossless so we can differentiate absolute and
  194. // relative paths, the root slash will be included even though no other
  195. // slashes will be. The precise behavior is:
  196. //
  197. // Posix: "/foo/bar" -> [ "/", "foo", "bar" ]
  198. // Windows: "C:\foo\bar" -> [ "C:", "\\", "foo", "bar" ]
  199. void GetComponents(std::vector<FilePath::StringType>* components) const;
  200. // Returns true if this FilePath is a parent or ancestor of the |child|.
  201. // Absolute and relative paths are accepted i.e. /foo is a parent to /foo/bar,
  202. // and foo is a parent to foo/bar. Any ancestor is considered a parent i.e. /a
  203. // is a parent to both /a/b and /a/b/c. Does not convert paths to absolute,
  204. // follow symlinks or directory navigation (e.g. ".."). A path is *NOT* its
  205. // own parent.
  206. bool IsParent(const FilePath& child) const;
  207. // If IsParent(child) holds, appends to path (if non-NULL) the
  208. // relative path to child and returns true. For example, if parent
  209. // holds "/Users/johndoe/Library/Application Support", child holds
  210. // "/Users/johndoe/Library/Application Support/Google/Chrome/Default", and
  211. // *path holds "/Users/johndoe/Library/Caches", then after
  212. // parent.AppendRelativePath(child, path) is called *path will hold
  213. // "/Users/johndoe/Library/Caches/Google/Chrome/Default". Otherwise,
  214. // returns false.
  215. bool AppendRelativePath(const FilePath& child, FilePath* path) const;
  216. // Returns a FilePath corresponding to the directory containing the path
  217. // named by this object, stripping away the file component. If this object
  218. // only contains one component, returns a FilePath identifying
  219. // kCurrentDirectory. If this object already refers to the root directory,
  220. // returns a FilePath identifying the root directory. Please note that this
  221. // doesn't resolve directory navigation, e.g. the result for "../a" is "..".
  222. FilePath DirName() const WARN_UNUSED_RESULT;
  223. // Returns a FilePath corresponding to the last path component of this
  224. // object, either a file or a directory. If this object already refers to
  225. // the root directory, returns a FilePath identifying the root directory;
  226. // this is the only situation in which BaseName will return an absolute path.
  227. FilePath BaseName() const WARN_UNUSED_RESULT;
  228. // Returns ".jpg" for path "C:\pics\jojo.jpg", or an empty string if
  229. // the file has no extension. If non-empty, Extension() will always start
  230. // with precisely one ".". The following code should always work regardless
  231. // of the value of path. For common double-extensions like .tar.gz and
  232. // .user.js, this method returns the combined extension. For a single
  233. // component, use FinalExtension().
  234. // new_path = path.RemoveExtension().value().append(path.Extension());
  235. // ASSERT(new_path == path.value());
  236. // NOTE: this is different from the original file_util implementation which
  237. // returned the extension without a leading "." ("jpg" instead of ".jpg")
  238. StringType Extension() const WARN_UNUSED_RESULT;
  239. // Returns the path's file extension, as in Extension(), but will
  240. // never return a double extension.
  241. //
  242. // TODO(davidben): Check all our extension-sensitive code to see if
  243. // we can rename this to Extension() and the other to something like
  244. // LongExtension(), defaulting to short extensions and leaving the
  245. // long "extensions" to logic like base::GetUniquePathNumber().
  246. StringType FinalExtension() const WARN_UNUSED_RESULT;
  247. // Returns "C:\pics\jojo" for path "C:\pics\jojo.jpg"
  248. // NOTE: this is slightly different from the similar file_util implementation
  249. // which returned simply 'jojo'.
  250. FilePath RemoveExtension() const WARN_UNUSED_RESULT;
  251. // Removes the path's file extension, as in RemoveExtension(), but
  252. // ignores double extensions.
  253. FilePath RemoveFinalExtension() const WARN_UNUSED_RESULT;
  254. // Inserts |suffix| after the file name portion of |path| but before the
  255. // extension. Returns "" if BaseName() == "." or "..".
  256. // Examples:
  257. // path == "C:\pics\jojo.jpg" suffix == " (1)", returns "C:\pics\jojo (1).jpg"
  258. // path == "jojo.jpg" suffix == " (1)", returns "jojo (1).jpg"
  259. // path == "C:\pics\jojo" suffix == " (1)", returns "C:\pics\jojo (1)"
  260. // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)"
  261. FilePath InsertBeforeExtension(
  262. StringPieceType suffix) const WARN_UNUSED_RESULT;
  263. FilePath InsertBeforeExtensionASCII(
  264. StringPiece suffix) const WARN_UNUSED_RESULT;
  265. // Adds |extension| to |file_name|. Returns the current FilePath if
  266. // |extension| is empty. Returns "" if BaseName() == "." or "..".
  267. FilePath AddExtension(StringPieceType extension) const WARN_UNUSED_RESULT;
  268. // Like above, but takes the extension as an ASCII string. See AppendASCII for
  269. // details on how this is handled.
  270. FilePath AddExtensionASCII(StringPiece extension) const WARN_UNUSED_RESULT;
  271. // Replaces the extension of |file_name| with |extension|. If |file_name|
  272. // does not have an extension, then |extension| is added. If |extension| is
  273. // empty, then the extension is removed from |file_name|.
  274. // Returns "" if BaseName() == "." or "..".
  275. FilePath ReplaceExtension(StringPieceType extension) const WARN_UNUSED_RESULT;
  276. // Returns true if the file path matches the specified extension. The test is
  277. // case insensitive. Don't forget the leading period if appropriate.
  278. bool MatchesExtension(StringPieceType extension) const;
  279. // Returns a FilePath by appending a separator and the supplied path
  280. // component to this object's path. Append takes care to avoid adding
  281. // excessive separators if this object's path already ends with a separator.
  282. // If this object's path is kCurrentDirectory, a new FilePath corresponding
  283. // only to |component| is returned. |component| must be a relative path;
  284. // it is an error to pass an absolute path.
  285. FilePath Append(StringPieceType component) const WARN_UNUSED_RESULT;
  286. FilePath Append(const FilePath& component) const WARN_UNUSED_RESULT;
  287. // Although Windows StringType is std::wstring, since the encoding it uses for
  288. // paths is well defined, it can handle ASCII path components as well.
  289. // Mac uses UTF8, and since ASCII is a subset of that, it works there as well.
  290. // On Linux, although it can use any 8-bit encoding for paths, we assume that
  291. // ASCII is a valid subset, regardless of the encoding, since many operating
  292. // system paths will always be ASCII.
  293. FilePath AppendASCII(StringPiece component) const WARN_UNUSED_RESULT;
  294. // Returns true if this FilePath contains an absolute path. On Windows, an
  295. // absolute path begins with either a drive letter specification followed by
  296. // a separator character, or with two separator characters. On POSIX
  297. // platforms, an absolute path begins with a separator character.
  298. bool IsAbsolute() const;
  299. // Returns true if the patch ends with a path separator character.
  300. bool EndsWithSeparator() const WARN_UNUSED_RESULT;
  301. // Returns a copy of this FilePath that ends with a trailing separator. If
  302. // the input path is empty, an empty FilePath will be returned.
  303. FilePath AsEndingWithSeparator() const WARN_UNUSED_RESULT;
  304. // Returns a copy of this FilePath that does not end with a trailing
  305. // separator.
  306. FilePath StripTrailingSeparators() const WARN_UNUSED_RESULT;
  307. // Returns true if this FilePath contains an attempt to reference a parent
  308. // directory (e.g. has a path component that is "..").
  309. bool ReferencesParent() const;
  310. // Return a Unicode human-readable version of this path.
  311. // Warning: you can *not*, in general, go from a display name back to a real
  312. // path. Only use this when displaying paths to users, not just when you
  313. // want to stuff a string16 into some other API.
  314. string16 LossyDisplayName() const;
  315. // Return the path as ASCII, or the empty string if the path is not ASCII.
  316. // This should only be used for cases where the FilePath is representing a
  317. // known-ASCII filename.
  318. std::string MaybeAsASCII() const;
  319. // Return the path as UTF-8.
  320. //
  321. // This function is *unsafe* as there is no way to tell what encoding is
  322. // used in file names on POSIX systems other than Mac and Chrome OS,
  323. // although UTF-8 is practically used everywhere these days. To mitigate
  324. // the encoding issue, this function internally calls
  325. // SysNativeMBToWide() on POSIX systems other than Mac and Chrome OS,
  326. // per assumption that the current locale's encoding is used in file
  327. // names, but this isn't a perfect solution.
  328. //
  329. // Once it becomes safe to to stop caring about non-UTF-8 file names,
  330. // the SysNativeMBToWide() hack will be removed from the code, along
  331. // with "Unsafe" in the function name.
  332. std::string AsUTF8Unsafe() const;
  333. // Similar to AsUTF8Unsafe, but returns UTF-16 instead.
  334. string16 AsUTF16Unsafe() const;
  335. // Returns a FilePath object from a path name in UTF-8. This function
  336. // should only be used for cases where you are sure that the input
  337. // string is UTF-8.
  338. //
  339. // Like AsUTF8Unsafe(), this function is unsafe. This function
  340. // internally calls SysWideToNativeMB() on POSIX systems other than Mac
  341. // and Chrome OS, to mitigate the encoding issue. See the comment at
  342. // AsUTF8Unsafe() for details.
  343. static FilePath FromUTF8Unsafe(StringPiece utf8);
  344. // Similar to FromUTF8Unsafe, but accepts UTF-16 instead.
  345. static FilePath FromUTF16Unsafe(StringPiece16 utf16);
  346. void WriteToPickle(Pickle* pickle) const;
  347. bool ReadFromPickle(PickleIterator* iter);
  348. // Normalize all path separators to backslash on Windows
  349. // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
  350. FilePath NormalizePathSeparators() const;
  351. // Normalize all path separattors to given type on Windows
  352. // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
  353. FilePath NormalizePathSeparatorsTo(CharType separator) const;
  354. // Compare two strings in the same way the file system does.
  355. // Note that these always ignore case, even on file systems that are case-
  356. // sensitive. If case-sensitive comparison is ever needed, add corresponding
  357. // methods here.
  358. // The methods are written as a static method so that they can also be used
  359. // on parts of a file path, e.g., just the extension.
  360. // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and
  361. // greater-than respectively.
  362. static int CompareIgnoreCase(StringPieceType string1,
  363. StringPieceType string2);
  364. static bool CompareEqualIgnoreCase(StringPieceType string1,
  365. StringPieceType string2) {
  366. return CompareIgnoreCase(string1, string2) == 0;
  367. }
  368. static bool CompareLessIgnoreCase(StringPieceType string1,
  369. StringPieceType string2) {
  370. return CompareIgnoreCase(string1, string2) < 0;
  371. }
  372. #if defined(OS_APPLE)
  373. // Returns the string in the special canonical decomposed form as defined for
  374. // HFS, which is close to, but not quite, decomposition form D. See
  375. // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties
  376. // for further comments.
  377. // Returns the epmty string if the conversion failed.
  378. static StringType GetHFSDecomposedForm(StringPieceType string);
  379. // Special UTF-8 version of FastUnicodeCompare. Cf:
  380. // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
  381. // IMPORTANT: The input strings must be in the special HFS decomposed form!
  382. // (cf. above GetHFSDecomposedForm method)
  383. static int HFSFastUnicodeCompare(StringPieceType string1,
  384. StringPieceType string2);
  385. #endif
  386. #if defined(OS_ANDROID)
  387. // On android, file selection dialog can return a file with content uri
  388. // scheme(starting with content://). Content uri needs to be opened with
  389. // ContentResolver to guarantee that the app has appropriate permissions
  390. // to access it.
  391. // Returns true if the path is a content uri, or false otherwise.
  392. bool IsContentUri() const;
  393. #endif
  394. private:
  395. // Remove trailing separators from this object. If the path is absolute, it
  396. // will never be stripped any more than to refer to the absolute root
  397. // directory, so "////" will become "/", not "". A leading pair of
  398. // separators is never stripped, to support alternate roots. This is used to
  399. // support UNC paths on Windows.
  400. void StripTrailingSeparatorsInternal();
  401. StringType path_;
  402. };
  403. BASE_EXPORT std::ostream& operator<<(std::ostream& out,
  404. const FilePath& file_path);
  405. } // namespace base
  406. namespace std {
  407. template <>
  408. struct hash<base::FilePath> {
  409. typedef base::FilePath argument_type;
  410. typedef std::size_t result_type;
  411. result_type operator()(argument_type const& f) const {
  412. return hash<base::FilePath::StringType>()(f.value());
  413. }
  414. };
  415. } // namespace std
  416. #endif // BASE_FILES_FILE_PATH_H_