file_path.h revision 72a454cd3513ac24fbdd0e0cb9ad70b86a99b801
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#pragma once
102
103#include <string>
104#include <vector>
105
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.
110
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
114// in the unit test.
115#if defined(OS_WIN)
116#define FILE_PATH_USES_DRIVE_LETTERS
117#define FILE_PATH_USES_WIN_SEPARATORS
118#endif  // OS_WIN
119
120class Pickle;
121
122// An abstraction to isolate users from the differences between native
123// pathnames on different platforms.
124class FilePath {
125 public:
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
129  // in UTF-8.
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;
135#endif  // OS_WIN
136
137  typedef StringType::value_type CharType;
138
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[];
144
145  // A special path component meaning "this directory."
146  static const CharType kCurrentDirectory[];
147
148  // A special path component meaning "the parent directory."
149  static const CharType kParentDirectory[];
150
151  // The character used to identify a file extension.
152  static const CharType kExtensionSeparator;
153
154  FilePath();
155  FilePath(const FilePath& that);
156  explicit FilePath(const StringType& path);
157  ~FilePath();
158  FilePath& operator=(const FilePath& that);
159
160  bool operator==(const FilePath& that) const;
161
162  bool operator!=(const FilePath& that) const;
163
164  // Required for some STL containers and operations
165  bool operator<(const FilePath& that) const {
166    return path_ < that.path_;
167  }
168
169  const StringType& value() const { return path_; }
170
171  bool empty() const { return path_.empty(); }
172
173  void clear() { path_.clear(); }
174
175  // Returns true if |character| is in kSeparators.
176  static bool IsSeparator(CharType character);
177
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;
182
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
187  // parent.
188  bool IsParent(const FilePath& child) const;
189
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,
197  // returns false.
198  bool AppendRelativePath(const FilePath& child, FilePath* path) const;
199
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;
206
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;
212
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;
222
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;
227
228  // Inserts |suffix| after the file name portion of |path| but before the
229  // extension.  Returns "" if BaseName() == "." or "..".
230  // Examples:
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;
237
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;
243
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;
247
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;
256
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;
265
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;
271
272  // Returns a copy of this FilePath that does not end with a trailing
273  // separator.
274  FilePath StripTrailingSeparators() const;
275
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;
279
280  // Return a Unicode human-readable version of this path.
281  // Warning: you can *not*, in general, go from a display name back to a real
282  // path.  Only use this when displaying paths to users, not just when you
283  // want to stuff a string16 into some other API.
284  string16 LossyDisplayName() const;
285
286  // Older Chromium code assumes that paths are always wstrings.
287  // These functions convert wstrings to/from FilePaths, and are
288  // useful to smooth porting that old code to the FilePath API.
289  // They have "Hack" in their names so people feel bad about using them.
290  // http://code.google.com/p/chromium/issues/detail?id=24672
291  //
292  // If you are trying to be a good citizen and remove these, ask yourself:
293  // - Am I interacting with other Chrome code that deals with files?  Then
294  //   try to convert the API into using FilePath.
295  // - Am I interacting with OS-native calls?  Then use value() to get at an
296  //   OS-native string format.
297  // - Am I using well-known file names, like "config.ini"?  Then use the
298  //   ASCII functions (we require paths to always be supersets of ASCII).
299  // - Am I displaying a string to the user in some UI?  Then use the
300  //   LossyDisplayName() function, but keep in mind that you can't
301  //   ever use the result of that again as a path.
302  static FilePath FromWStringHack(const std::wstring& wstring);
303  std::wstring ToWStringHack() const;
304
305  // Static helper method to write a StringType to a pickle.
306  static void WriteStringTypeToPickle(Pickle* pickle,
307                                      const FilePath::StringType& path);
308  static bool ReadStringTypeFromPickle(Pickle* pickle, void** iter,
309                                       FilePath::StringType* path);
310
311  void WriteToPickle(Pickle* pickle);
312  bool ReadFromPickle(Pickle* pickle, void** iter);
313
314#if defined(FILE_PATH_USES_WIN_SEPARATORS)
315  // Normalize all path separators to backslash.
316  FilePath NormalizeWindowsPathSeparators() const;
317#endif
318
319  // Compare two strings in the same way the file system does.
320  // Note that these always ignore case, even on file systems that are case-
321  // sensitive. If case-sensitive comparison is ever needed, add corresponding
322  // methods here.
323  // The methods are written as a static method so that they can also be used
324  // on parts of a file path, e.g., just the extension.
325  // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and
326  // greater-than respectively.
327  static int CompareIgnoreCase(const StringType& string1,
328                               const StringType& string2);
329  static bool CompareEqualIgnoreCase(const StringType& string1,
330                                     const StringType& string2) {
331    return CompareIgnoreCase(string1, string2) == 0;
332  }
333  static bool CompareLessIgnoreCase(const StringType& string1,
334                                    const StringType& string2) {
335    return CompareIgnoreCase(string1, string2) < 0;
336  }
337
338#if defined(OS_MACOSX)
339  // Returns the string in the special canonical decomposed form as defined for
340  // HFS, which is close to, but not quite, decomposition form D. See
341  // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties
342  // for further comments.
343  // Returns the epmty string if the conversion failed.
344  static StringType GetHFSDecomposedForm(const FilePath::StringType& string);
345
346  // Special UTF-8 version of FastUnicodeCompare. Cf:
347  // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
348  // IMPORTANT: The input strings must be in the special HFS decomposed form!
349  // (cf. above GetHFSDecomposedForm method)
350  static int HFSFastUnicodeCompare(const StringType& string1,
351                                   const StringType& string2);
352#endif
353
354 private:
355  // Remove trailing separators from this object.  If the path is absolute, it
356  // will never be stripped any more than to refer to the absolute root
357  // directory, so "////" will become "/", not "".  A leading pair of
358  // separators is never stripped, to support alternate roots.  This is used to
359  // support UNC paths on Windows.
360  void StripTrailingSeparatorsInternal();
361
362  StringType path_;
363};
364
365// Macros for string literal initialization of FilePath::CharType[], and for
366// using a FilePath::CharType[] in a printf-style format string.
367#if defined(OS_POSIX)
368#define FILE_PATH_LITERAL(x) x
369#define PRFilePath "s"
370#define PRFilePathLiteral "%s"
371#elif defined(OS_WIN)
372#define FILE_PATH_LITERAL(x) L ## x
373#define PRFilePath "ls"
374#define PRFilePathLiteral L"%ls"
375#endif  // OS_WIN
376
377// Provide a hash function so that hash_sets and maps can contain FilePath
378// objects.
379#if defined(COMPILER_GCC)
380namespace __gnu_cxx {
381
382template<>
383struct hash<FilePath> {
384  std::size_t operator()(const FilePath& f) const {
385    return hash<FilePath::StringType>()(f.value());
386  }
387};
388
389}  // namespace __gnu_cxx
390#elif defined(COMPILER_MSVC)
391namespace stdext {
392
393inline size_t hash_value(const FilePath& f) {
394  return hash_value(f.value());
395}
396
397}  // namespace stdext
398#endif  // COMPILER
399
400#endif  // BASE_FILE_PATH_H_
401