1 // Copyright 2008, Google Inc. 2 // All rights reserved. 3 // 4 // Redistribution and use in source and binary forms, with or without 5 // modification, are permitted provided that the following conditions are 6 // met: 7 // 8 // * Redistributions of source code must retain the above copyright 9 // notice, this list of conditions and the following disclaimer. 10 // * Redistributions in binary form must reproduce the above 11 // copyright notice, this list of conditions and the following disclaimer 12 // in the documentation and/or other materials provided with the 13 // distribution. 14 // * Neither the name of Google Inc. nor the names of its 15 // contributors may be used to endorse or promote products derived from 16 // this software without specific prior written permission. 17 // 18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 // 30 // Authors: keith.ray (at) gmail.com (Keith Ray) 31 32 #include "gtest/internal/gtest-filepath.h" 33 #include "gtest/internal/gtest-port.h" 34 35 #include <stdlib.h> 36 37 #if GTEST_OS_WINDOWS_MOBILE 38 # include <windows.h> 39 #elif GTEST_OS_WINDOWS 40 # include <direct.h> 41 # include <io.h> 42 #elif GTEST_OS_SYMBIAN 43 // Symbian OpenC has PATH_MAX in sys/syslimits.h 44 # include <sys/syslimits.h> 45 #else 46 # include <limits.h> 47 # include <climits> // Some Linux distributions define PATH_MAX here. 48 #endif // GTEST_OS_WINDOWS_MOBILE 49 50 #if GTEST_OS_WINDOWS 51 # define GTEST_PATH_MAX_ _MAX_PATH 52 #elif defined(PATH_MAX) 53 # define GTEST_PATH_MAX_ PATH_MAX 54 #elif defined(_XOPEN_PATH_MAX) 55 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX 56 #else 57 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX 58 #endif // GTEST_OS_WINDOWS 59 60 #include "gtest/internal/gtest-string.h" 61 62 namespace testing { 63 namespace internal { 64 65 #if GTEST_OS_WINDOWS 66 // On Windows, '\\' is the standard path separator, but many tools and the 67 // Windows API also accept '/' as an alternate path separator. Unless otherwise 68 // noted, a file path can contain either kind of path separators, or a mixture 69 // of them. 70 const char kPathSeparator = '\\'; 71 const char kAlternatePathSeparator = '/'; 72 const char kPathSeparatorString[] = "\\"; 73 const char kAlternatePathSeparatorString[] = "/"; 74 # if GTEST_OS_WINDOWS_MOBILE 75 // Windows CE doesn't have a current directory. You should not use 76 // the current directory in tests on Windows CE, but this at least 77 // provides a reasonable fallback. 78 const char kCurrentDirectoryString[] = "\\"; 79 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES 80 const DWORD kInvalidFileAttributes = 0xffffffff; 81 # else 82 const char kCurrentDirectoryString[] = ".\\"; 83 # endif // GTEST_OS_WINDOWS_MOBILE 84 #else 85 const char kPathSeparator = '/'; 86 const char kPathSeparatorString[] = "/"; 87 const char kCurrentDirectoryString[] = "./"; 88 #endif // GTEST_OS_WINDOWS 89 90 // Returns whether the given character is a valid path separator. 91 static bool IsPathSeparator(char c) { 92 #if GTEST_HAS_ALT_PATH_SEP_ 93 return (c == kPathSeparator) || (c == kAlternatePathSeparator); 94 #else 95 return c == kPathSeparator; 96 #endif 97 } 98 99 // Returns the current working directory, or "" if unsuccessful. 100 FilePath FilePath::GetCurrentDir() { 101 #if GTEST_OS_WINDOWS_MOBILE 102 // Windows CE doesn't have a current directory, so we just return 103 // something reasonable. 104 return FilePath(kCurrentDirectoryString); 105 #elif GTEST_OS_WINDOWS 106 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; 107 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); 108 #else 109 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; 110 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); 111 #endif // GTEST_OS_WINDOWS_MOBILE 112 } 113 114 // Returns a copy of the FilePath with the case-insensitive extension removed. 115 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns 116 // FilePath("dir/file"). If a case-insensitive extension is not 117 // found, returns a copy of the original FilePath. 118 FilePath FilePath::RemoveExtension(const char* extension) const { 119 const std::string dot_extension = std::string(".") + extension; 120 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { 121 return FilePath(pathname_.substr( 122 0, pathname_.length() - dot_extension.length())); 123 } 124 return *this; 125 } 126 127 // Returns a pointer to the last occurence of a valid path separator in 128 // the FilePath. On Windows, for example, both '/' and '\' are valid path 129 // separators. Returns NULL if no path separator was found. 130 const char* FilePath::FindLastPathSeparator() const { 131 const char* const last_sep = strrchr(c_str(), kPathSeparator); 132 #if GTEST_HAS_ALT_PATH_SEP_ 133 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); 134 // Comparing two pointers of which only one is NULL is undefined. 135 if (last_alt_sep != NULL && 136 (last_sep == NULL || last_alt_sep > last_sep)) { 137 return last_alt_sep; 138 } 139 #endif 140 return last_sep; 141 } 142 143 // Returns a copy of the FilePath with the directory part removed. 144 // Example: FilePath("path/to/file").RemoveDirectoryName() returns 145 // FilePath("file"). If there is no directory part ("just_a_file"), it returns 146 // the FilePath unmodified. If there is no file part ("just_a_dir/") it 147 // returns an empty FilePath (""). 148 // On Windows platform, '\' is the path separator, otherwise it is '/'. 149 FilePath FilePath::RemoveDirectoryName() const { 150 const char* const last_sep = FindLastPathSeparator(); 151 return last_sep ? FilePath(last_sep + 1) : *this; 152 } 153 154 // RemoveFileName returns the directory path with the filename removed. 155 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". 156 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns 157 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does 158 // not have a file, like "just/a/dir/", it returns the FilePath unmodified. 159 // On Windows platform, '\' is the path separator, otherwise it is '/'. 160 FilePath FilePath::RemoveFileName() const { 161 const char* const last_sep = FindLastPathSeparator(); 162 std::string dir; 163 if (last_sep) { 164 dir = std::string(c_str(), last_sep + 1 - c_str()); 165 } else { 166 dir = kCurrentDirectoryString; 167 } 168 return FilePath(dir); 169 } 170 171 // Helper functions for naming files in a directory for xml output. 172 173 // Given directory = "dir", base_name = "test", number = 0, 174 // extension = "xml", returns "dir/test.xml". If number is greater 175 // than zero (e.g., 12), returns "dir/test_12.xml". 176 // On Windows platform, uses \ as the separator rather than /. 177 FilePath FilePath::MakeFileName(const FilePath& directory, 178 const FilePath& base_name, 179 int number, 180 const char* extension) { 181 std::string file; 182 if (number == 0) { 183 file = base_name.string() + "." + extension; 184 } else { 185 file = base_name.string() + "_" + String::Format("%d", number).c_str() 186 + "." + extension; 187 } 188 return ConcatPaths(directory, FilePath(file)); 189 } 190 191 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". 192 // On Windows, uses \ as the separator rather than /. 193 FilePath FilePath::ConcatPaths(const FilePath& directory, 194 const FilePath& relative_path) { 195 if (directory.IsEmpty()) 196 return relative_path; 197 const FilePath dir(directory.RemoveTrailingPathSeparator()); 198 return FilePath(dir.string() + kPathSeparator + relative_path.string()); 199 } 200 201 // Returns true if pathname describes something findable in the file-system, 202 // either a file, directory, or whatever. 203 bool FilePath::FileOrDirectoryExists() const { 204 #if GTEST_OS_WINDOWS_MOBILE 205 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); 206 const DWORD attributes = GetFileAttributes(unicode); 207 delete [] unicode; 208 return attributes != kInvalidFileAttributes; 209 #else 210 posix::StatStruct file_stat; 211 return posix::Stat(pathname_.c_str(), &file_stat) == 0; 212 #endif // GTEST_OS_WINDOWS_MOBILE 213 } 214 215 // Returns true if pathname describes a directory in the file-system 216 // that exists. 217 bool FilePath::DirectoryExists() const { 218 bool result = false; 219 #if GTEST_OS_WINDOWS 220 // Don't strip off trailing separator if path is a root directory on 221 // Windows (like "C:\\"). 222 const FilePath& path(IsRootDirectory() ? *this : 223 RemoveTrailingPathSeparator()); 224 #else 225 const FilePath& path(*this); 226 #endif 227 228 #if GTEST_OS_WINDOWS_MOBILE 229 LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); 230 const DWORD attributes = GetFileAttributes(unicode); 231 delete [] unicode; 232 if ((attributes != kInvalidFileAttributes) && 233 (attributes & FILE_ATTRIBUTE_DIRECTORY)) { 234 result = true; 235 } 236 #else 237 posix::StatStruct file_stat; 238 result = posix::Stat(path.c_str(), &file_stat) == 0 && 239 posix::IsDir(file_stat); 240 #endif // GTEST_OS_WINDOWS_MOBILE 241 242 return result; 243 } 244 245 // Returns true if pathname describes a root directory. (Windows has one 246 // root directory per disk drive.) 247 bool FilePath::IsRootDirectory() const { 248 #if GTEST_OS_WINDOWS 249 // TODO(wan (at) google.com): on Windows a network share like 250 // \\server\share can be a root directory, although it cannot be the 251 // current directory. Handle this properly. 252 return pathname_.length() == 3 && IsAbsolutePath(); 253 #else 254 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); 255 #endif 256 } 257 258 // Returns true if pathname describes an absolute path. 259 bool FilePath::IsAbsolutePath() const { 260 const char* const name = pathname_.c_str(); 261 #if GTEST_OS_WINDOWS 262 return pathname_.length() >= 3 && 263 ((name[0] >= 'a' && name[0] <= 'z') || 264 (name[0] >= 'A' && name[0] <= 'Z')) && 265 name[1] == ':' && 266 IsPathSeparator(name[2]); 267 #else 268 return IsPathSeparator(name[0]); 269 #endif 270 } 271 272 // Returns a pathname for a file that does not currently exist. The pathname 273 // will be directory/base_name.extension or 274 // directory/base_name_<number>.extension if directory/base_name.extension 275 // already exists. The number will be incremented until a pathname is found 276 // that does not already exist. 277 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. 278 // There could be a race condition if two or more processes are calling this 279 // function at the same time -- they could both pick the same filename. 280 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, 281 const FilePath& base_name, 282 const char* extension) { 283 FilePath full_pathname; 284 int number = 0; 285 do { 286 full_pathname.Set(MakeFileName(directory, base_name, number++, extension)); 287 } while (full_pathname.FileOrDirectoryExists()); 288 return full_pathname; 289 } 290 291 // Returns true if FilePath ends with a path separator, which indicates that 292 // it is intended to represent a directory. Returns false otherwise. 293 // This does NOT check that a directory (or file) actually exists. 294 bool FilePath::IsDirectory() const { 295 return !pathname_.empty() && 296 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); 297 } 298 299 // Create directories so that path exists. Returns true if successful or if 300 // the directories already exist; returns false if unable to create directories 301 // for any reason. 302 bool FilePath::CreateDirectoriesRecursively() const { 303 if (!this->IsDirectory()) { 304 return false; 305 } 306 307 if (pathname_.length() == 0 || this->DirectoryExists()) { 308 return true; 309 } 310 311 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName()); 312 return parent.CreateDirectoriesRecursively() && this->CreateFolder(); 313 } 314 315 // Create the directory so that path exists. Returns true if successful or 316 // if the directory already exists; returns false if unable to create the 317 // directory for any reason, including if the parent directory does not 318 // exist. Not named "CreateDirectory" because that's a macro on Windows. 319 bool FilePath::CreateFolder() const { 320 #if GTEST_OS_WINDOWS_MOBILE 321 FilePath removed_sep(this->RemoveTrailingPathSeparator()); 322 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); 323 int result = CreateDirectory(unicode, NULL) ? 0 : -1; 324 delete [] unicode; 325 #elif GTEST_OS_WINDOWS 326 int result = _mkdir(pathname_.c_str()); 327 #else 328 int result = mkdir(pathname_.c_str(), 0777); 329 #endif // GTEST_OS_WINDOWS_MOBILE 330 331 if (result == -1) { 332 return this->DirectoryExists(); // An error is OK if the directory exists. 333 } 334 return true; // No error. 335 } 336 337 // If input name has a trailing separator character, remove it and return the 338 // name, otherwise return the name string unmodified. 339 // On Windows platform, uses \ as the separator, other platforms use /. 340 FilePath FilePath::RemoveTrailingPathSeparator() const { 341 return IsDirectory() 342 ? FilePath(pathname_.substr(0, pathname_.length() - 1)) 343 : *this; 344 } 345 346 // Removes any redundant separators that might be in the pathname. 347 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other 348 // redundancies that might be in a pathname involving "." or "..". 349 // TODO(wan (at) google.com): handle Windows network shares (e.g. \\server\share). 350 void FilePath::Normalize() { 351 if (pathname_.c_str() == NULL) { 352 pathname_ = ""; 353 return; 354 } 355 const char* src = pathname_.c_str(); 356 char* const dest = new char[pathname_.length() + 1]; 357 char* dest_ptr = dest; 358 memset(dest_ptr, 0, pathname_.length() + 1); 359 360 while (*src != '\0') { 361 *dest_ptr = *src; 362 if (!IsPathSeparator(*src)) { 363 src++; 364 } else { 365 #if GTEST_HAS_ALT_PATH_SEP_ 366 if (*dest_ptr == kAlternatePathSeparator) { 367 *dest_ptr = kPathSeparator; 368 } 369 #endif 370 while (IsPathSeparator(*src)) 371 src++; 372 } 373 dest_ptr++; 374 } 375 *dest_ptr = '\0'; 376 pathname_ = dest; 377 delete[] dest; 378 } 379 380 } // namespace internal 381 } // namespace testing 382