1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 // Copyright (c) 2008 The Chromium Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style license that can be
5 // found in the LICENSE file.
6 
7 // FilePath is a container for pathnames stored in a platform's native string
8 // type, providing containers for manipulation in according with the
9 // platform's conventions for pathnames.  It supports the following path
10 // types:
11 //
12 //                   POSIX            Windows
13 //                   ---------------  ----------------------------------
14 // Fundamental type  char[]           wchar_t[]
15 // Encoding          unspecified*     UTF-16
16 // Separator         /                \, tolerant of /
17 // Drive letters     no               case-insensitive A-Z followed by :
18 // Alternate root    // (surprise!)   \\, for UNC paths
19 //
20 // * The encoding need not be specified on POSIX systems, although some
21 //   POSIX-compliant systems do specify an encoding.  Mac OS X uses UTF-8.
22 //   Linux does not specify an encoding, but in practice, the locale's
23 //   character set may be used.
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 #ifndef BASE_FILE_PATH_H_
68 #define BASE_FILE_PATH_H_
69 
70 #include <string>
71 
72 #include "base/basictypes.h"
73 #include "base/compiler_specific.h"
74 
75 // Windows-style drive letter support and pathname separator characters can be
76 // enabled and disabled independently, to aid testing.  These #defines are
77 // here so that the same setting can be used in both the implementation and
78 // in the unit test.
79 #if defined(OS_WIN)
80 #  define FILE_PATH_USES_DRIVE_LETTERS
81 #  define FILE_PATH_USES_WIN_SEPARATORS
82 #endif  // OS_WIN
83 
84 // An abstraction to isolate users from the differences between native
85 // pathnames on different platforms.
86 class FilePath {
87  public:
88 #if defined(OS_POSIX)
89   // On most platforms, native pathnames are char arrays, and the encoding
90   // may or may not be specified.  On Mac OS X, native pathnames are encoded
91   // in UTF-8.
92   typedef std::string StringType;
93 #elif defined(OS_WIN)
94   // On Windows, for Unicode-aware applications, native pathnames are wchar_t
95   // arrays encoded in UTF-16.
96   typedef std::wstring StringType;
97 #endif  // OS_WIN
98 
99   typedef StringType::value_type CharType;
100 
101   // Null-terminated array of separators used to separate components in
102   // hierarchical paths.  Each character in this array is a valid separator,
103   // but kSeparators[0] is treated as the canonical separator and will be used
104   // when composing pathnames.
105   static const CharType kSeparators[];
106 
107   // A special path component meaning "this directory."
108   static const CharType kCurrentDirectory[];
109 
110   // A special path component meaning "the parent directory."
111   static const CharType kParentDirectory[];
112 
113   // The character used to identify a file extension.
114   static const CharType kExtensionSeparator;
115 
FilePath()116   FilePath() {}
FilePath(const FilePath & that)117   FilePath(const FilePath& that) : path_(that.path_) {}
FilePath(const StringType & path)118   explicit FilePath(const StringType& path) : path_(path) {}
119 
120 #if defined(OS_WIN)
FilePath(const wchar_t * path)121   explicit FilePath(const wchar_t* path) : path_(path) {}
122 #endif
123 
124   FilePath& operator=(const FilePath& that) {
125     path_ = that.path_;
126     return *this;
127   }
128 
129   bool operator==(const FilePath& that) const { return path_ == that.path_; }
130 
131   bool operator!=(const FilePath& that) const { return path_ != that.path_; }
132 
133   // Required for some STL containers and operations
134   bool operator<(const FilePath& that) const { return path_ < that.path_; }
135 
value()136   const StringType& value() const { return path_; }
137 
empty()138   bool empty() const { return path_.empty(); }
139 
140   // Returns true if |character| is in kSeparators.
141   static bool IsSeparator(CharType character);
142 
143   // Returns a FilePath corresponding to the directory containing the path
144   // named by this object, stripping away the file component.  If this object
145   // only contains one component, returns a FilePath identifying
146   // kCurrentDirectory.  If this object already refers to the root directory,
147   // returns a FilePath identifying the root directory.
148   FilePath DirName() const;
149 
150   // Returns a FilePath corresponding to the last path component of this
151   // object, either a file or a directory.  If this object already refers to
152   // the root directory, returns a FilePath identifying the root directory;
153   // this is the only situation in which BaseName will return an absolute path.
154   FilePath BaseName() const;
155 
156   // Returns ".jpg" for path "C:\pics\jojo.jpg", or an empty string if
157   // the file has no extension.  If non-empty, Extension() will always start
158   // with precisely one ".".  The following code should always work regardless
159   // of the value of path.
160   // new_path = path.RemoveExtension().value().append(path.Extension());
161   // ASSERT(new_path == path.value());
162   // NOTE: this is different from the original file_util implementation which
163   // returned the extension without a leading "." ("jpg" instead of ".jpg")
164   StringType Extension() const;
165 
166   // Returns "C:\pics\jojo" for path "C:\pics\jojo.jpg"
167   // NOTE: this is slightly different from the similar file_util implementation
168   // which returned simply 'jojo'.
169   FilePath RemoveExtension() const;
170 
171   // Inserts |suffix| after the file name portion of |path| but before the
172   // extension.  Returns "" if BaseName() == "." or "..".
173   // Examples:
174   // path == "C:\pics\jojo.jpg" suffix == " (1)", returns "C:\pics\jojo (1).jpg"
175   // path == "jojo.jpg"         suffix == " (1)", returns "jojo (1).jpg"
176   // path == "C:\pics\jojo"     suffix == " (1)", returns "C:\pics\jojo (1)"
177   // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)"
178   FilePath InsertBeforeExtension(const StringType& suffix) const;
179 
180   // Replaces the extension of |file_name| with |extension|.  If |file_name|
181   // does not have an extension, them |extension| is added.  If |extension| is
182   // empty, then the extension is removed from |file_name|.
183   // Returns "" if BaseName() == "." or "..".
184   FilePath ReplaceExtension(const StringType& extension) const;
185 
186   // Returns a FilePath by appending a separator and the supplied path
187   // component to this object's path.  Append takes care to avoid adding
188   // excessive separators if this object's path already ends with a separator.
189   // If this object's path is kCurrentDirectory, a new FilePath corresponding
190   // only to |component| is returned.  |component| must be a relative path;
191   // it is an error to pass an absolute path.
192   FilePath Append(const StringType& component) const WARN_UNUSED_RESULT;
193   FilePath Append(const FilePath& component) const WARN_UNUSED_RESULT;
194 
195   // Although Windows StringType is std::wstring, since the encoding it uses for
196   // paths is well defined, it can handle ASCII path components as well.
197   // Mac uses UTF8, and since ASCII is a subset of that, it works there as well.
198   // On Linux, although it can use any 8-bit encoding for paths, we assume that
199   // ASCII is a valid subset, regardless of the encoding, since many operating
200   // system paths will always be ASCII.
201   FilePath AppendASCII(const std::string& component) const WARN_UNUSED_RESULT;
202 
203   // Returns true if this FilePath contains an absolute path.  On Windows, an
204   // absolute path begins with either a drive letter specification followed by
205   // a separator character, or with two separator characters.  On POSIX
206   // platforms, an absolute path begins with a separator character.
207   bool IsAbsolute() const;
208 
209   // Returns a copy of this FilePath that does not end with a trailing
210   // separator.
211   FilePath StripTrailingSeparators() const;
212 
213   // Calls open on given ifstream instance
214   void OpenInputStream(std::ifstream& stream) const;
215 
216   // Older Chromium code assumes that paths are always wstrings.
217   // This function converts a wstring to a FilePath, and is useful to smooth
218   // porting that old code to the FilePath API.
219   // It has "Hack" in its name so people feel bad about using it.
220   // TODO(port): remove these functions.
221   static FilePath FromWStringHack(const std::wstring& wstring);
222 
223   // Older Chromium code assumes that paths are always wstrings.
224   // This function produces a wstring from a FilePath, and is useful to smooth
225   // porting that old code to the FilePath API.
226   // It has "Hack" in its name so people feel bad about using it.
227   // TODO(port): remove these functions.
228   std::wstring ToWStringHack() const;
229 
230  private:
231   // Remove trailing separators from this object.  If the path is absolute, it
232   // will never be stripped any more than to refer to the absolute root
233   // directory, so "////" will become "/", not "".  A leading pair of
234   // separators is never stripped, to support alternate roots.  This is used to
235   // support UNC paths on Windows.
236   void StripTrailingSeparatorsInternal();
237 
238   StringType path_;
239 };
240 
241 // Macros for string literal initialization of FilePath::CharType[].
242 #if defined(OS_POSIX)
243 #  define FILE_PATH_LITERAL(x) x
244 #elif defined(OS_WIN)
245 #  define FILE_PATH_LITERAL(x) L##x
246 #endif  // OS_WIN
247 
248 #endif  // BASE_FILE_PATH_H_
249