gtest-filepath.cc
Go to the documentation of this file.
00001 // Copyright 2008, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 //
00030 // Authors: keith.ray@gmail.com (Keith Ray)
00031 
00032 #include "gtest/gtest-message.h"
00033 #include "gtest/internal/gtest-filepath.h"
00034 #include "gtest/internal/gtest-port.h"
00035 
00036 #include <stdlib.h>
00037 
00038 #if GTEST_OS_WINDOWS_MOBILE
00039 # include <windows.h>
00040 #elif GTEST_OS_WINDOWS
00041 # include <direct.h>
00042 # include <io.h>
00043 #elif GTEST_OS_SYMBIAN
00044 // Symbian OpenC has PATH_MAX in sys/syslimits.h
00045 # include <sys/syslimits.h>
00046 #else
00047 # include <limits.h>
00048 # include <climits>  // Some Linux distributions define PATH_MAX here.
00049 #endif  // GTEST_OS_WINDOWS_MOBILE
00050 
00051 #if GTEST_OS_WINDOWS
00052 # define GTEST_PATH_MAX_ _MAX_PATH
00053 #elif defined(PATH_MAX)
00054 # define GTEST_PATH_MAX_ PATH_MAX
00055 #elif defined(_XOPEN_PATH_MAX)
00056 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
00057 #else
00058 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
00059 #endif  // GTEST_OS_WINDOWS
00060 
00061 #include "gtest/internal/gtest-string.h"
00062 
00063 namespace testing {
00064 namespace internal {
00065 
00066 #if GTEST_OS_WINDOWS
00067 // On Windows, '\\' is the standard path separator, but many tools and the
00068 // Windows API also accept '/' as an alternate path separator. Unless otherwise
00069 // noted, a file path can contain either kind of path separators, or a mixture
00070 // of them.
00071 const char kPathSeparator = '\\';
00072 const char kAlternatePathSeparator = '/';
00073 const char kPathSeparatorString[] = "\\";
00074 const char kAlternatePathSeparatorString[] = "/";
00075 # if GTEST_OS_WINDOWS_MOBILE
00076 // Windows CE doesn't have a current directory. You should not use
00077 // the current directory in tests on Windows CE, but this at least
00078 // provides a reasonable fallback.
00079 const char kCurrentDirectoryString[] = "\\";
00080 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
00081 const DWORD kInvalidFileAttributes = 0xffffffff;
00082 # else
00083 const char kCurrentDirectoryString[] = ".\\";
00084 # endif  // GTEST_OS_WINDOWS_MOBILE
00085 #else
00086 const char kPathSeparator = '/';
00087 const char kPathSeparatorString[] = "/";
00088 const char kCurrentDirectoryString[] = "./";
00089 #endif  // GTEST_OS_WINDOWS
00090 
00091 // Returns whether the given character is a valid path separator.
00092 static bool IsPathSeparator(char c) {
00093 #if GTEST_HAS_ALT_PATH_SEP_
00094   return (c == kPathSeparator) || (c == kAlternatePathSeparator);
00095 #else
00096   return c == kPathSeparator;
00097 #endif
00098 }
00099 
00100 // Returns the current working directory, or "" if unsuccessful.
00101 FilePath FilePath::GetCurrentDir() {
00102 #if GTEST_OS_WINDOWS_MOBILE
00103   // Windows CE doesn't have a current directory, so we just return
00104   // something reasonable.
00105   return FilePath(kCurrentDirectoryString);
00106 #elif GTEST_OS_WINDOWS
00107   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
00108   return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
00109 #else
00110   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
00111   return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
00112 #endif  // GTEST_OS_WINDOWS_MOBILE
00113 }
00114 
00115 // Returns a copy of the FilePath with the case-insensitive extension removed.
00116 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
00117 // FilePath("dir/file"). If a case-insensitive extension is not
00118 // found, returns a copy of the original FilePath.
00119 FilePath FilePath::RemoveExtension(const char* extension) const {
00120   const std::string dot_extension = std::string(".") + extension;
00121   if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
00122     return FilePath(pathname_.substr(
00123         0, pathname_.length() - dot_extension.length()));
00124   }
00125   return *this;
00126 }
00127 
00128 // Returns a pointer to the last occurence of a valid path separator in
00129 // the FilePath. On Windows, for example, both '/' and '\' are valid path
00130 // separators. Returns NULL if no path separator was found.
00131 const char* FilePath::FindLastPathSeparator() const {
00132   const char* const last_sep = strrchr(c_str(), kPathSeparator);
00133 #if GTEST_HAS_ALT_PATH_SEP_
00134   const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
00135   // Comparing two pointers of which only one is NULL is undefined.
00136   if (last_alt_sep != NULL &&
00137       (last_sep == NULL || last_alt_sep > last_sep)) {
00138     return last_alt_sep;
00139   }
00140 #endif
00141   return last_sep;
00142 }
00143 
00144 // Returns a copy of the FilePath with the directory part removed.
00145 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
00146 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
00147 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
00148 // returns an empty FilePath ("").
00149 // On Windows platform, '\' is the path separator, otherwise it is '/'.
00150 FilePath FilePath::RemoveDirectoryName() const {
00151   const char* const last_sep = FindLastPathSeparator();
00152   return last_sep ? FilePath(last_sep + 1) : *this;
00153 }
00154 
00155 // RemoveFileName returns the directory path with the filename removed.
00156 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
00157 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
00158 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
00159 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
00160 // On Windows platform, '\' is the path separator, otherwise it is '/'.
00161 FilePath FilePath::RemoveFileName() const {
00162   const char* const last_sep = FindLastPathSeparator();
00163   std::string dir;
00164   if (last_sep) {
00165     dir = std::string(c_str(), last_sep + 1 - c_str());
00166   } else {
00167     dir = kCurrentDirectoryString;
00168   }
00169   return FilePath(dir);
00170 }
00171 
00172 // Helper functions for naming files in a directory for xml output.
00173 
00174 // Given directory = "dir", base_name = "test", number = 0,
00175 // extension = "xml", returns "dir/test.xml". If number is greater
00176 // than zero (e.g., 12), returns "dir/test_12.xml".
00177 // On Windows platform, uses \ as the separator rather than /.
00178 FilePath FilePath::MakeFileName(const FilePath& directory,
00179                                 const FilePath& base_name,
00180                                 int number,
00181                                 const char* extension) {
00182   std::string file;
00183   if (number == 0) {
00184     file = base_name.string() + "." + extension;
00185   } else {
00186     file = base_name.string() + "_" + StreamableToString(number)
00187         + "." + extension;
00188   }
00189   return ConcatPaths(directory, FilePath(file));
00190 }
00191 
00192 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
00193 // On Windows, uses \ as the separator rather than /.
00194 FilePath FilePath::ConcatPaths(const FilePath& directory,
00195                                const FilePath& relative_path) {
00196   if (directory.IsEmpty())
00197     return relative_path;
00198   const FilePath dir(directory.RemoveTrailingPathSeparator());
00199   return FilePath(dir.string() + kPathSeparator + relative_path.string());
00200 }
00201 
00202 // Returns true if pathname describes something findable in the file-system,
00203 // either a file, directory, or whatever.
00204 bool FilePath::FileOrDirectoryExists() const {
00205 #if GTEST_OS_WINDOWS_MOBILE
00206   LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
00207   const DWORD attributes = GetFileAttributes(unicode);
00208   delete [] unicode;
00209   return attributes != kInvalidFileAttributes;
00210 #else
00211   posix::StatStruct file_stat;
00212   return posix::Stat(pathname_.c_str(), &file_stat) == 0;
00213 #endif  // GTEST_OS_WINDOWS_MOBILE
00214 }
00215 
00216 // Returns true if pathname describes a directory in the file-system
00217 // that exists.
00218 bool FilePath::DirectoryExists() const {
00219   bool result = false;
00220 #if GTEST_OS_WINDOWS
00221   // Don't strip off trailing separator if path is a root directory on
00222   // Windows (like "C:\\").
00223   const FilePath& path(IsRootDirectory() ? *this :
00224                                            RemoveTrailingPathSeparator());
00225 #else
00226   const FilePath& path(*this);
00227 #endif
00228 
00229 #if GTEST_OS_WINDOWS_MOBILE
00230   LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
00231   const DWORD attributes = GetFileAttributes(unicode);
00232   delete [] unicode;
00233   if ((attributes != kInvalidFileAttributes) &&
00234       (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
00235     result = true;
00236   }
00237 #else
00238   posix::StatStruct file_stat;
00239   result = posix::Stat(path.c_str(), &file_stat) == 0 &&
00240       posix::IsDir(file_stat);
00241 #endif  // GTEST_OS_WINDOWS_MOBILE
00242 
00243   return result;
00244 }
00245 
00246 // Returns true if pathname describes a root directory. (Windows has one
00247 // root directory per disk drive.)
00248 bool FilePath::IsRootDirectory() const {
00249 #if GTEST_OS_WINDOWS
00250   // TODO(wan@google.com): on Windows a network share like
00251   // \\server\share can be a root directory, although it cannot be the
00252   // current directory.  Handle this properly.
00253   return pathname_.length() == 3 && IsAbsolutePath();
00254 #else
00255   return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
00256 #endif
00257 }
00258 
00259 // Returns true if pathname describes an absolute path.
00260 bool FilePath::IsAbsolutePath() const {
00261   const char* const name = pathname_.c_str();
00262 #if GTEST_OS_WINDOWS
00263   return pathname_.length() >= 3 &&
00264      ((name[0] >= 'a' && name[0] <= 'z') ||
00265       (name[0] >= 'A' && name[0] <= 'Z')) &&
00266      name[1] == ':' &&
00267      IsPathSeparator(name[2]);
00268 #else
00269   return IsPathSeparator(name[0]);
00270 #endif
00271 }
00272 
00273 // Returns a pathname for a file that does not currently exist. The pathname
00274 // will be directory/base_name.extension or
00275 // directory/base_name_<number>.extension if directory/base_name.extension
00276 // already exists. The number will be incremented until a pathname is found
00277 // that does not already exist.
00278 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
00279 // There could be a race condition if two or more processes are calling this
00280 // function at the same time -- they could both pick the same filename.
00281 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
00282                                           const FilePath& base_name,
00283                                           const char* extension) {
00284   FilePath full_pathname;
00285   int number = 0;
00286   do {
00287     full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
00288   } while (full_pathname.FileOrDirectoryExists());
00289   return full_pathname;
00290 }
00291 
00292 // Returns true if FilePath ends with a path separator, which indicates that
00293 // it is intended to represent a directory. Returns false otherwise.
00294 // This does NOT check that a directory (or file) actually exists.
00295 bool FilePath::IsDirectory() const {
00296   return !pathname_.empty() &&
00297          IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
00298 }
00299 
00300 // Create directories so that path exists. Returns true if successful or if
00301 // the directories already exist; returns false if unable to create directories
00302 // for any reason.
00303 bool FilePath::CreateDirectoriesRecursively() const {
00304   if (!this->IsDirectory()) {
00305     return false;
00306   }
00307 
00308   if (pathname_.length() == 0 || this->DirectoryExists()) {
00309     return true;
00310   }
00311 
00312   const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
00313   return parent.CreateDirectoriesRecursively() && this->CreateFolder();
00314 }
00315 
00316 // Create the directory so that path exists. Returns true if successful or
00317 // if the directory already exists; returns false if unable to create the
00318 // directory for any reason, including if the parent directory does not
00319 // exist. Not named "CreateDirectory" because that's a macro on Windows.
00320 bool FilePath::CreateFolder() const {
00321 #if GTEST_OS_WINDOWS_MOBILE
00322   FilePath removed_sep(this->RemoveTrailingPathSeparator());
00323   LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
00324   int result = CreateDirectory(unicode, NULL) ? 0 : -1;
00325   delete [] unicode;
00326 #elif GTEST_OS_WINDOWS
00327   int result = _mkdir(pathname_.c_str());
00328 #else
00329   int result = mkdir(pathname_.c_str(), 0777);
00330 #endif  // GTEST_OS_WINDOWS_MOBILE
00331 
00332   if (result == -1) {
00333     return this->DirectoryExists();  // An error is OK if the directory exists.
00334   }
00335   return true;  // No error.
00336 }
00337 
00338 // If input name has a trailing separator character, remove it and return the
00339 // name, otherwise return the name string unmodified.
00340 // On Windows platform, uses \ as the separator, other platforms use /.
00341 FilePath FilePath::RemoveTrailingPathSeparator() const {
00342   return IsDirectory()
00343       ? FilePath(pathname_.substr(0, pathname_.length() - 1))
00344       : *this;
00345 }
00346 
00347 // Removes any redundant separators that might be in the pathname.
00348 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
00349 // redundancies that might be in a pathname involving "." or "..".
00350 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
00351 void FilePath::Normalize() {
00352   if (pathname_.c_str() == NULL) {
00353     pathname_ = "";
00354     return;
00355   }
00356   const char* src = pathname_.c_str();
00357   char* const dest = new char[pathname_.length() + 1];
00358   char* dest_ptr = dest;
00359   memset(dest_ptr, 0, pathname_.length() + 1);
00360 
00361   while (*src != '\0') {
00362     *dest_ptr = *src;
00363     if (!IsPathSeparator(*src)) {
00364       src++;
00365     } else {
00366 #if GTEST_HAS_ALT_PATH_SEP_
00367       if (*dest_ptr == kAlternatePathSeparator) {
00368         *dest_ptr = kPathSeparator;
00369       }
00370 #endif
00371       while (IsPathSeparator(*src))
00372         src++;
00373     }
00374     dest_ptr++;
00375   }
00376   *dest_ptr = '\0';
00377   pathname_ = dest;
00378   delete[] dest;
00379 }
00380 
00381 }  // namespace internal
00382 }  // namespace testing


ros_opcua_impl_freeopcua
Author(s): Denis Štogl
autogenerated on Sat Jun 8 2019 18:24:44