file_path.h revision 49139a52abc21019da7fcbafdef393ad960ea0e2
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.
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[]           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
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//   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// 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:
59//
60// | const FilePath::CharType kLogFileName[] = FILE_PATH_LITERAL("log.txt");
61// |
62// | void Function() {
63// |   FilePath log_file_path(kLogFileName);
64// |   [...]
65// | }
66//
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
70// RTL UI.
71//
72// This is a very common source of bugs, please try to keep this in mind.
73//
74// ARCANE BITS OF PATH TRIVIA
75//
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.
82//    References:
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
87//
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.
94//    Reference:
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
98
99#ifndef BASE_FILE_PATH_H_
100#define BASE_FILE_PATH_H_
101
102#include <string>
103#include <vector>
104
105#include "base/basictypes.h"
106#include "base/compiler_specific.h"
107#include "base/hash_tables.h"
108#include "base/string_piece.h"  // For implicit conversions.
109
110// Windows-style drive letter support and pathname separator characters can be
111// enabled and disabled independently, to aid testing.  These #defines are
112// here so that the same setting can be used in both the implementation and
113// in the unit test.
114#if defined(OS_WIN)
115#define FILE_PATH_USES_DRIVE_LETTERS
116#define FILE_PATH_USES_WIN_SEPARATORS
117#endif  // OS_WIN
118
119class Pickle;
120
121// An abstraction to isolate users from the differences between native
122// pathnames on different platforms.
123class FilePath {
124 public:
125#if defined(OS_POSIX)
126  // On most platforms, native pathnames are char arrays, and the encoding
127  // may or may not be specified.  On Mac OS X, native pathnames are encoded
128  // in UTF-8.
129  typedef std::string StringType;
130#elif defined(OS_WIN)
131  // On Windows, for Unicode-aware applications, native pathnames are wchar_t
132  // arrays encoded in UTF-16.
133  typedef std::wstring StringType;
134#endif  // OS_WIN
135
136  typedef StringType::value_type CharType;
137
138  // Null-terminated array of separators used to separate components in
139  // hierarchical paths.  Each character in this array is a valid separator,
140  // but kSeparators[0] is treated as the canonical separator and will be used
141  // when composing pathnames.
142  static const CharType kSeparators[];
143
144  // A special path component meaning "this directory."
145  static const CharType kCurrentDirectory[];
146
147  // A special path component meaning "the parent directory."
148  static const CharType kParentDirectory[];
149
150  // The character used to identify a file extension.
151  static const CharType kExtensionSeparator;
152
153  FilePath();
154  FilePath(const FilePath& that);
155  explicit FilePath(const StringType& path);
156  ~FilePath();
157  FilePath& operator=(const FilePath& that);
158
159  bool operator==(const FilePath& that) const;
160
161  bool operator!=(const FilePath& that) const;
162
163  // Required for some STL containers and operations
164  bool operator<(const FilePath& that) const {
165    return path_ < that.path_;
166  }
167
168  const StringType& value() const { return path_; }
169
170  bool empty() const { return path_.empty(); }
171
172  void clear() { path_.clear(); }
173
174  // Returns true if |character| is in kSeparators.
175  static bool IsSeparator(CharType character);
176
177  // Returns a vector of all of the components of the provided path. It is
178  // equivalent to calling DirName().value() on the path's root component,
179  // and BaseName().value() on each child component.
180  void GetComponents(std::vector<FilePath::StringType>* components) const;
181
182  // Returns true if this FilePath is a strict parent of the |child|. Absolute
183  // and relative paths are accepted i.e. is /foo parent to /foo/bar and
184  // is foo parent to foo/bar. Does not convert paths to absolute, follow
185  // symlinks or directory navigation (e.g. ".."). A path is *NOT* its own
186  // parent.
187  bool IsParent(const FilePath& child) const;
188
189  // If IsParent(child) holds, appends to path (if non-NULL) the
190  // relative path to child and returns true.  For example, if parent
191  // holds "/Users/johndoe/Library/Application Support", child holds
192  // "/Users/johndoe/Library/Application Support/Google/Chrome/Default", and
193  // *path holds "/Users/johndoe/Library/Caches", then after
194  // parent.AppendRelativePath(child, path) is called *path will hold
195  // "/Users/johndoe/Library/Caches/Google/Chrome/Default".  Otherwise,
196  // returns false.
197  bool AppendRelativePath(const FilePath& child, FilePath* path) const;
198
199  // Returns a FilePath corresponding to the directory containing the path
200  // named by this object, stripping away the file component.  If this object
201  // only contains one component, returns a FilePath identifying
202  // kCurrentDirectory.  If this object already refers to the root directory,
203  // returns a FilePath identifying the root directory.
204  FilePath DirName() const;
205
206  // Returns a FilePath corresponding to the last path component of this
207  // object, either a file or a directory.  If this object already refers to
208  // the root directory, returns a FilePath identifying the root directory;
209  // this is the only situation in which BaseName will return an absolute path.
210  FilePath BaseName() const;
211
212  // Returns ".jpg" for path "C:\pics\jojo.jpg", or an empty string if
213  // the file has no extension.  If non-empty, Extension() will always start
214  // with precisely one ".".  The following code should always work regardless
215  // of the value of path.
216  // new_path = path.RemoveExtension().value().append(path.Extension());
217  // ASSERT(new_path == path.value());
218  // NOTE: this is different from the original file_util implementation which
219  // returned the extension without a leading "." ("jpg" instead of ".jpg")
220  StringType Extension() const;
221
222  // Returns "C:\pics\jojo" for path "C:\pics\jojo.jpg"
223  // NOTE: this is slightly different from the similar file_util implementation
224  // which returned simply 'jojo'.
225  FilePath RemoveExtension() const;
226
227  // Inserts |suffix| after the file name portion of |path| but before the
228  // extension.  Returns "" if BaseName() == "." or "..".
229  // Examples:
230  // path == "C:\pics\jojo.jpg" suffix == " (1)", returns "C:\pics\jojo (1).jpg"
231  // path == "jojo.jpg"         suffix == " (1)", returns "jojo (1).jpg"
232  // path == "C:\pics\jojo"     suffix == " (1)", returns "C:\pics\jojo (1)"
233  // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)"
234  FilePath InsertBeforeExtension(const StringType& suffix) const;
235  FilePath InsertBeforeExtensionASCII(const base::StringPiece& suffix) const;
236
237  // Replaces the extension of |file_name| with |extension|.  If |file_name|
238  // does not have an extension, them |extension| is added.  If |extension| is
239  // empty, then the extension is removed from |file_name|.
240  // Returns "" if BaseName() == "." or "..".
241  FilePath ReplaceExtension(const StringType& extension) const;
242
243  // Returns true if the file path matches the specified extension. The test is
244  // case insensitive. Don't forget the leading period if appropriate.
245  bool MatchesExtension(const StringType& extension) const;
246
247  // Returns a FilePath by appending a separator and the supplied path
248  // component to this object's path.  Append takes care to avoid adding
249  // excessive separators if this object's path already ends with a separator.
250  // If this object's path is kCurrentDirectory, a new FilePath corresponding
251  // only to |component| is returned.  |component| must be a relative path;
252  // it is an error to pass an absolute path.
253  FilePath Append(const StringType& component) const WARN_UNUSED_RESULT;
254  FilePath Append(const FilePath& component) const WARN_UNUSED_RESULT;
255
256  // Although Windows StringType is std::wstring, since the encoding it uses for
257  // paths is well defined, it can handle ASCII path components as well.
258  // Mac uses UTF8, and since ASCII is a subset of that, it works there as well.
259  // On Linux, although it can use any 8-bit encoding for paths, we assume that
260  // ASCII is a valid subset, regardless of the encoding, since many operating
261  // system paths will always be ASCII.
262  FilePath AppendASCII(const base::StringPiece& component)
263      const WARN_UNUSED_RESULT;
264
265  // Returns true if this FilePath contains an absolute path.  On Windows, an
266  // absolute path begins with either a drive letter specification followed by
267  // a separator character, or with two separator characters.  On POSIX
268  // platforms, an absolute path begins with a separator character.
269  bool IsAbsolute() const;
270
271  // Returns a copy of this FilePath that does not end with a trailing
272  // separator.
273  FilePath StripTrailingSeparators() const;
274
275  // Returns true if this FilePath contains any attempt to reference a parent
276  // directory (i.e. has a path component that is ".."
277  bool ReferencesParent() const;
278
279  // Older Chromium code assumes that paths are always wstrings.
280  // These functions convert wstrings to/from FilePaths, and are
281  // useful to smooth porting that old code to the FilePath API.
282  // They have "Hack" in their names so people feel bad about using them.
283  // http://code.google.com/p/chromium/issues/detail?id=24672
284  //
285  // If you are trying to be a good citizen and remove these, ask yourself:
286  // - Am I interacting with other Chrome code that deals with files?  Then
287  //   try to convert the API into using FilePath.
288  // - Am I interacting with OS-native calls?  Then use value() to get at an
289  //   OS-native string format.
290  // - Am I using well-known file names, like "config.ini"?  Then use the
291  //   ASCII functions (we require paths to always be supersets of ASCII).
292  static FilePath FromWStringHack(const std::wstring& wstring);
293  std::wstring ToWStringHack() const;
294
295  // Static helper method to write a StringType to a pickle.
296  static void WriteStringTypeToPickle(Pickle* pickle,
297                                      const FilePath::StringType& path);
298  static bool ReadStringTypeFromPickle(Pickle* pickle, void** iter,
299                                       FilePath::StringType* path);
300
301  void WriteToPickle(Pickle* pickle);
302  bool ReadFromPickle(Pickle* pickle, void** iter);
303
304#if defined(FILE_PATH_USES_WIN_SEPARATORS)
305  // Normalize all path separators to backslash.
306  FilePath NormalizeWindowsPathSeparators() const;
307#endif
308
309  // Compare two strings in the same way the file system does.
310  // Note that these always ignore case, even on file systems that are case-
311  // sensitive. If case-sensitive comparison is ever needed, add corresponding
312  // methods here.
313  // The methods are written as a static method so that they can also be used
314  // on parts of a file path, e.g., just the extension.
315  // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and
316  // greater-than respectively.
317  static int CompareIgnoreCase(const StringType& string1,
318                               const StringType& string2);
319  static bool CompareEqualIgnoreCase(const StringType& string1,
320                                     const StringType& string2) {
321    return CompareIgnoreCase(string1, string2) == 0;
322  }
323  static bool CompareLessIgnoreCase(const StringType& string1,
324                                    const StringType& string2) {
325    return CompareIgnoreCase(string1, string2) < 0;
326  }
327
328#if defined(OS_MACOSX)
329  // Returns the string in the special canonical decomposed form as defined for
330  // HFS, which is close to, but not quite, decomposition form D. See
331  // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties
332  // for further comments.
333  // Returns the epmty string if the conversion failed.
334  static StringType GetHFSDecomposedForm(const FilePath::StringType& string);
335
336  // Special UTF-8 version of FastUnicodeCompare. Cf:
337  // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
338  // IMPORTANT: The input strings must be in the special HFS decomposed form!
339  // (cf. above GetHFSDecomposedForm method)
340  static int HFSFastUnicodeCompare(const StringType& string1,
341                                   const StringType& string2);
342#endif
343
344 private:
345  // Remove trailing separators from this object.  If the path is absolute, it
346  // will never be stripped any more than to refer to the absolute root
347  // directory, so "////" will become "/", not "".  A leading pair of
348  // separators is never stripped, to support alternate roots.  This is used to
349  // support UNC paths on Windows.
350  void StripTrailingSeparatorsInternal();
351
352  StringType path_;
353};
354
355// Macros for string literal initialization of FilePath::CharType[], and for
356// using a FilePath::CharType[] in a printf-style format string.
357#if defined(OS_POSIX)
358#define FILE_PATH_LITERAL(x) x
359#define PRFilePath "s"
360#define PRFilePathLiteral "%s"
361#elif defined(OS_WIN)
362#define FILE_PATH_LITERAL(x) L ## x
363#define PRFilePath "ls"
364#define PRFilePathLiteral L"%ls"
365#endif  // OS_WIN
366
367// Provide a hash function so that hash_sets and maps can contain FilePath
368// objects.
369#if defined(COMPILER_GCC)
370namespace __gnu_cxx {
371
372template<>
373struct hash<FilePath> {
374  std::size_t operator()(const FilePath& f) const {
375    return hash<FilePath::StringType>()(f.value());
376  }
377};
378
379}  // namespace __gnu_cxx
380#elif defined(COMPILER_MSVC)
381namespace stdext {
382
383inline size_t hash_value(const FilePath& f) {
384  return hash_value(f.value());
385}
386
387}  // namespace stdext
388#endif  // COMPILER
389
390#endif  // BASE_FILE_PATH_H_
391