Update V8 to version 4.7.58.
[chromium-blink-merge.git] / base / files / file_path.h
blob25b8391c01094387ed583ad64cacb8a611790723
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 // As a precaution against premature truncation, paths can't contain NULs.
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:
63 // | const FilePath::CharType kLogFileName[] = FILE_PATH_LITERAL("log.txt");
64 // |
65 // | void Function() {
66 // | FilePath log_file_path(kLogFileName);
67 // | [...]
68 // | }
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.
75 // This is a very common source of bugs, please try to keep this in mind.
77 // ARCANE BITS OF PATH TRIVIA
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
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
102 #ifndef BASE_FILES_FILE_PATH_H_
103 #define BASE_FILES_FILE_PATH_H_
105 #include <stddef.h>
107 #include <iosfwd>
108 #include <string>
109 #include <vector>
111 #include "base/base_export.h"
112 #include "base/compiler_specific.h"
113 #include "base/containers/hash_tables.h"
114 #include "base/strings/string16.h"
115 #include "base/strings/string_piece.h"
116 #include "build/build_config.h"
118 // Windows-style drive letter support and pathname separator characters can be
119 // enabled and disabled independently, to aid testing. These #defines are
120 // here so that the same setting can be used in both the implementation and
121 // in the unit test.
122 #if defined(OS_WIN)
123 #define FILE_PATH_USES_DRIVE_LETTERS
124 #define FILE_PATH_USES_WIN_SEPARATORS
125 #endif // OS_WIN
127 namespace base {
129 class Pickle;
130 class PickleIterator;
132 // An abstraction to isolate users from the differences between native
133 // pathnames on different platforms.
134 class BASE_EXPORT FilePath {
135 public:
136 #if defined(OS_POSIX)
137 // On most platforms, native pathnames are char arrays, and the encoding
138 // may or may not be specified. On Mac OS X, native pathnames are encoded
139 // in UTF-8.
140 typedef std::string StringType;
141 #elif defined(OS_WIN)
142 // On Windows, for Unicode-aware applications, native pathnames are wchar_t
143 // arrays encoded in UTF-16.
144 typedef std::wstring StringType;
145 #endif // OS_WIN
147 typedef BasicStringPiece<StringType> StringPieceType;
148 typedef StringType::value_type CharType;
150 // Null-terminated array of separators used to separate components in
151 // hierarchical paths. Each character in this array is a valid separator,
152 // but kSeparators[0] is treated as the canonical separator and will be used
153 // when composing pathnames.
154 static const CharType kSeparators[];
156 // arraysize(kSeparators).
157 static const size_t kSeparatorsLength;
159 // A special path component meaning "this directory."
160 static const CharType kCurrentDirectory[];
162 // A special path component meaning "the parent directory."
163 static const CharType kParentDirectory[];
165 // The character used to identify a file extension.
166 static const CharType kExtensionSeparator;
168 FilePath();
169 FilePath(const FilePath& that);
170 explicit FilePath(StringPieceType path);
171 ~FilePath();
172 FilePath& operator=(const FilePath& that);
174 bool operator==(const FilePath& that) const;
176 bool operator!=(const FilePath& that) const;
178 // Required for some STL containers and operations
179 bool operator<(const FilePath& that) const {
180 return path_ < that.path_;
183 const StringType& value() const { return path_; }
185 bool empty() const { return path_.empty(); }
187 void clear() { path_.clear(); }
189 // Returns true if |character| is in kSeparators.
190 static bool IsSeparator(CharType character);
192 // Returns a vector of all of the components of the provided path. It is
193 // equivalent to calling DirName().value() on the path's root component,
194 // and BaseName().value() on each child component.
196 // To make sure this is lossless so we can differentiate absolute and
197 // relative paths, the root slash will be included even though no other
198 // slashes will be. The precise behavior is:
200 // Posix: "/foo/bar" -> [ "/", "foo", "bar" ]
201 // Windows: "C:\foo\bar" -> [ "C:", "\\", "foo", "bar" ]
202 void GetComponents(std::vector<FilePath::StringType>* components) const;
204 // Returns true if this FilePath is a strict parent of the |child|. Absolute
205 // and relative paths are accepted i.e. is /foo parent to /foo/bar and
206 // is foo parent to foo/bar. Does not convert paths to absolute, follow
207 // symlinks or directory navigation (e.g. ".."). A path is *NOT* its own
208 // parent.
209 bool IsParent(const FilePath& child) const;
211 // If IsParent(child) holds, appends to path (if non-NULL) the
212 // relative path to child and returns true. For example, if parent
213 // holds "/Users/johndoe/Library/Application Support", child holds
214 // "/Users/johndoe/Library/Application Support/Google/Chrome/Default", and
215 // *path holds "/Users/johndoe/Library/Caches", then after
216 // parent.AppendRelativePath(child, path) is called *path will hold
217 // "/Users/johndoe/Library/Caches/Google/Chrome/Default". Otherwise,
218 // returns false.
219 bool AppendRelativePath(const FilePath& child, FilePath* path) const;
221 // Returns a FilePath corresponding to the directory containing the path
222 // named by this object, stripping away the file component. If this object
223 // only contains one component, returns a FilePath identifying
224 // kCurrentDirectory. If this object already refers to the root directory,
225 // returns a FilePath identifying the root directory.
226 FilePath DirName() const WARN_UNUSED_RESULT;
228 // Returns a FilePath corresponding to the last path component of this
229 // object, either a file or a directory. If this object already refers to
230 // the root directory, returns a FilePath identifying the root directory;
231 // this is the only situation in which BaseName will return an absolute path.
232 FilePath BaseName() const WARN_UNUSED_RESULT;
234 // Returns ".jpg" for path "C:\pics\jojo.jpg", or an empty string if
235 // the file has no extension. If non-empty, Extension() will always start
236 // with precisely one ".". The following code should always work regardless
237 // of the value of path. For common double-extensions like .tar.gz and
238 // .user.js, this method returns the combined extension. For a single
239 // component, use FinalExtension().
240 // new_path = path.RemoveExtension().value().append(path.Extension());
241 // ASSERT(new_path == path.value());
242 // NOTE: this is different from the original file_util implementation which
243 // returned the extension without a leading "." ("jpg" instead of ".jpg")
244 StringType Extension() const WARN_UNUSED_RESULT;
246 // Returns the path's file extension, as in Extension(), but will
247 // never return a double extension.
249 // TODO(davidben): Check all our extension-sensitive code to see if
250 // we can rename this to Extension() and the other to something like
251 // LongExtension(), defaulting to short extensions and leaving the
252 // long "extensions" to logic like base::GetUniquePathNumber().
253 StringType FinalExtension() const WARN_UNUSED_RESULT;
255 // Returns "C:\pics\jojo" for path "C:\pics\jojo.jpg"
256 // NOTE: this is slightly different from the similar file_util implementation
257 // which returned simply 'jojo'.
258 FilePath RemoveExtension() const WARN_UNUSED_RESULT;
260 // Removes the path's file extension, as in RemoveExtension(), but
261 // ignores double extensions.
262 FilePath RemoveFinalExtension() const WARN_UNUSED_RESULT;
264 // Inserts |suffix| after the file name portion of |path| but before the
265 // extension. Returns "" if BaseName() == "." or "..".
266 // Examples:
267 // path == "C:\pics\jojo.jpg" suffix == " (1)", returns "C:\pics\jojo (1).jpg"
268 // path == "jojo.jpg" suffix == " (1)", returns "jojo (1).jpg"
269 // path == "C:\pics\jojo" suffix == " (1)", returns "C:\pics\jojo (1)"
270 // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)"
271 FilePath InsertBeforeExtension(
272 StringPieceType suffix) const WARN_UNUSED_RESULT;
273 FilePath InsertBeforeExtensionASCII(
274 StringPiece suffix) const WARN_UNUSED_RESULT;
276 // Adds |extension| to |file_name|. Returns the current FilePath if
277 // |extension| is empty. Returns "" if BaseName() == "." or "..".
278 FilePath AddExtension(StringPieceType extension) const WARN_UNUSED_RESULT;
280 // Replaces the extension of |file_name| with |extension|. If |file_name|
281 // does not have an extension, then |extension| is added. If |extension| is
282 // empty, then the extension is removed from |file_name|.
283 // Returns "" if BaseName() == "." or "..".
284 FilePath ReplaceExtension(StringPieceType extension) const WARN_UNUSED_RESULT;
286 // Returns true if the file path matches the specified extension. The test is
287 // case insensitive. Don't forget the leading period if appropriate.
288 bool MatchesExtension(StringPieceType extension) const;
290 // Returns a FilePath by appending a separator and the supplied path
291 // component to this object's path. Append takes care to avoid adding
292 // excessive separators if this object's path already ends with a separator.
293 // If this object's path is kCurrentDirectory, a new FilePath corresponding
294 // only to |component| is returned. |component| must be a relative path;
295 // it is an error to pass an absolute path.
296 FilePath Append(StringPieceType component) const WARN_UNUSED_RESULT;
297 FilePath Append(const FilePath& component) const WARN_UNUSED_RESULT;
299 // Although Windows StringType is std::wstring, since the encoding it uses for
300 // paths is well defined, it can handle ASCII path components as well.
301 // Mac uses UTF8, and since ASCII is a subset of that, it works there as well.
302 // On Linux, although it can use any 8-bit encoding for paths, we assume that
303 // ASCII is a valid subset, regardless of the encoding, since many operating
304 // system paths will always be ASCII.
305 FilePath AppendASCII(StringPiece component) const WARN_UNUSED_RESULT;
307 // Returns true if this FilePath contains an absolute path. On Windows, an
308 // absolute path begins with either a drive letter specification followed by
309 // a separator character, or with two separator characters. On POSIX
310 // platforms, an absolute path begins with a separator character.
311 bool IsAbsolute() const;
313 // Returns true if the patch ends with a path separator character.
314 bool EndsWithSeparator() const WARN_UNUSED_RESULT;
316 // Returns a copy of this FilePath that ends with a trailing separator. If
317 // the input path is empty, an empty FilePath will be returned.
318 FilePath AsEndingWithSeparator() const WARN_UNUSED_RESULT;
320 // Returns a copy of this FilePath that does not end with a trailing
321 // separator.
322 FilePath StripTrailingSeparators() const WARN_UNUSED_RESULT;
324 // Returns true if this FilePath contains an attempt to reference a parent
325 // directory (e.g. has a path component that is "..").
326 bool ReferencesParent() const;
328 // Return a Unicode human-readable version of this path.
329 // Warning: you can *not*, in general, go from a display name back to a real
330 // path. Only use this when displaying paths to users, not just when you
331 // want to stuff a string16 into some other API.
332 string16 LossyDisplayName() const;
334 // Return the path as ASCII, or the empty string if the path is not ASCII.
335 // This should only be used for cases where the FilePath is representing a
336 // known-ASCII filename.
337 std::string MaybeAsASCII() const;
339 // Return the path as UTF-8.
341 // This function is *unsafe* as there is no way to tell what encoding is
342 // used in file names on POSIX systems other than Mac and Chrome OS,
343 // although UTF-8 is practically used everywhere these days. To mitigate
344 // the encoding issue, this function internally calls
345 // SysNativeMBToWide() on POSIX systems other than Mac and Chrome OS,
346 // per assumption that the current locale's encoding is used in file
347 // names, but this isn't a perfect solution.
349 // Once it becomes safe to to stop caring about non-UTF-8 file names,
350 // the SysNativeMBToWide() hack will be removed from the code, along
351 // with "Unsafe" in the function name.
352 std::string AsUTF8Unsafe() const;
354 // Similar to AsUTF8Unsafe, but returns UTF-16 instead.
355 string16 AsUTF16Unsafe() const;
357 // Returns a FilePath object from a path name in UTF-8. This function
358 // should only be used for cases where you are sure that the input
359 // string is UTF-8.
361 // Like AsUTF8Unsafe(), this function is unsafe. This function
362 // internally calls SysWideToNativeMB() on POSIX systems other than Mac
363 // and Chrome OS, to mitigate the encoding issue. See the comment at
364 // AsUTF8Unsafe() for details.
365 static FilePath FromUTF8Unsafe(const std::string& utf8);
367 // Similar to FromUTF8Unsafe, but accepts UTF-16 instead.
368 static FilePath FromUTF16Unsafe(const string16& utf16);
370 void WriteToPickle(Pickle* pickle) const;
371 bool ReadFromPickle(PickleIterator* iter);
373 // Normalize all path separators to backslash on Windows
374 // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
375 FilePath NormalizePathSeparators() const;
377 // Normalize all path separattors to given type on Windows
378 // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
379 FilePath NormalizePathSeparatorsTo(CharType separator) const;
381 // Compare two strings in the same way the file system does.
382 // Note that these always ignore case, even on file systems that are case-
383 // sensitive. If case-sensitive comparison is ever needed, add corresponding
384 // methods here.
385 // The methods are written as a static method so that they can also be used
386 // on parts of a file path, e.g., just the extension.
387 // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and
388 // greater-than respectively.
389 static int CompareIgnoreCase(StringPieceType string1,
390 StringPieceType string2);
391 static bool CompareEqualIgnoreCase(StringPieceType string1,
392 StringPieceType string2) {
393 return CompareIgnoreCase(string1, string2) == 0;
395 static bool CompareLessIgnoreCase(StringPieceType string1,
396 StringPieceType string2) {
397 return CompareIgnoreCase(string1, string2) < 0;
400 #if defined(OS_MACOSX)
401 // Returns the string in the special canonical decomposed form as defined for
402 // HFS, which is close to, but not quite, decomposition form D. See
403 // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties
404 // for further comments.
405 // Returns the epmty string if the conversion failed.
406 static StringType GetHFSDecomposedForm(StringPieceType string);
408 // Special UTF-8 version of FastUnicodeCompare. Cf:
409 // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
410 // IMPORTANT: The input strings must be in the special HFS decomposed form!
411 // (cf. above GetHFSDecomposedForm method)
412 static int HFSFastUnicodeCompare(StringPieceType string1,
413 StringPieceType string2);
414 #endif
416 #if defined(OS_ANDROID)
417 // On android, file selection dialog can return a file with content uri
418 // scheme(starting with content://). Content uri needs to be opened with
419 // ContentResolver to guarantee that the app has appropriate permissions
420 // to access it.
421 // Returns true if the path is a content uri, or false otherwise.
422 bool IsContentUri() const;
423 #endif
425 private:
426 // Remove trailing separators from this object. If the path is absolute, it
427 // will never be stripped any more than to refer to the absolute root
428 // directory, so "////" will become "/", not "". A leading pair of
429 // separators is never stripped, to support alternate roots. This is used to
430 // support UNC paths on Windows.
431 void StripTrailingSeparatorsInternal();
433 StringType path_;
436 // This is required by googletest to print a readable output on test failures.
437 // This is declared here for use in gtest-based unit tests but is defined in
438 // the test_support_base target. Depend on that to use this in your unit test.
439 // This should not be used in production code - call ToString() instead.
440 void PrintTo(const FilePath& path, std::ostream* out);
442 } // namespace base
444 // Macros for string literal initialization of FilePath::CharType[], and for
445 // using a FilePath::CharType[] in a printf-style format string.
446 #if defined(OS_POSIX)
447 #define FILE_PATH_LITERAL(x) x
448 #define PRFilePath "s"
449 #elif defined(OS_WIN)
450 #define FILE_PATH_LITERAL(x) L ## x
451 #define PRFilePath "ls"
452 #endif // OS_WIN
454 // Provide a hash function so that hash_sets and maps can contain FilePath
455 // objects.
456 namespace BASE_HASH_NAMESPACE {
458 template<>
459 struct hash<base::FilePath> {
460 size_t operator()(const base::FilePath& f) const {
461 return hash<base::FilePath::StringType>()(f.value());
465 } // namespace BASE_HASH_NAMESPACE
467 #endif // BASE_FILES_FILE_PATH_H_