michael@0: // Copyright (c) 2012 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: // FilePath is a container for pathnames stored in a platform's native string michael@0: // type, providing containers for manipulation in according with the michael@0: // platform's conventions for pathnames. It supports the following path michael@0: // types: michael@0: // michael@0: // POSIX Windows michael@0: // --------------- ---------------------------------- michael@0: // Fundamental type char[] wchar_t[] michael@0: // Encoding unspecified* UTF-16 michael@0: // Separator / \, tolerant of / michael@0: // Drive letters no case-insensitive A-Z followed by : michael@0: // Alternate root // (surprise!) \\, for UNC paths michael@0: // michael@0: // * The encoding need not be specified on POSIX systems, although some michael@0: // POSIX-compliant systems do specify an encoding. Mac OS X uses UTF-8. michael@0: // Chrome OS also uses UTF-8. michael@0: // Linux does not specify an encoding, but in practice, the locale's michael@0: // character set may be used. michael@0: // michael@0: // For more arcane bits of path trivia, see below. michael@0: // michael@0: // FilePath objects are intended to be used anywhere paths are. An michael@0: // application may pass FilePath objects around internally, masking the michael@0: // underlying differences between systems, only differing in implementation michael@0: // where interfacing directly with the system. For example, a single michael@0: // OpenFile(const FilePath &) function may be made available, allowing all michael@0: // callers to operate without regard to the underlying implementation. On michael@0: // POSIX-like platforms, OpenFile might wrap fopen, and on Windows, it might michael@0: // wrap _wfopen_s, perhaps both by calling file_path.value().c_str(). This michael@0: // allows each platform to pass pathnames around without requiring conversions michael@0: // between encodings, which has an impact on performance, but more imporantly, michael@0: // has an impact on correctness on platforms that do not have well-defined michael@0: // encodings for pathnames. michael@0: // michael@0: // Several methods are available to perform common operations on a FilePath michael@0: // object, such as determining the parent directory (DirName), isolating the michael@0: // final path component (BaseName), and appending a relative pathname string michael@0: // to an existing FilePath object (Append). These methods are highly michael@0: // recommended over attempting to split and concatenate strings directly. michael@0: // These methods are based purely on string manipulation and knowledge of michael@0: // platform-specific pathname conventions, and do not consult the filesystem michael@0: // at all, making them safe to use without fear of blocking on I/O operations. michael@0: // These methods do not function as mutators but instead return distinct michael@0: // instances of FilePath objects, and are therefore safe to use on const michael@0: // objects. The objects themselves are safe to share between threads. michael@0: // michael@0: // To aid in initialization of FilePath objects from string literals, a michael@0: // FILE_PATH_LITERAL macro is provided, which accounts for the difference michael@0: // between char[]-based pathnames on POSIX systems and wchar_t[]-based michael@0: // pathnames on Windows. michael@0: // michael@0: // Paths can't contain NULs as a precaution agaist premature truncation. michael@0: // michael@0: // Because a FilePath object should not be instantiated at the global scope, michael@0: // instead, use a FilePath::CharType[] and initialize it with michael@0: // FILE_PATH_LITERAL. At runtime, a FilePath object can be created from the michael@0: // character array. Example: michael@0: // michael@0: // | const FilePath::CharType kLogFileName[] = FILE_PATH_LITERAL("log.txt"); michael@0: // | michael@0: // | void Function() { michael@0: // | FilePath log_file_path(kLogFileName); michael@0: // | [...] michael@0: // | } michael@0: // michael@0: // WARNING: FilePaths should ALWAYS be displayed with LTR directionality, even michael@0: // when the UI language is RTL. This means you always need to pass filepaths michael@0: // through base::i18n::WrapPathWithLTRFormatting() before displaying it in the michael@0: // RTL UI. michael@0: // michael@0: // This is a very common source of bugs, please try to keep this in mind. michael@0: // michael@0: // ARCANE BITS OF PATH TRIVIA michael@0: // michael@0: // - A double leading slash is actually part of the POSIX standard. Systems michael@0: // are allowed to treat // as an alternate root, as Windows does for UNC michael@0: // (network share) paths. Most POSIX systems don't do anything special michael@0: // with two leading slashes, but FilePath handles this case properly michael@0: // in case it ever comes across such a system. FilePath needs this support michael@0: // for Windows UNC paths, anyway. michael@0: // References: michael@0: // The Open Group Base Specifications Issue 7, sections 3.266 ("Pathname") michael@0: // and 4.12 ("Pathname Resolution"), available at: michael@0: // http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_266 michael@0: // http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12 michael@0: // michael@0: // - Windows treats c:\\ the same way it treats \\. This was intended to michael@0: // allow older applications that require drive letters to support UNC paths michael@0: // like \\server\share\path, by permitting c:\\server\share\path as an michael@0: // equivalent. Since the OS treats these paths specially, FilePath needs michael@0: // to do the same. Since Windows can use either / or \ as the separator, michael@0: // FilePath treats c://, c:\\, //, and \\ all equivalently. michael@0: // Reference: michael@0: // The Old New Thing, "Why is a drive letter permitted in front of UNC michael@0: // paths (sometimes)?", available at: michael@0: // http://blogs.msdn.com/oldnewthing/archive/2005/11/22/495740.aspx michael@0: michael@0: #ifndef BASE_FILES_FILE_PATH_H_ michael@0: #define BASE_FILES_FILE_PATH_H_ michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include "base/base_export.h" michael@0: #include "base/compiler_specific.h" michael@0: #include "base/containers/hash_tables.h" michael@0: #include "base/strings/string16.h" michael@0: #include "base/strings/string_piece.h" // For implicit conversions. michael@0: #include "build/build_config.h" michael@0: michael@0: // Windows-style drive letter support and pathname separator characters can be michael@0: // enabled and disabled independently, to aid testing. These #defines are michael@0: // here so that the same setting can be used in both the implementation and michael@0: // in the unit test. michael@0: #if defined(OS_WIN) michael@0: #define FILE_PATH_USES_DRIVE_LETTERS michael@0: #define FILE_PATH_USES_WIN_SEPARATORS michael@0: #endif // OS_WIN michael@0: michael@0: class Pickle; michael@0: class PickleIterator; michael@0: michael@0: namespace base { michael@0: michael@0: // An abstraction to isolate users from the differences between native michael@0: // pathnames on different platforms. michael@0: class BASE_EXPORT FilePath { michael@0: public: michael@0: #if defined(OS_POSIX) michael@0: // On most platforms, native pathnames are char arrays, and the encoding michael@0: // may or may not be specified. On Mac OS X, native pathnames are encoded michael@0: // in UTF-8. michael@0: typedef std::string StringType; michael@0: #elif defined(OS_WIN) michael@0: // On Windows, for Unicode-aware applications, native pathnames are wchar_t michael@0: // arrays encoded in UTF-16. michael@0: typedef std::wstring StringType; michael@0: #endif // OS_WIN michael@0: michael@0: typedef StringType::value_type CharType; michael@0: michael@0: // Null-terminated array of separators used to separate components in michael@0: // hierarchical paths. Each character in this array is a valid separator, michael@0: // but kSeparators[0] is treated as the canonical separator and will be used michael@0: // when composing pathnames. michael@0: static const CharType kSeparators[]; michael@0: michael@0: // arraysize(kSeparators). michael@0: static const size_t kSeparatorsLength; michael@0: michael@0: // A special path component meaning "this directory." michael@0: static const CharType kCurrentDirectory[]; michael@0: michael@0: // A special path component meaning "the parent directory." michael@0: static const CharType kParentDirectory[]; michael@0: michael@0: // The character used to identify a file extension. michael@0: static const CharType kExtensionSeparator; michael@0: michael@0: FilePath(); michael@0: FilePath(const FilePath& that); michael@0: explicit FilePath(const StringType& path); michael@0: ~FilePath(); michael@0: FilePath& operator=(const FilePath& that); michael@0: michael@0: bool operator==(const FilePath& that) const; michael@0: michael@0: bool operator!=(const FilePath& that) const; michael@0: michael@0: // Required for some STL containers and operations michael@0: bool operator<(const FilePath& that) const { michael@0: return path_ < that.path_; michael@0: } michael@0: michael@0: const StringType& value() const { return path_; } michael@0: michael@0: bool empty() const { return path_.empty(); } michael@0: michael@0: void clear() { path_.clear(); } michael@0: michael@0: // Returns true if |character| is in kSeparators. michael@0: static bool IsSeparator(CharType character); michael@0: michael@0: // Returns a vector of all of the components of the provided path. It is michael@0: // equivalent to calling DirName().value() on the path's root component, michael@0: // and BaseName().value() on each child component. michael@0: void GetComponents(std::vector* components) const; michael@0: michael@0: // Returns true if this FilePath is a strict parent of the |child|. Absolute michael@0: // and relative paths are accepted i.e. is /foo parent to /foo/bar and michael@0: // is foo parent to foo/bar. Does not convert paths to absolute, follow michael@0: // symlinks or directory navigation (e.g. ".."). A path is *NOT* its own michael@0: // parent. michael@0: bool IsParent(const FilePath& child) const; michael@0: michael@0: // If IsParent(child) holds, appends to path (if non-NULL) the michael@0: // relative path to child and returns true. For example, if parent michael@0: // holds "/Users/johndoe/Library/Application Support", child holds michael@0: // "/Users/johndoe/Library/Application Support/Google/Chrome/Default", and michael@0: // *path holds "/Users/johndoe/Library/Caches", then after michael@0: // parent.AppendRelativePath(child, path) is called *path will hold michael@0: // "/Users/johndoe/Library/Caches/Google/Chrome/Default". Otherwise, michael@0: // returns false. michael@0: bool AppendRelativePath(const FilePath& child, FilePath* path) const; michael@0: michael@0: // Returns a FilePath corresponding to the directory containing the path michael@0: // named by this object, stripping away the file component. If this object michael@0: // only contains one component, returns a FilePath identifying michael@0: // kCurrentDirectory. If this object already refers to the root directory, michael@0: // returns a FilePath identifying the root directory. michael@0: FilePath DirName() const WARN_UNUSED_RESULT; michael@0: michael@0: // Returns a FilePath corresponding to the last path component of this michael@0: // object, either a file or a directory. If this object already refers to michael@0: // the root directory, returns a FilePath identifying the root directory; michael@0: // this is the only situation in which BaseName will return an absolute path. michael@0: FilePath BaseName() const WARN_UNUSED_RESULT; michael@0: michael@0: // Returns ".jpg" for path "C:\pics\jojo.jpg", or an empty string if michael@0: // the file has no extension. If non-empty, Extension() will always start michael@0: // with precisely one ".". The following code should always work regardless michael@0: // of the value of path. michael@0: // new_path = path.RemoveExtension().value().append(path.Extension()); michael@0: // ASSERT(new_path == path.value()); michael@0: // NOTE: this is different from the original file_util implementation which michael@0: // returned the extension without a leading "." ("jpg" instead of ".jpg") michael@0: StringType Extension() const; michael@0: michael@0: // Returns "C:\pics\jojo" for path "C:\pics\jojo.jpg" michael@0: // NOTE: this is slightly different from the similar file_util implementation michael@0: // which returned simply 'jojo'. michael@0: FilePath RemoveExtension() const WARN_UNUSED_RESULT; michael@0: michael@0: // Inserts |suffix| after the file name portion of |path| but before the michael@0: // extension. Returns "" if BaseName() == "." or "..". michael@0: // Examples: michael@0: // path == "C:\pics\jojo.jpg" suffix == " (1)", returns "C:\pics\jojo (1).jpg" michael@0: // path == "jojo.jpg" suffix == " (1)", returns "jojo (1).jpg" michael@0: // path == "C:\pics\jojo" suffix == " (1)", returns "C:\pics\jojo (1)" michael@0: // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)" michael@0: FilePath InsertBeforeExtension( michael@0: const StringType& suffix) const WARN_UNUSED_RESULT; michael@0: FilePath InsertBeforeExtensionASCII( michael@0: const base::StringPiece& suffix) const WARN_UNUSED_RESULT; michael@0: michael@0: // Adds |extension| to |file_name|. Returns the current FilePath if michael@0: // |extension| is empty. Returns "" if BaseName() == "." or "..". michael@0: FilePath AddExtension( michael@0: const StringType& extension) const WARN_UNUSED_RESULT; michael@0: michael@0: // Replaces the extension of |file_name| with |extension|. If |file_name| michael@0: // does not have an extension, then |extension| is added. If |extension| is michael@0: // empty, then the extension is removed from |file_name|. michael@0: // Returns "" if BaseName() == "." or "..". michael@0: FilePath ReplaceExtension( michael@0: const StringType& extension) const WARN_UNUSED_RESULT; michael@0: michael@0: // Returns true if the file path matches the specified extension. The test is michael@0: // case insensitive. Don't forget the leading period if appropriate. michael@0: bool MatchesExtension(const StringType& extension) const; michael@0: michael@0: // Returns a FilePath by appending a separator and the supplied path michael@0: // component to this object's path. Append takes care to avoid adding michael@0: // excessive separators if this object's path already ends with a separator. michael@0: // If this object's path is kCurrentDirectory, a new FilePath corresponding michael@0: // only to |component| is returned. |component| must be a relative path; michael@0: // it is an error to pass an absolute path. michael@0: FilePath Append(const StringType& component) const WARN_UNUSED_RESULT; michael@0: FilePath Append(const FilePath& component) const WARN_UNUSED_RESULT; michael@0: michael@0: // Although Windows StringType is std::wstring, since the encoding it uses for michael@0: // paths is well defined, it can handle ASCII path components as well. michael@0: // Mac uses UTF8, and since ASCII is a subset of that, it works there as well. michael@0: // On Linux, although it can use any 8-bit encoding for paths, we assume that michael@0: // ASCII is a valid subset, regardless of the encoding, since many operating michael@0: // system paths will always be ASCII. michael@0: FilePath AppendASCII(const base::StringPiece& component) michael@0: const WARN_UNUSED_RESULT; michael@0: michael@0: // Returns true if this FilePath contains an absolute path. On Windows, an michael@0: // absolute path begins with either a drive letter specification followed by michael@0: // a separator character, or with two separator characters. On POSIX michael@0: // platforms, an absolute path begins with a separator character. michael@0: bool IsAbsolute() const; michael@0: michael@0: // Returns true if the patch ends with a path separator character. michael@0: bool EndsWithSeparator() const WARN_UNUSED_RESULT; michael@0: michael@0: // Returns a copy of this FilePath that ends with a trailing separator. If michael@0: // the input path is empty, an empty FilePath will be returned. michael@0: FilePath AsEndingWithSeparator() const WARN_UNUSED_RESULT; michael@0: michael@0: // Returns a copy of this FilePath that does not end with a trailing michael@0: // separator. michael@0: FilePath StripTrailingSeparators() const WARN_UNUSED_RESULT; michael@0: michael@0: // Returns true if this FilePath contains any attempt to reference a parent michael@0: // directory (i.e. has a path component that is ".." michael@0: bool ReferencesParent() const; michael@0: michael@0: // Return a Unicode human-readable version of this path. michael@0: // Warning: you can *not*, in general, go from a display name back to a real michael@0: // path. Only use this when displaying paths to users, not just when you michael@0: // want to stuff a string16 into some other API. michael@0: string16 LossyDisplayName() const; michael@0: michael@0: // Return the path as ASCII, or the empty string if the path is not ASCII. michael@0: // This should only be used for cases where the FilePath is representing a michael@0: // known-ASCII filename. michael@0: std::string MaybeAsASCII() const; michael@0: michael@0: // Return the path as UTF-8. michael@0: // michael@0: // This function is *unsafe* as there is no way to tell what encoding is michael@0: // used in file names on POSIX systems other than Mac and Chrome OS, michael@0: // although UTF-8 is practically used everywhere these days. To mitigate michael@0: // the encoding issue, this function internally calls michael@0: // SysNativeMBToWide() on POSIX systems other than Mac and Chrome OS, michael@0: // per assumption that the current locale's encoding is used in file michael@0: // names, but this isn't a perfect solution. michael@0: // michael@0: // Once it becomes safe to to stop caring about non-UTF-8 file names, michael@0: // the SysNativeMBToWide() hack will be removed from the code, along michael@0: // with "Unsafe" in the function name. michael@0: std::string AsUTF8Unsafe() const; michael@0: michael@0: // Similar to AsUTF8Unsafe, but returns UTF-16 instead. michael@0: string16 AsUTF16Unsafe() const; michael@0: michael@0: // Older Chromium code assumes that paths are always wstrings. michael@0: // This function converts wstrings to FilePaths, and is michael@0: // useful to smooth porting that old code to the FilePath API. michael@0: // It has "Hack" its name so people feel bad about using it. michael@0: // http://code.google.com/p/chromium/issues/detail?id=24672 michael@0: // michael@0: // If you are trying to be a good citizen and remove these, ask yourself: michael@0: // - Am I interacting with other Chrome code that deals with files? Then michael@0: // try to convert the API into using FilePath. michael@0: // - Am I interacting with OS-native calls? Then use value() to get at an michael@0: // OS-native string format. michael@0: // - Am I using well-known file names, like "config.ini"? Then use the michael@0: // ASCII functions (we require paths to always be supersets of ASCII). michael@0: // - Am I displaying a string to the user in some UI? Then use the michael@0: // LossyDisplayName() function, but keep in mind that you can't michael@0: // ever use the result of that again as a path. michael@0: static FilePath FromWStringHack(const std::wstring& wstring); michael@0: michael@0: // Returns a FilePath object from a path name in UTF-8. This function michael@0: // should only be used for cases where you are sure that the input michael@0: // string is UTF-8. michael@0: // michael@0: // Like AsUTF8Unsafe(), this function is unsafe. This function michael@0: // internally calls SysWideToNativeMB() on POSIX systems other than Mac michael@0: // and Chrome OS, to mitigate the encoding issue. See the comment at michael@0: // AsUTF8Unsafe() for details. michael@0: static FilePath FromUTF8Unsafe(const std::string& utf8); michael@0: michael@0: // Similar to FromUTF8Unsafe, but accepts UTF-16 instead. michael@0: static FilePath FromUTF16Unsafe(const string16& utf16); michael@0: michael@0: void WriteToPickle(Pickle* pickle) const; michael@0: bool ReadFromPickle(PickleIterator* iter); michael@0: michael@0: // Normalize all path separators to backslash on Windows michael@0: // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems. michael@0: FilePath NormalizePathSeparators() const; michael@0: michael@0: // Compare two strings in the same way the file system does. michael@0: // Note that these always ignore case, even on file systems that are case- michael@0: // sensitive. If case-sensitive comparison is ever needed, add corresponding michael@0: // methods here. michael@0: // The methods are written as a static method so that they can also be used michael@0: // on parts of a file path, e.g., just the extension. michael@0: // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and michael@0: // greater-than respectively. michael@0: static int CompareIgnoreCase(const StringType& string1, michael@0: const StringType& string2); michael@0: static bool CompareEqualIgnoreCase(const StringType& string1, michael@0: const StringType& string2) { michael@0: return CompareIgnoreCase(string1, string2) == 0; michael@0: } michael@0: static bool CompareLessIgnoreCase(const StringType& string1, michael@0: const StringType& string2) { michael@0: return CompareIgnoreCase(string1, string2) < 0; michael@0: } michael@0: michael@0: #if defined(OS_MACOSX) michael@0: // Returns the string in the special canonical decomposed form as defined for michael@0: // HFS, which is close to, but not quite, decomposition form D. See michael@0: // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties michael@0: // for further comments. michael@0: // Returns the epmty string if the conversion failed. michael@0: static StringType GetHFSDecomposedForm(const FilePath::StringType& string); michael@0: michael@0: // Special UTF-8 version of FastUnicodeCompare. Cf: michael@0: // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm michael@0: // IMPORTANT: The input strings must be in the special HFS decomposed form! michael@0: // (cf. above GetHFSDecomposedForm method) michael@0: static int HFSFastUnicodeCompare(const StringType& string1, michael@0: const StringType& string2); michael@0: #endif michael@0: michael@0: private: michael@0: // Remove trailing separators from this object. If the path is absolute, it michael@0: // will never be stripped any more than to refer to the absolute root michael@0: // directory, so "////" will become "/", not "". A leading pair of michael@0: // separators is never stripped, to support alternate roots. This is used to michael@0: // support UNC paths on Windows. michael@0: void StripTrailingSeparatorsInternal(); michael@0: michael@0: StringType path_; michael@0: }; michael@0: michael@0: } // namespace base michael@0: michael@0: // This is required by googletest to print a readable output on test failures. michael@0: BASE_EXPORT extern void PrintTo(const base::FilePath& path, std::ostream* out); michael@0: michael@0: // Macros for string literal initialization of FilePath::CharType[], and for michael@0: // using a FilePath::CharType[] in a printf-style format string. michael@0: #if defined(OS_POSIX) michael@0: #define FILE_PATH_LITERAL(x) x michael@0: #define PRFilePath "s" michael@0: #define PRFilePathLiteral "%s" michael@0: #elif defined(OS_WIN) michael@0: #define FILE_PATH_LITERAL(x) L ## x michael@0: #define PRFilePath "ls" michael@0: #define PRFilePathLiteral L"%ls" michael@0: #endif // OS_WIN michael@0: michael@0: // Provide a hash function so that hash_sets and maps can contain FilePath michael@0: // objects. michael@0: namespace BASE_HASH_NAMESPACE { michael@0: #if defined(COMPILER_GCC) michael@0: michael@0: template<> michael@0: struct hash { michael@0: size_t operator()(const base::FilePath& f) const { michael@0: return hash()(f.value()); michael@0: } michael@0: }; michael@0: michael@0: #elif defined(COMPILER_MSVC) michael@0: michael@0: inline size_t hash_value(const base::FilePath& f) { michael@0: return hash_value(f.value()); michael@0: } michael@0: michael@0: #endif // COMPILER michael@0: michael@0: } // namespace BASE_HASH_NAMESPACE michael@0: michael@0: #endif // BASE_FILES_FILE_PATH_H_