1 // Copyright (c) 2010 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.
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
11 // --------------- ----------------------------------
12 // Fundamental type char[] wchar_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
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 // Linux does not specify an encoding, but in practice, the locale's
21 // character set may be used.
23 // For more arcane bits of path trivia, see below.
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.
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.
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.
55 // Because a FilePath object should not be instantiated at the global scope,
56 // instead, use a FilePath::CharType[] and initialize it with
57 // FILE_PATH_LITERAL. At runtime, a FilePath object can be created from the
58 // character array. Example:
60 // | const FilePath::CharType kLogFileName[] = FILE_PATH_LITERAL("log.txt");
62 // | void Function() {
63 // | FilePath log_file_path(kLogFileName);
67 // WARNING: FilePaths should ALWAYS be displayed with LTR directionality, even
68 // when the UI language is RTL. This means you always need to pass filepaths
69 // through base::i18n::WrapPathWithLTRFormatting() before displaying it in the
72 // This is a very common source of bugs, please try to keep this in mind.
74 // ARCANE BITS OF PATH TRIVIA
76 // - A double leading slash is actually part of the POSIX standard. Systems
77 // are allowed to treat // as an alternate root, as Windows does for UNC
78 // (network share) paths. Most POSIX systems don't do anything special
79 // with two leading slashes, but FilePath handles this case properly
80 // in case it ever comes across such a system. FilePath needs this support
81 // for Windows UNC paths, anyway.
83 // The Open Group Base Specifications Issue 7, sections 3.266 ("Pathname")
84 // and 4.12 ("Pathname Resolution"), available at:
85 // http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_266
86 // http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
88 // - Windows treats c:\\ the same way it treats \\. This was intended to
89 // allow older applications that require drive letters to support UNC paths
90 // like \\server\share\path, by permitting c:\\server\share\path as an
91 // equivalent. Since the OS treats these paths specially, FilePath needs
92 // to do the same. Since Windows can use either / or \ as the separator,
93 // FilePath treats c://, c:\\, //, and \\ all equivalently.
95 // The Old New Thing, "Why is a drive letter permitted in front of UNC
96 // paths (sometimes)?", available at:
97 // http://blogs.msdn.com/oldnewthing/archive/2005/11/22/495740.aspx
99 #ifndef BASE_FILE_PATH_H_
100 #define BASE_FILE_PATH_H_
106 #include "base/basictypes.h"
107 #include "base/compiler_specific.h"
108 #include "base/hash_tables.h"
109 #include "base/string_piece.h" // For implicit conversions.
111 // Windows-style drive letter support and pathname separator characters can be
112 // enabled and disabled independently, to aid testing. These #defines are
113 // here so that the same setting can be used in both the implementation and
116 #define FILE_PATH_USES_DRIVE_LETTERS
117 #define FILE_PATH_USES_WIN_SEPARATORS
122 // An abstraction to isolate users from the differences between native
123 // pathnames on different platforms.
126 #if defined(OS_POSIX)
127 // On most platforms, native pathnames are char arrays, and the encoding
128 // may or may not be specified. On Mac OS X, native pathnames are encoded
130 typedef std::string StringType
;
131 #elif defined(OS_WIN)
132 // On Windows, for Unicode-aware applications, native pathnames are wchar_t
133 // arrays encoded in UTF-16.
134 typedef std::wstring StringType
;
137 typedef StringType::value_type CharType
;
139 // Null-terminated array of separators used to separate components in
140 // hierarchical paths. Each character in this array is a valid separator,
141 // but kSeparators[0] is treated as the canonical separator and will be used
142 // when composing pathnames.
143 static const CharType kSeparators
[];
145 // A special path component meaning "this directory."
146 static const CharType kCurrentDirectory
[];
148 // A special path component meaning "the parent directory."
149 static const CharType kParentDirectory
[];
151 // The character used to identify a file extension.
152 static const CharType kExtensionSeparator
;
155 FilePath(const FilePath
& that
);
156 explicit FilePath(const StringType
& path
);
158 FilePath
& operator=(const FilePath
& that
);
160 bool operator==(const FilePath
& that
) const;
162 bool operator!=(const FilePath
& that
) const;
164 // Required for some STL containers and operations
165 bool operator<(const FilePath
& that
) const {
166 return path_
< that
.path_
;
169 const StringType
& value() const { return path_
; }
171 bool empty() const { return path_
.empty(); }
173 void clear() { path_
.clear(); }
175 // Returns true if |character| is in kSeparators.
176 static bool IsSeparator(CharType character
);
178 // Returns a vector of all of the components of the provided path. It is
179 // equivalent to calling DirName().value() on the path's root component,
180 // and BaseName().value() on each child component.
181 void GetComponents(std::vector
<FilePath::StringType
>* components
) const;
183 // Returns true if this FilePath is a strict parent of the |child|. Absolute
184 // and relative paths are accepted i.e. is /foo parent to /foo/bar and
185 // is foo parent to foo/bar. Does not convert paths to absolute, follow
186 // symlinks or directory navigation (e.g. ".."). A path is *NOT* its own
188 bool IsParent(const FilePath
& child
) const;
190 // If IsParent(child) holds, appends to path (if non-NULL) the
191 // relative path to child and returns true. For example, if parent
192 // holds "/Users/johndoe/Library/Application Support", child holds
193 // "/Users/johndoe/Library/Application Support/Google/Chrome/Default", and
194 // *path holds "/Users/johndoe/Library/Caches", then after
195 // parent.AppendRelativePath(child, path) is called *path will hold
196 // "/Users/johndoe/Library/Caches/Google/Chrome/Default". Otherwise,
198 bool AppendRelativePath(const FilePath
& child
, FilePath
* path
) const;
200 // Returns a FilePath corresponding to the directory containing the path
201 // named by this object, stripping away the file component. If this object
202 // only contains one component, returns a FilePath identifying
203 // kCurrentDirectory. If this object already refers to the root directory,
204 // returns a FilePath identifying the root directory.
205 FilePath
DirName() const;
207 // Returns a FilePath corresponding to the last path component of this
208 // object, either a file or a directory. If this object already refers to
209 // the root directory, returns a FilePath identifying the root directory;
210 // this is the only situation in which BaseName will return an absolute path.
211 FilePath
BaseName() const;
213 // Returns ".jpg" for path "C:\pics\jojo.jpg", or an empty string if
214 // the file has no extension. If non-empty, Extension() will always start
215 // with precisely one ".". The following code should always work regardless
216 // of the value of path.
217 // new_path = path.RemoveExtension().value().append(path.Extension());
218 // ASSERT(new_path == path.value());
219 // NOTE: this is different from the original file_util implementation which
220 // returned the extension without a leading "." ("jpg" instead of ".jpg")
221 StringType
Extension() const;
223 // Returns "C:\pics\jojo" for path "C:\pics\jojo.jpg"
224 // NOTE: this is slightly different from the similar file_util implementation
225 // which returned simply 'jojo'.
226 FilePath
RemoveExtension() const;
228 // Inserts |suffix| after the file name portion of |path| but before the
229 // extension. Returns "" if BaseName() == "." or "..".
231 // path == "C:\pics\jojo.jpg" suffix == " (1)", returns "C:\pics\jojo (1).jpg"
232 // path == "jojo.jpg" suffix == " (1)", returns "jojo (1).jpg"
233 // path == "C:\pics\jojo" suffix == " (1)", returns "C:\pics\jojo (1)"
234 // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)"
235 FilePath
InsertBeforeExtension(const StringType
& suffix
) const;
236 FilePath
InsertBeforeExtensionASCII(const base::StringPiece
& suffix
) const;
238 // Replaces the extension of |file_name| with |extension|. If |file_name|
239 // does not have an extension, them |extension| is added. If |extension| is
240 // empty, then the extension is removed from |file_name|.
241 // Returns "" if BaseName() == "." or "..".
242 FilePath
ReplaceExtension(const StringType
& extension
) const;
244 // Returns true if the file path matches the specified extension. The test is
245 // case insensitive. Don't forget the leading period if appropriate.
246 bool MatchesExtension(const StringType
& extension
) const;
248 // Returns a FilePath by appending a separator and the supplied path
249 // component to this object's path. Append takes care to avoid adding
250 // excessive separators if this object's path already ends with a separator.
251 // If this object's path is kCurrentDirectory, a new FilePath corresponding
252 // only to |component| is returned. |component| must be a relative path;
253 // it is an error to pass an absolute path.
254 FilePath
Append(const StringType
& component
) const WARN_UNUSED_RESULT
;
255 FilePath
Append(const FilePath
& component
) const WARN_UNUSED_RESULT
;
257 // Although Windows StringType is std::wstring, since the encoding it uses for
258 // paths is well defined, it can handle ASCII path components as well.
259 // Mac uses UTF8, and since ASCII is a subset of that, it works there as well.
260 // On Linux, although it can use any 8-bit encoding for paths, we assume that
261 // ASCII is a valid subset, regardless of the encoding, since many operating
262 // system paths will always be ASCII.
263 FilePath
AppendASCII(const base::StringPiece
& component
)
264 const WARN_UNUSED_RESULT
;
266 // Returns true if this FilePath contains an absolute path. On Windows, an
267 // absolute path begins with either a drive letter specification followed by
268 // a separator character, or with two separator characters. On POSIX
269 // platforms, an absolute path begins with a separator character.
270 bool IsAbsolute() const;
272 // Returns a copy of this FilePath that does not end with a trailing
274 FilePath
StripTrailingSeparators() const;
276 // Returns true if this FilePath contains any attempt to reference a parent
277 // directory (i.e. has a path component that is ".."
278 bool ReferencesParent() const;
280 // Older Chromium code assumes that paths are always wstrings.
281 // These functions convert wstrings to/from FilePaths, and are
282 // useful to smooth porting that old code to the FilePath API.
283 // They have "Hack" in their names so people feel bad about using them.
284 // http://code.google.com/p/chromium/issues/detail?id=24672
286 // If you are trying to be a good citizen and remove these, ask yourself:
287 // - Am I interacting with other Chrome code that deals with files? Then
288 // try to convert the API into using FilePath.
289 // - Am I interacting with OS-native calls? Then use value() to get at an
290 // OS-native string format.
291 // - Am I using well-known file names, like "config.ini"? Then use the
292 // ASCII functions (we require paths to always be supersets of ASCII).
293 static FilePath
FromWStringHack(const std::wstring
& wstring
);
294 std::wstring
ToWStringHack() const;
296 // Static helper method to write a StringType to a pickle.
297 static void WriteStringTypeToPickle(Pickle
* pickle
,
298 const FilePath::StringType
& path
);
299 static bool ReadStringTypeFromPickle(Pickle
* pickle
, void** iter
,
300 FilePath::StringType
* path
);
302 void WriteToPickle(Pickle
* pickle
);
303 bool ReadFromPickle(Pickle
* pickle
, void** iter
);
305 #if defined(FILE_PATH_USES_WIN_SEPARATORS)
306 // Normalize all path separators to backslash.
307 FilePath
NormalizeWindowsPathSeparators() const;
310 // Compare two strings in the same way the file system does.
311 // Note that these always ignore case, even on file systems that are case-
312 // sensitive. If case-sensitive comparison is ever needed, add corresponding
314 // The methods are written as a static method so that they can also be used
315 // on parts of a file path, e.g., just the extension.
316 // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and
317 // greater-than respectively.
318 static int CompareIgnoreCase(const StringType
& string1
,
319 const StringType
& string2
);
320 static bool CompareEqualIgnoreCase(const StringType
& string1
,
321 const StringType
& string2
) {
322 return CompareIgnoreCase(string1
, string2
) == 0;
324 static bool CompareLessIgnoreCase(const StringType
& string1
,
325 const StringType
& string2
) {
326 return CompareIgnoreCase(string1
, string2
) < 0;
329 #if defined(OS_MACOSX)
330 // Returns the string in the special canonical decomposed form as defined for
331 // HFS, which is close to, but not quite, decomposition form D. See
332 // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties
333 // for further comments.
334 // Returns the epmty string if the conversion failed.
335 static StringType
GetHFSDecomposedForm(const FilePath::StringType
& string
);
337 // Special UTF-8 version of FastUnicodeCompare. Cf:
338 // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
339 // IMPORTANT: The input strings must be in the special HFS decomposed form!
340 // (cf. above GetHFSDecomposedForm method)
341 static int HFSFastUnicodeCompare(const StringType
& string1
,
342 const StringType
& string2
);
346 // Remove trailing separators from this object. If the path is absolute, it
347 // will never be stripped any more than to refer to the absolute root
348 // directory, so "////" will become "/", not "". A leading pair of
349 // separators is never stripped, to support alternate roots. This is used to
350 // support UNC paths on Windows.
351 void StripTrailingSeparatorsInternal();
356 // Macros for string literal initialization of FilePath::CharType[], and for
357 // using a FilePath::CharType[] in a printf-style format string.
358 #if defined(OS_POSIX)
359 #define FILE_PATH_LITERAL(x) x
360 #define PRFilePath "s"
361 #define PRFilePathLiteral "%s"
362 #elif defined(OS_WIN)
363 #define FILE_PATH_LITERAL(x) L ## x
364 #define PRFilePath "ls"
365 #define PRFilePathLiteral L"%ls"
368 // Provide a hash function so that hash_sets and maps can contain FilePath
370 #if defined(COMPILER_GCC)
371 namespace __gnu_cxx
{
374 struct hash
<FilePath
> {
375 std::size_t operator()(const FilePath
& f
) const {
376 return hash
<FilePath::StringType
>()(f
.value());
380 } // namespace __gnu_cxx
381 #elif defined(COMPILER_MSVC)
384 inline size_t hash_value(const FilePath
& f
) {
385 return hash_value(f
.value());
388 } // namespace stdext
391 #endif // BASE_FILE_PATH_H_