Home | History | Annotate | Download | only in base
      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 l10n_util::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 
    119 class Pickle;
    120 
    121 // An abstraction to isolate users from the differences between native
    122 // pathnames on different platforms.
    123 class 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) : path_(that.path_) {}
    155   explicit FilePath(const StringType& path) : path_(path) {}
    156 
    157   FilePath& operator=(const FilePath& that) {
    158     path_ = that.path_;
    159     return *this;
    160   }
    161 
    162   bool operator==(const FilePath& that) const;
    163 
    164   bool operator!=(const FilePath& that) const;
    165 
    166   // Required for some STL containers and operations
    167   bool operator<(const FilePath& that) const {
    168     return path_ < that.path_;
    169   }
    170 
    171   const StringType& value() const { return path_; }
    172 
    173   bool empty() const { return path_.empty(); }
    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   // Older Chromium code assumes that paths are always wstrings.
    281   // This function converts a wstring to a FilePath, and is useful to smooth
    282   // porting that old code to the FilePath API.
    283   // It has "Hack" in its name so people feel bad about using it.
    284   // TODO(port): remove these functions.
    285   static FilePath FromWStringHack(const std::wstring& wstring);
    286 
    287   // Static helper method to write a StringType to a pickle.
    288   static void WriteStringTypeToPickle(Pickle* pickle,
    289                                       const FilePath::StringType& path);
    290   static bool ReadStringTypeFromPickle(Pickle* pickle, void** iter,
    291                                        FilePath::StringType* path);
    292 
    293   void WriteToPickle(Pickle* pickle);
    294   bool ReadFromPickle(Pickle* pickle, void** iter);
    295 
    296   // Compare two strings in the same way the file system does.
    297   // Note that these always ignore case, even on file systems that are case-
    298   // sensitive. If case-sensitive comparison is ever needed, add corresponding
    299   // methods here.
    300   // The methods are written as a static method so that they can also be used
    301   // on parts of a file path, e.g., just the extension.
    302   // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and
    303   // greater-than respectively.
    304   static int CompareIgnoreCase(const StringType& string1,
    305                                const StringType& string2);
    306   static bool CompareEqualIgnoreCase(const StringType& string1,
    307                                      const StringType& string2) {
    308     return CompareIgnoreCase(string1, string2) == 0;
    309   }
    310   static bool CompareLessIgnoreCase(const StringType& string1,
    311                                     const StringType& string2) {
    312     return CompareIgnoreCase(string1, string2) < 0;
    313   }
    314 
    315 #if defined(OS_MACOSX)
    316   // Returns the string in the special canonical decomposed form as defined for
    317   // HFS, which is close to, but not quite, decomposition form D. See
    318   // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties
    319   // for further comments.
    320   // Returns the epmty string if the conversion failed.
    321   static StringType GetHFSDecomposedForm(const FilePath::StringType& string);
    322 
    323   // Special UTF-8 version of FastUnicodeCompare. Cf:
    324   // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
    325   // IMPORTANT: The input strings must be in the special HFS decomposed form!
    326   // (cf. above GetHFSDecomposedForm method)
    327   static int HFSFastUnicodeCompare(const StringType& string1,
    328                                    const StringType& string2);
    329 #endif
    330 
    331   // Older Chromium code assumes that paths are always wstrings.
    332   // This function produces a wstring from a FilePath, and is useful to smooth
    333   // porting that old code to the FilePath API.
    334   // It has "Hack" in its name so people feel bad about using it.
    335   // TODO(port): remove these functions.
    336   std::wstring ToWStringHack() const;
    337 
    338  private:
    339   // Remove trailing separators from this object.  If the path is absolute, it
    340   // will never be stripped any more than to refer to the absolute root
    341   // directory, so "////" will become "/", not "".  A leading pair of
    342   // separators is never stripped, to support alternate roots.  This is used to
    343   // support UNC paths on Windows.
    344   void StripTrailingSeparatorsInternal();
    345 
    346   StringType path_;
    347 };
    348 
    349 // Macros for string literal initialization of FilePath::CharType[].
    350 #if defined(OS_POSIX)
    351 #define FILE_PATH_LITERAL(x) x
    352 #elif defined(OS_WIN)
    353 #define FILE_PATH_LITERAL(x) L ## x
    354 #endif  // OS_WIN
    355 
    356 // Provide a hash function so that hash_sets and maps can contain FilePath
    357 // objects.
    358 #if defined(COMPILER_GCC)
    359 namespace __gnu_cxx {
    360 
    361 template<>
    362 struct hash<FilePath> {
    363   std::size_t operator()(const FilePath& f) const {
    364     return hash<FilePath::StringType>()(f.value());
    365   }
    366 };
    367 
    368 }  // namespace __gnu_cxx
    369 #elif defined(COMPILER_MSVC)
    370 namespace stdext {
    371 
    372 inline size_t hash_value(const FilePath& f) {
    373   return hash_value(f.value());
    374 }
    375 
    376 }  // namespace stdext
    377 #endif  // COMPILER
    378 
    379 #endif  // BASE_FILE_PATH_H_
    380