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#include "gtest/internal/gtest-filepath.h"
31
32#include <stdlib.h>
33
34#include "gtest/gtest-message.h"
35#include "gtest/internal/gtest-port.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#else
43#include <limits.h>
44
45#include <climits> // Some Linux distributions define PATH_MAX here.
46#endif // GTEST_OS_WINDOWS_MOBILE
47
48#include "gtest/internal/gtest-string.h"
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#if GTEST_HAS_FILE_SYSTEM
61
62namespace testing {
63namespace 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.
70const char kPathSeparator = '\\';
71const char kAlternatePathSeparator = '/';
72const char kAlternatePathSeparatorString[] = "/";
73#if GTEST_OS_WINDOWS_MOBILE
74// Windows CE doesn't have a current directory. You should not use
75// the current directory in tests on Windows CE, but this at least
76// provides a reasonable fallback.
77const char kCurrentDirectoryString[] = "\\";
78// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
79const DWORD kInvalidFileAttributes = 0xffffffff;
80#else
81const char kCurrentDirectoryString[] = ".\\";
82#endif // GTEST_OS_WINDOWS_MOBILE
83#else
84const char kPathSeparator = '/';
85const char kCurrentDirectoryString[] = "./";
86#endif // GTEST_OS_WINDOWS
87
88// Returns whether the given character is a valid path separator.
89static bool IsPathSeparator(char c) {
90#if GTEST_HAS_ALT_PATH_SEP_
91 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
92#else
93 return c == kPathSeparator;
94#endif
95}
96
97// Returns the current working directory, or "" if unsuccessful.
98FilePath FilePath::GetCurrentDir() {
99#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
100 GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \
101 GTEST_OS_XTENSA || GTEST_OS_QURT
102 // These platforms do not 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)) == nullptr ? "" : cwd);
108#else
109 char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
110 char* result = getcwd(buf: cwd, size: sizeof(cwd));
111#if GTEST_OS_NACL
112 // getcwd will likely fail in NaCl due to the sandbox, so return something
113 // reasonable. The user may have provided a shim implementation for getcwd,
114 // however, so fallback only when failure is detected.
115 return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
116#endif // GTEST_OS_NACL
117 return FilePath(result == nullptr ? "" : cwd);
118#endif // GTEST_OS_WINDOWS_MOBILE
119}
120
121// Returns a copy of the FilePath with the case-insensitive extension removed.
122// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
123// FilePath("dir/file"). If a case-insensitive extension is not
124// found, returns a copy of the original FilePath.
125FilePath FilePath::RemoveExtension(const char* extension) const {
126 const std::string dot_extension = std::string(".") + extension;
127 if (String::EndsWithCaseInsensitive(str: pathname_, suffix: dot_extension)) {
128 return FilePath(
129 pathname_.substr(pos: 0, n: pathname_.length() - dot_extension.length()));
130 }
131 return *this;
132}
133
134// Returns a pointer to the last occurrence of a valid path separator in
135// the FilePath. On Windows, for example, both '/' and '\' are valid path
136// separators. Returns NULL if no path separator was found.
137const char* FilePath::FindLastPathSeparator() const {
138 const char* const last_sep = strrchr(s: c_str(), c: kPathSeparator);
139#if GTEST_HAS_ALT_PATH_SEP_
140 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
141 // Comparing two pointers of which only one is NULL is undefined.
142 if (last_alt_sep != nullptr &&
143 (last_sep == nullptr || last_alt_sep > last_sep)) {
144 return last_alt_sep;
145 }
146#endif
147 return last_sep;
148}
149
150size_t FilePath::CalculateRootLength() const {
151 const auto &path = pathname_;
152 auto s = path.begin();
153 auto end = path.end();
154#if GTEST_OS_WINDOWS
155 if (end - s >= 2 && s[1] == ':' &&
156 (end - s == 2 || IsPathSeparator(s[2])) &&
157 (('A' <= s[0] && s[0] <= 'Z') || ('a' <= s[0] && s[0] <= 'z'))) {
158 // A typical absolute path like "C:\Windows" or "D:"
159 s += 2;
160 if (s != end) {
161 ++s;
162 }
163 } else if (end - s >= 3 && IsPathSeparator(*s) && IsPathSeparator(*(s + 1))
164 && !IsPathSeparator(*(s + 2))) {
165 // Move past the "\\" prefix in a UNC path like "\\Server\Share\Folder"
166 s += 2;
167 // Skip 2 components and their following separators ("Server\" and "Share\")
168 for (int i = 0; i < 2; ++i) {
169 while (s != end) {
170 bool stop = IsPathSeparator(*s);
171 ++s;
172 if (stop) {
173 break;
174 }
175 }
176 }
177 } else if (s != end && IsPathSeparator(*s)) {
178 // A drive-rooted path like "\Windows"
179 ++s;
180 }
181#else
182 if (s != end && IsPathSeparator(c: *s)) {
183 ++s;
184 }
185#endif
186 return static_cast<size_t>(s - path.begin());
187}
188
189// Returns a copy of the FilePath with the directory part removed.
190// Example: FilePath("path/to/file").RemoveDirectoryName() returns
191// FilePath("file"). If there is no directory part ("just_a_file"), it returns
192// the FilePath unmodified. If there is no file part ("just_a_dir/") it
193// returns an empty FilePath ("").
194// On Windows platform, '\' is the path separator, otherwise it is '/'.
195FilePath FilePath::RemoveDirectoryName() const {
196 const char* const last_sep = FindLastPathSeparator();
197 return last_sep ? FilePath(last_sep + 1) : *this;
198}
199
200// RemoveFileName returns the directory path with the filename removed.
201// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
202// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
203// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
204// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
205// On Windows platform, '\' is the path separator, otherwise it is '/'.
206FilePath FilePath::RemoveFileName() const {
207 const char* const last_sep = FindLastPathSeparator();
208 std::string dir;
209 if (last_sep) {
210 dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str()));
211 } else {
212 dir = kCurrentDirectoryString;
213 }
214 return FilePath(dir);
215}
216
217// Helper functions for naming files in a directory for xml output.
218
219// Given directory = "dir", base_name = "test", number = 0,
220// extension = "xml", returns "dir/test.xml". If number is greater
221// than zero (e.g., 12), returns "dir/test_12.xml".
222// On Windows platform, uses \ as the separator rather than /.
223FilePath FilePath::MakeFileName(const FilePath& directory,
224 const FilePath& base_name, int number,
225 const char* extension) {
226 std::string file;
227 if (number == 0) {
228 file = base_name.string() + "." + extension;
229 } else {
230 file =
231 base_name.string() + "_" + StreamableToString(streamable: number) + "." + extension;
232 }
233 return ConcatPaths(directory, relative_path: FilePath(file));
234}
235
236// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
237// On Windows, uses \ as the separator rather than /.
238FilePath FilePath::ConcatPaths(const FilePath& directory,
239 const FilePath& relative_path) {
240 if (directory.IsEmpty()) return relative_path;
241 const FilePath dir(directory.RemoveTrailingPathSeparator());
242 return FilePath(dir.string() + kPathSeparator + relative_path.string());
243}
244
245// Returns true if pathname describes something findable in the file-system,
246// either a file, directory, or whatever.
247bool FilePath::FileOrDirectoryExists() const {
248#if GTEST_OS_WINDOWS_MOBILE
249 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
250 const DWORD attributes = GetFileAttributes(unicode);
251 delete[] unicode;
252 return attributes != kInvalidFileAttributes;
253#else
254 posix::StatStruct file_stat{};
255 return posix::Stat(path: pathname_.c_str(), buf: &file_stat) == 0;
256#endif // GTEST_OS_WINDOWS_MOBILE
257}
258
259// Returns true if pathname describes a directory in the file-system
260// that exists.
261bool FilePath::DirectoryExists() const {
262 bool result = false;
263#if GTEST_OS_WINDOWS
264 // Don't strip off trailing separator if path is a root directory on
265 // Windows (like "C:\\").
266 const FilePath& path(IsRootDirectory() ? *this
267 : RemoveTrailingPathSeparator());
268#else
269 const FilePath& path(*this);
270#endif
271
272#if GTEST_OS_WINDOWS_MOBILE
273 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
274 const DWORD attributes = GetFileAttributes(unicode);
275 delete[] unicode;
276 if ((attributes != kInvalidFileAttributes) &&
277 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
278 result = true;
279 }
280#else
281 posix::StatStruct file_stat{};
282 result =
283 posix::Stat(path: path.c_str(), buf: &file_stat) == 0 && posix::IsDir(st: file_stat);
284#endif // GTEST_OS_WINDOWS_MOBILE
285
286 return result;
287}
288
289// Returns true if pathname describes a root directory. (Windows has one
290// root directory per disk drive. UNC share roots are also included.)
291bool FilePath::IsRootDirectory() const {
292 size_t root_length = CalculateRootLength();
293 return root_length > 0 && root_length == pathname_.size() &&
294 IsPathSeparator(c: pathname_[root_length - 1]);
295}
296
297// Returns true if pathname describes an absolute path.
298bool FilePath::IsAbsolutePath() const {
299 return CalculateRootLength() > 0;
300}
301
302// Returns a pathname for a file that does not currently exist. The pathname
303// will be directory/base_name.extension or
304// directory/base_name_<number>.extension if directory/base_name.extension
305// already exists. The number will be incremented until a pathname is found
306// that does not already exist.
307// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
308// There could be a race condition if two or more processes are calling this
309// function at the same time -- they could both pick the same filename.
310FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
311 const FilePath& base_name,
312 const char* extension) {
313 FilePath full_pathname;
314 int number = 0;
315 do {
316 full_pathname.Set(MakeFileName(directory, base_name, number: number++, extension));
317 } while (full_pathname.FileOrDirectoryExists());
318 return full_pathname;
319}
320
321// Returns true if FilePath ends with a path separator, which indicates that
322// it is intended to represent a directory. Returns false otherwise.
323// This does NOT check that a directory (or file) actually exists.
324bool FilePath::IsDirectory() const {
325 return !pathname_.empty() &&
326 IsPathSeparator(c: pathname_.c_str()[pathname_.length() - 1]);
327}
328
329// Create directories so that path exists. Returns true if successful or if
330// the directories already exist; returns false if unable to create directories
331// for any reason.
332bool FilePath::CreateDirectoriesRecursively() const {
333 if (!this->IsDirectory()) {
334 return false;
335 }
336
337 if (pathname_.length() == 0 || this->DirectoryExists()) {
338 return true;
339 }
340
341 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
342 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
343}
344
345// Create the directory so that path exists. Returns true if successful or
346// if the directory already exists; returns false if unable to create the
347// directory for any reason, including if the parent directory does not
348// exist. Not named "CreateDirectory" because that's a macro on Windows.
349bool FilePath::CreateFolder() const {
350#if GTEST_OS_WINDOWS_MOBILE
351 FilePath removed_sep(this->RemoveTrailingPathSeparator());
352 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
353 int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
354 delete[] unicode;
355#elif GTEST_OS_WINDOWS
356 int result = _mkdir(pathname_.c_str());
357#elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA || GTEST_OS_QURT
358 // do nothing
359 int result = 0;
360#else
361 int result = mkdir(path: pathname_.c_str(), mode: 0777);
362#endif // GTEST_OS_WINDOWS_MOBILE
363
364 if (result == -1) {
365 return this->DirectoryExists(); // An error is OK if the directory exists.
366 }
367 return true; // No error.
368}
369
370// If input name has a trailing separator character, remove it and return the
371// name, otherwise return the name string unmodified.
372// On Windows platform, uses \ as the separator, other platforms use /.
373FilePath FilePath::RemoveTrailingPathSeparator() const {
374 return IsDirectory() ? FilePath(pathname_.substr(pos: 0, n: pathname_.length() - 1))
375 : *this;
376}
377
378// Removes any redundant separators that might be in the pathname.
379// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
380// redundancies that might be in a pathname involving "." or "..".
381// Note that "\\Host\Share" does not contain a redundancy on Windows!
382void FilePath::Normalize() {
383 auto out = pathname_.begin();
384
385 auto i = pathname_.cbegin();
386#if GTEST_OS_WINDOWS
387 // UNC paths are treated specially
388 if (pathname_.end() - i >= 3 && IsPathSeparator(*i) &&
389 IsPathSeparator(*(i + 1)) && !IsPathSeparator(*(i + 2))) {
390 *(out++) = kPathSeparator;
391 *(out++) = kPathSeparator;
392 }
393#endif
394 while (i != pathname_.end()) {
395 const char character = *i;
396 if (!IsPathSeparator(c: character)) {
397 *(out++) = character;
398 } else if (out == pathname_.begin() || *std::prev(x: out) != kPathSeparator) {
399 *(out++) = kPathSeparator;
400 }
401 ++i;
402 }
403
404 pathname_.erase(first: out, last: pathname_.end());
405}
406
407} // namespace internal
408} // namespace testing
409
410#endif // GTEST_HAS_FILE_SYSTEM
411