WebKit roll 109146:109201
[chromium-blink-merge.git] / base / file_path.h
blobbde3cec30c21e53002408469446a3761b1717654
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.
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[] 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 // 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.
24 // For more arcane bits of path trivia, see below.
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.
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.
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 wchar_t[]-based
54 // pathnames on Windows.
56 // Because a FilePath object should not be instantiated at the global scope,
57 // instead, use a FilePath::CharType[] and initialize it with
58 // FILE_PATH_LITERAL. At runtime, a FilePath object can be created from the
59 // character array. Example:
61 // | const FilePath::CharType kLogFileName[] = FILE_PATH_LITERAL("log.txt");
62 // |
63 // | void Function() {
64 // | FilePath log_file_path(kLogFileName);
65 // | [...]
66 // | }
68 // WARNING: FilePaths should ALWAYS be displayed with LTR directionality, even
69 // when the UI language is RTL. This means you always need to pass filepaths
70 // through base::i18n::WrapPathWithLTRFormatting() before displaying it in the
71 // RTL UI.
73 // This is a very common source of bugs, please try to keep this in mind.
75 // ARCANE BITS OF PATH TRIVIA
77 // - A double leading slash is actually part of the POSIX standard. Systems
78 // are allowed to treat // as an alternate root, as Windows does for UNC
79 // (network share) paths. Most POSIX systems don't do anything special
80 // with two leading slashes, but FilePath handles this case properly
81 // in case it ever comes across such a system. FilePath needs this support
82 // for Windows UNC paths, anyway.
83 // References:
84 // The Open Group Base Specifications Issue 7, sections 3.266 ("Pathname")
85 // and 4.12 ("Pathname Resolution"), available at:
86 // http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_266
87 // http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
89 // - Windows treats c:\\ the same way it treats \\. This was intended to
90 // allow older applications that require drive letters to support UNC paths
91 // like \\server\share\path, by permitting c:\\server\share\path as an
92 // equivalent. Since the OS treats these paths specially, FilePath needs
93 // to do the same. Since Windows can use either / or \ as the separator,
94 // FilePath treats c://, c:\\, //, and \\ all equivalently.
95 // Reference:
96 // The Old New Thing, "Why is a drive letter permitted in front of UNC
97 // paths (sometimes)?", available at:
98 // http://blogs.msdn.com/oldnewthing/archive/2005/11/22/495740.aspx
100 #ifndef BASE_FILE_PATH_H_
101 #define BASE_FILE_PATH_H_
102 #pragma once
104 #include <stddef.h>
105 #include <string>
106 #include <vector>
108 #include "base/base_export.h"
109 #include "base/compiler_specific.h"
110 #include "base/hash_tables.h"
111 #include "base/string16.h"
112 #include "base/string_piece.h" // For implicit conversions.
113 #include "build/build_config.h"
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
124 class Pickle;
126 // An abstraction to isolate users from the differences between native
127 // pathnames on different platforms.
128 class BASE_EXPORT FilePath {
129 public:
130 #if defined(OS_POSIX)
131 // On most platforms, native pathnames are char arrays, and the encoding
132 // may or may not be specified. On Mac OS X, native pathnames are encoded
133 // in UTF-8.
134 typedef std::string StringType;
135 #elif defined(OS_WIN)
136 // On Windows, for Unicode-aware applications, native pathnames are wchar_t
137 // arrays encoded in UTF-16.
138 typedef std::wstring StringType;
139 #endif // OS_WIN
141 typedef StringType::value_type CharType;
143 // Null-terminated array of separators used to separate components in
144 // hierarchical paths. Each character in this array is a valid separator,
145 // but kSeparators[0] is treated as the canonical separator and will be used
146 // when composing pathnames.
147 static const CharType kSeparators[];
149 // A special path component meaning "this directory."
150 static const CharType kCurrentDirectory[];
152 // A special path component meaning "the parent directory."
153 static const CharType kParentDirectory[];
155 // The character used to identify a file extension.
156 static const CharType kExtensionSeparator;
158 FilePath();
159 FilePath(const FilePath& that);
160 explicit FilePath(const StringType& path);
161 ~FilePath();
162 FilePath& operator=(const FilePath& that);
164 bool operator==(const FilePath& that) const;
166 bool operator!=(const FilePath& that) const;
168 // Required for some STL containers and operations
169 bool operator<(const FilePath& that) const {
170 return path_ < that.path_;
173 const StringType& value() const { return path_; }
175 bool empty() const { return path_.empty(); }
177 void clear() { path_.clear(); }
179 // Returns true if |character| is in kSeparators.
180 static bool IsSeparator(CharType character);
182 // Returns a vector of all of the components of the provided path. It is
183 // equivalent to calling DirName().value() on the path's root component,
184 // and BaseName().value() on each child component.
185 void GetComponents(std::vector<FilePath::StringType>* components) const;
187 // Returns true if this FilePath is a strict parent of the |child|. Absolute
188 // and relative paths are accepted i.e. is /foo parent to /foo/bar and
189 // is foo parent to foo/bar. Does not convert paths to absolute, follow
190 // symlinks or directory navigation (e.g. ".."). A path is *NOT* its own
191 // parent.
192 bool IsParent(const FilePath& child) const;
194 // If IsParent(child) holds, appends to path (if non-NULL) the
195 // relative path to child and returns true. For example, if parent
196 // holds "/Users/johndoe/Library/Application Support", child holds
197 // "/Users/johndoe/Library/Application Support/Google/Chrome/Default", and
198 // *path holds "/Users/johndoe/Library/Caches", then after
199 // parent.AppendRelativePath(child, path) is called *path will hold
200 // "/Users/johndoe/Library/Caches/Google/Chrome/Default". Otherwise,
201 // returns false.
202 bool AppendRelativePath(const FilePath& child, FilePath* path) const;
204 // Returns a FilePath corresponding to the directory containing the path
205 // named by this object, stripping away the file component. If this object
206 // only contains one component, returns a FilePath identifying
207 // kCurrentDirectory. If this object already refers to the root directory,
208 // returns a FilePath identifying the root directory.
209 FilePath DirName() const WARN_UNUSED_RESULT;
211 // Returns a FilePath corresponding to the last path component of this
212 // object, either a file or a directory. If this object already refers to
213 // the root directory, returns a FilePath identifying the root directory;
214 // this is the only situation in which BaseName will return an absolute path.
215 FilePath BaseName() const WARN_UNUSED_RESULT;
217 // Returns ".jpg" for path "C:\pics\jojo.jpg", or an empty string if
218 // the file has no extension. If non-empty, Extension() will always start
219 // with precisely one ".". The following code should always work regardless
220 // of the value of path.
221 // new_path = path.RemoveExtension().value().append(path.Extension());
222 // ASSERT(new_path == path.value());
223 // NOTE: this is different from the original file_util implementation which
224 // returned the extension without a leading "." ("jpg" instead of ".jpg")
225 StringType Extension() const;
227 // Returns "C:\pics\jojo" for path "C:\pics\jojo.jpg"
228 // NOTE: this is slightly different from the similar file_util implementation
229 // which returned simply 'jojo'.
230 FilePath RemoveExtension() const WARN_UNUSED_RESULT;
232 // Inserts |suffix| after the file name portion of |path| but before the
233 // extension. Returns "" if BaseName() == "." or "..".
234 // Examples:
235 // path == "C:\pics\jojo.jpg" suffix == " (1)", returns "C:\pics\jojo (1).jpg"
236 // path == "jojo.jpg" suffix == " (1)", returns "jojo (1).jpg"
237 // path == "C:\pics\jojo" suffix == " (1)", returns "C:\pics\jojo (1)"
238 // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)"
239 FilePath InsertBeforeExtension(
240 const StringType& suffix) const WARN_UNUSED_RESULT;
241 FilePath InsertBeforeExtensionASCII(
242 const base::StringPiece& suffix) const WARN_UNUSED_RESULT;
244 // Replaces the extension of |file_name| with |extension|. If |file_name|
245 // does not have an extension, them |extension| is added. If |extension| is
246 // empty, then the extension is removed from |file_name|.
247 // Returns "" if BaseName() == "." or "..".
248 FilePath ReplaceExtension(
249 const StringType& extension) const WARN_UNUSED_RESULT;
251 // Returns true if the file path matches the specified extension. The test is
252 // case insensitive. Don't forget the leading period if appropriate.
253 bool MatchesExtension(const StringType& extension) const;
255 // Returns a FilePath by appending a separator and the supplied path
256 // component to this object's path. Append takes care to avoid adding
257 // excessive separators if this object's path already ends with a separator.
258 // If this object's path is kCurrentDirectory, a new FilePath corresponding
259 // only to |component| is returned. |component| must be a relative path;
260 // it is an error to pass an absolute path.
261 FilePath Append(const StringType& component) const WARN_UNUSED_RESULT;
262 FilePath Append(const FilePath& component) const WARN_UNUSED_RESULT;
264 // Although Windows StringType is std::wstring, since the encoding it uses for
265 // paths is well defined, it can handle ASCII path components as well.
266 // Mac uses UTF8, and since ASCII is a subset of that, it works there as well.
267 // On Linux, although it can use any 8-bit encoding for paths, we assume that
268 // ASCII is a valid subset, regardless of the encoding, since many operating
269 // system paths will always be ASCII.
270 FilePath AppendASCII(const base::StringPiece& component)
271 const WARN_UNUSED_RESULT;
273 // Returns true if this FilePath contains an absolute path. On Windows, an
274 // absolute path begins with either a drive letter specification followed by
275 // a separator character, or with two separator characters. On POSIX
276 // platforms, an absolute path begins with a separator character.
277 bool IsAbsolute() const;
279 // Returns a copy of this FilePath that does not end with a trailing
280 // separator.
281 FilePath StripTrailingSeparators() const WARN_UNUSED_RESULT;
283 // Returns true if this FilePath contains any attempt to reference a parent
284 // directory (i.e. has a path component that is ".."
285 bool ReferencesParent() const;
287 // Return a Unicode human-readable version of this path.
288 // Warning: you can *not*, in general, go from a display name back to a real
289 // path. Only use this when displaying paths to users, not just when you
290 // want to stuff a string16 into some other API.
291 string16 LossyDisplayName() const;
293 // Return the path as ASCII, or the empty string if the path is not ASCII.
294 // This should only be used for cases where the FilePath is representing a
295 // known-ASCII filename.
296 std::string MaybeAsASCII() const;
298 // Return the path as UTF-8.
300 // This function is *unsafe* as there is no way to tell what encoding is
301 // used in file names on POSIX systems other than Mac and Chrome OS,
302 // although UTF-8 is practically used everywhere these days. To mitigate
303 // the encoding issue, this function internally calls
304 // SysNativeMBToWide() on POSIX systems other than Mac and Chrome OS,
305 // per assumption that the current locale's encoding is used in file
306 // names, but this isn't a perfect solution.
308 // Once it becomes safe to to stop caring about non-UTF-8 file names,
309 // the SysNativeMBToWide() hack will be removed from the code, along
310 // with "Unsafe" in the function name.
311 std::string AsUTF8Unsafe() const;
313 // Older Chromium code assumes that paths are always wstrings.
314 // This function converts wstrings to FilePaths, and is
315 // useful to smooth porting that old code to the FilePath API.
316 // It has "Hack" its name so people feel bad about using it.
317 // http://code.google.com/p/chromium/issues/detail?id=24672
319 // If you are trying to be a good citizen and remove these, ask yourself:
320 // - Am I interacting with other Chrome code that deals with files? Then
321 // try to convert the API into using FilePath.
322 // - Am I interacting with OS-native calls? Then use value() to get at an
323 // OS-native string format.
324 // - Am I using well-known file names, like "config.ini"? Then use the
325 // ASCII functions (we require paths to always be supersets of ASCII).
326 // - Am I displaying a string to the user in some UI? Then use the
327 // LossyDisplayName() function, but keep in mind that you can't
328 // ever use the result of that again as a path.
329 static FilePath FromWStringHack(const std::wstring& wstring);
331 // Returns a FilePath object from a path name in UTF-8. This function
332 // should only be used for cases where you are sure that the input
333 // string is UTF-8.
335 // Like AsUTF8Unsafe(), this function is unsafe. This function
336 // internally calls SysWideToNativeMB() on POSIX systems other than Mac
337 // and Chrome OS, to mitigate the encoding issue. See the comment at
338 // AsUTF8Unsafe() for details.
339 static FilePath FromUTF8Unsafe(const std::string& utf8);
341 void WriteToPickle(Pickle* pickle);
342 bool ReadFromPickle(Pickle* pickle, void** iter);
344 // Normalize all path separators to backslash on Windows
345 // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
346 FilePath NormalizePathSeparators() const;
348 // Compare two strings in the same way the file system does.
349 // Note that these always ignore case, even on file systems that are case-
350 // sensitive. If case-sensitive comparison is ever needed, add corresponding
351 // methods here.
352 // The methods are written as a static method so that they can also be used
353 // on parts of a file path, e.g., just the extension.
354 // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and
355 // greater-than respectively.
356 static int CompareIgnoreCase(const StringType& string1,
357 const StringType& string2);
358 static bool CompareEqualIgnoreCase(const StringType& string1,
359 const StringType& string2) {
360 return CompareIgnoreCase(string1, string2) == 0;
362 static bool CompareLessIgnoreCase(const StringType& string1,
363 const StringType& string2) {
364 return CompareIgnoreCase(string1, string2) < 0;
367 #if defined(OS_MACOSX)
368 // Returns the string in the special canonical decomposed form as defined for
369 // HFS, which is close to, but not quite, decomposition form D. See
370 // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties
371 // for further comments.
372 // Returns the epmty string if the conversion failed.
373 static StringType GetHFSDecomposedForm(const FilePath::StringType& string);
375 // Special UTF-8 version of FastUnicodeCompare. Cf:
376 // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
377 // IMPORTANT: The input strings must be in the special HFS decomposed form!
378 // (cf. above GetHFSDecomposedForm method)
379 static int HFSFastUnicodeCompare(const StringType& string1,
380 const StringType& string2);
381 #endif
383 private:
384 // Remove trailing separators from this object. If the path is absolute, it
385 // will never be stripped any more than to refer to the absolute root
386 // directory, so "////" will become "/", not "". A leading pair of
387 // separators is never stripped, to support alternate roots. This is used to
388 // support UNC paths on Windows.
389 void StripTrailingSeparatorsInternal();
391 StringType path_;
394 // Macros for string literal initialization of FilePath::CharType[], and for
395 // using a FilePath::CharType[] in a printf-style format string.
396 #if defined(OS_POSIX)
397 #define FILE_PATH_LITERAL(x) x
398 #define PRFilePath "s"
399 #define PRFilePathLiteral "%s"
400 #elif defined(OS_WIN)
401 #define FILE_PATH_LITERAL(x) L ## x
402 #define PRFilePath "ls"
403 #define PRFilePathLiteral L"%ls"
404 #endif // OS_WIN
406 // Provide a hash function so that hash_sets and maps can contain FilePath
407 // objects.
408 namespace BASE_HASH_NAMESPACE {
409 #if defined(COMPILER_GCC)
411 template<>
412 struct hash<FilePath> {
413 size_t operator()(const FilePath& f) const {
414 return hash<FilePath::StringType>()(f.value());
418 #elif defined(COMPILER_MSVC)
420 inline size_t hash_value(const FilePath& f) {
421 return hash_value(f.value());
424 #endif // COMPILER
426 } // namespace BASE_HASH_NAMESPACE
428 #endif // BASE_FILE_PATH_H_