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