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