Path: blob/master/dep/googletest/src/gtest-filepath.cc
4804 views
// Copyright 2008, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829#include "gtest/internal/gtest-filepath.h"3031#include <stdlib.h>3233#include <iterator>34#include <string>3536#include "gtest/gtest-message.h"37#include "gtest/internal/gtest-port.h"3839#ifdef GTEST_OS_WINDOWS_MOBILE40#include <windows.h>41#elif defined(GTEST_OS_WINDOWS)42#include <direct.h>43#include <io.h>44#else45#include <limits.h>4647#include <climits> // Some Linux distributions define PATH_MAX here.48#endif // GTEST_OS_WINDOWS_MOBILE4950#include "gtest/internal/gtest-string.h"5152#ifdef GTEST_OS_WINDOWS53#define GTEST_PATH_MAX_ _MAX_PATH54#elif defined(PATH_MAX)55#define GTEST_PATH_MAX_ PATH_MAX56#elif defined(_XOPEN_PATH_MAX)57#define GTEST_PATH_MAX_ _XOPEN_PATH_MAX58#else59#define GTEST_PATH_MAX_ _POSIX_PATH_MAX60#endif // GTEST_OS_WINDOWS6162#if GTEST_HAS_FILE_SYSTEM6364namespace testing {65namespace internal {6667#ifdef GTEST_OS_WINDOWS68// On Windows, '\\' is the standard path separator, but many tools and the69// Windows API also accept '/' as an alternate path separator. Unless otherwise70// noted, a file path can contain either kind of path separators, or a mixture71// of them.72const char kPathSeparator = '\\';73const char kAlternatePathSeparator = '/';74const char kAlternatePathSeparatorString[] = "/";75#ifdef GTEST_OS_WINDOWS_MOBILE76// Windows CE doesn't have a current directory. You should not use77// the current directory in tests on Windows CE, but this at least78// provides a reasonable fallback.79const char kCurrentDirectoryString[] = "\\";80// Windows CE doesn't define INVALID_FILE_ATTRIBUTES81const DWORD kInvalidFileAttributes = 0xffffffff;82#else83const char kCurrentDirectoryString[] = ".\\";84#endif // GTEST_OS_WINDOWS_MOBILE85#else86const char kPathSeparator = '/';87const char kCurrentDirectoryString[] = "./";88#endif // GTEST_OS_WINDOWS8990// Returns whether the given character is a valid path separator.91static bool IsPathSeparator(char c) {92#if GTEST_HAS_ALT_PATH_SEP_93return (c == kPathSeparator) || (c == kAlternatePathSeparator);94#else95return c == kPathSeparator;96#endif97}9899// Returns the current working directory, or "" if unsuccessful.100FilePath FilePath::GetCurrentDir() {101#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \102defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_ESP8266) || \103defined(GTEST_OS_ESP32) || defined(GTEST_OS_XTENSA) || \104defined(GTEST_OS_QURT) || defined(GTEST_OS_NXP_QN9090) || \105defined(GTEST_OS_NRF52)106// These platforms do not have a current directory, so we just return107// something reasonable.108return FilePath(kCurrentDirectoryString);109#elif defined(GTEST_OS_WINDOWS)110char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};111return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);112#else113char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};114char* result = getcwd(cwd, sizeof(cwd));115#ifdef GTEST_OS_NACL116// getcwd will likely fail in NaCl due to the sandbox, so return something117// reasonable. The user may have provided a shim implementation for getcwd,118// however, so fallback only when failure is detected.119return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);120#endif // GTEST_OS_NACL121return FilePath(result == nullptr ? "" : cwd);122#endif // GTEST_OS_WINDOWS_MOBILE123}124125// Returns a copy of the FilePath with the case-insensitive extension removed.126// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns127// FilePath("dir/file"). If a case-insensitive extension is not128// found, returns a copy of the original FilePath.129FilePath FilePath::RemoveExtension(const char* extension) const {130const std::string dot_extension = std::string(".") + extension;131if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {132return FilePath(133pathname_.substr(0, pathname_.length() - dot_extension.length()));134}135return *this;136}137138// Returns a pointer to the last occurrence of a valid path separator in139// the FilePath. On Windows, for example, both '/' and '\' are valid path140// separators. Returns NULL if no path separator was found.141const char* FilePath::FindLastPathSeparator() const {142const char* const last_sep = strrchr(c_str(), kPathSeparator);143#if GTEST_HAS_ALT_PATH_SEP_144const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);145// Comparing two pointers of which only one is NULL is undefined.146if (last_alt_sep != nullptr &&147(last_sep == nullptr || last_alt_sep > last_sep)) {148return last_alt_sep;149}150#endif151return last_sep;152}153154size_t FilePath::CalculateRootLength() const {155const auto& path = pathname_;156auto s = path.begin();157auto end = path.end();158#ifdef GTEST_OS_WINDOWS159if (end - s >= 2 && s[1] == ':' && (end - s == 2 || IsPathSeparator(s[2])) &&160(('A' <= s[0] && s[0] <= 'Z') || ('a' <= s[0] && s[0] <= 'z'))) {161// A typical absolute path like "C:\Windows" or "D:"162s += 2;163if (s != end) {164++s;165}166} else if (end - s >= 3 && IsPathSeparator(*s) && IsPathSeparator(*(s + 1)) &&167!IsPathSeparator(*(s + 2))) {168// Move past the "\\" prefix in a UNC path like "\\Server\Share\Folder"169s += 2;170// Skip 2 components and their following separators ("Server\" and "Share\")171for (int i = 0; i < 2; ++i) {172while (s != end) {173bool stop = IsPathSeparator(*s);174++s;175if (stop) {176break;177}178}179}180} else if (s != end && IsPathSeparator(*s)) {181// A drive-rooted path like "\Windows"182++s;183}184#else185if (s != end && IsPathSeparator(*s)) {186++s;187}188#endif189return static_cast<size_t>(s - path.begin());190}191192// Returns a copy of the FilePath with the directory part removed.193// Example: FilePath("path/to/file").RemoveDirectoryName() returns194// FilePath("file"). If there is no directory part ("just_a_file"), it returns195// the FilePath unmodified. If there is no file part ("just_a_dir/") it196// returns an empty FilePath ("").197// On Windows platform, '\' is the path separator, otherwise it is '/'.198FilePath FilePath::RemoveDirectoryName() const {199const char* const last_sep = FindLastPathSeparator();200return last_sep ? FilePath(last_sep + 1) : *this;201}202203// RemoveFileName returns the directory path with the filename removed.204// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".205// If the FilePath is "a_file" or "/a_file", RemoveFileName returns206// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does207// not have a file, like "just/a/dir/", it returns the FilePath unmodified.208// On Windows platform, '\' is the path separator, otherwise it is '/'.209FilePath FilePath::RemoveFileName() const {210const char* const last_sep = FindLastPathSeparator();211std::string dir;212if (last_sep) {213dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str()));214} else {215dir = kCurrentDirectoryString;216}217return FilePath(dir);218}219220// Helper functions for naming files in a directory for xml output.221222// Given directory = "dir", base_name = "test", number = 0,223// extension = "xml", returns "dir/test.xml". If number is greater224// than zero (e.g., 12), returns "dir/test_12.xml".225// On Windows platform, uses \ as the separator rather than /.226FilePath FilePath::MakeFileName(const FilePath& directory,227const FilePath& base_name, int number,228const char* extension) {229std::string file;230if (number == 0) {231file = base_name.string() + "." + extension;232} else {233file =234base_name.string() + "_" + StreamableToString(number) + "." + extension;235}236return ConcatPaths(directory, FilePath(file));237}238239// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".240// On Windows, uses \ as the separator rather than /.241FilePath FilePath::ConcatPaths(const FilePath& directory,242const FilePath& relative_path) {243if (directory.IsEmpty()) return relative_path;244const FilePath dir(directory.RemoveTrailingPathSeparator());245return FilePath(dir.string() + kPathSeparator + relative_path.string());246}247248// Returns true if pathname describes something findable in the file-system,249// either a file, directory, or whatever.250bool FilePath::FileOrDirectoryExists() const {251#ifdef GTEST_OS_WINDOWS_MOBILE252LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());253const DWORD attributes = GetFileAttributes(unicode);254delete[] unicode;255return attributes != kInvalidFileAttributes;256#else257posix::StatStruct file_stat{};258return posix::Stat(pathname_.c_str(), &file_stat) == 0;259#endif // GTEST_OS_WINDOWS_MOBILE260}261262// Returns true if pathname describes a directory in the file-system263// that exists.264bool FilePath::DirectoryExists() const {265bool result = false;266#ifdef GTEST_OS_WINDOWS267// Don't strip off trailing separator if path is a root directory on268// Windows (like "C:\\").269const FilePath& path(IsRootDirectory() ? *this270: RemoveTrailingPathSeparator());271#else272const FilePath& path(*this);273#endif274275#ifdef GTEST_OS_WINDOWS_MOBILE276LPCWSTR unicode = String::AnsiToUtf16(path.c_str());277const DWORD attributes = GetFileAttributes(unicode);278delete[] unicode;279if ((attributes != kInvalidFileAttributes) &&280(attributes & FILE_ATTRIBUTE_DIRECTORY)) {281result = true;282}283#else284posix::StatStruct file_stat{};285result =286posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);287#endif // GTEST_OS_WINDOWS_MOBILE288289return result;290}291292// Returns true if pathname describes a root directory. (Windows has one293// root directory per disk drive. UNC share roots are also included.)294bool FilePath::IsRootDirectory() const {295size_t root_length = CalculateRootLength();296return root_length > 0 && root_length == pathname_.size() &&297IsPathSeparator(pathname_[root_length - 1]);298}299300// Returns true if pathname describes an absolute path.301bool FilePath::IsAbsolutePath() const { return CalculateRootLength() > 0; }302303// Returns a pathname for a file that does not currently exist. The pathname304// will be directory/base_name.extension or305// directory/base_name_<number>.extension if directory/base_name.extension306// already exists. The number will be incremented until a pathname is found307// that does not already exist.308// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.309// There could be a race condition if two or more processes are calling this310// function at the same time -- they could both pick the same filename.311FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,312const FilePath& base_name,313const char* extension) {314FilePath full_pathname;315int number = 0;316do {317full_pathname.Set(MakeFileName(directory, base_name, number++, extension));318} while (full_pathname.FileOrDirectoryExists());319return full_pathname;320}321322// Returns true if FilePath ends with a path separator, which indicates that323// it is intended to represent a directory. Returns false otherwise.324// This does NOT check that a directory (or file) actually exists.325bool FilePath::IsDirectory() const {326return !pathname_.empty() &&327IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);328}329330// Create directories so that path exists. Returns true if successful or if331// the directories already exist; returns false if unable to create directories332// for any reason.333bool FilePath::CreateDirectoriesRecursively() const {334if (!this->IsDirectory()) {335return false;336}337338if (pathname_.empty() || this->DirectoryExists()) {339return true;340}341342const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());343return parent.CreateDirectoriesRecursively() && this->CreateFolder();344}345346// Create the directory so that path exists. Returns true if successful or347// if the directory already exists; returns false if unable to create the348// directory for any reason, including if the parent directory does not349// exist. Not named "CreateDirectory" because that's a macro on Windows.350bool FilePath::CreateFolder() const {351#ifdef GTEST_OS_WINDOWS_MOBILE352FilePath removed_sep(this->RemoveTrailingPathSeparator());353LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());354int result = CreateDirectory(unicode, nullptr) ? 0 : -1;355delete[] unicode;356#elif defined(GTEST_OS_WINDOWS)357int result = _mkdir(pathname_.c_str());358#elif defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \359defined(GTEST_OS_QURT) || defined(GTEST_OS_NXP_QN9090) || \360defined(GTEST_OS_NRF52)361// do nothing362int result = 0;363#else364int result = mkdir(pathname_.c_str(), 0777);365#endif // GTEST_OS_WINDOWS_MOBILE366367if (result == -1) {368return this->DirectoryExists(); // An error is OK if the directory exists.369}370return true; // No error.371}372373// If input name has a trailing separator character, remove it and return the374// name, otherwise return the name string unmodified.375// On Windows platform, uses \ as the separator, other platforms use /.376FilePath FilePath::RemoveTrailingPathSeparator() const {377return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))378: *this;379}380381// Removes any redundant separators that might be in the pathname.382// For example, "bar///foo" becomes "bar/foo". Does not eliminate other383// redundancies that might be in a pathname involving "." or "..".384// Note that "\\Host\Share" does not contain a redundancy on Windows!385void FilePath::Normalize() {386auto out = pathname_.begin();387388auto i = pathname_.cbegin();389#ifdef GTEST_OS_WINDOWS390// UNC paths are treated specially391if (pathname_.end() - i >= 3 && IsPathSeparator(*i) &&392IsPathSeparator(*(i + 1)) && !IsPathSeparator(*(i + 2))) {393*(out++) = kPathSeparator;394*(out++) = kPathSeparator;395}396#endif397while (i != pathname_.end()) {398const char character = *i;399if (!IsPathSeparator(character)) {400*(out++) = character;401} else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {402*(out++) = kPathSeparator;403}404++i;405}406407pathname_.erase(out, pathname_.end());408}409410} // namespace internal411} // namespace testing412413#endif // GTEST_HAS_FILE_SYSTEM414415416