Update actions to ubuntu-latest (#14114)
[betaflight.git] / lib / test / gtest / src / gtest-filepath.cc
blob75f52bcfc0f9968f58c8958a33c04e13a8bfce06
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.
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.
30 #include "gtest/internal/gtest-filepath.h"
32 #include <stdlib.h>
34 #include <iterator>
35 #include <string>
37 #include "gtest/gtest-message.h"
38 #include "gtest/internal/gtest-port.h"
40 #ifdef GTEST_OS_WINDOWS_MOBILE
41 #include <windows.h>
42 #elif defined(GTEST_OS_WINDOWS)
43 #include <direct.h>
44 #include <io.h>
45 #else
46 #include <limits.h>
48 #include <climits> // Some Linux distributions define PATH_MAX here.
49 #endif // GTEST_OS_WINDOWS_MOBILE
51 #include "gtest/internal/gtest-string.h"
53 #ifdef GTEST_OS_WINDOWS
54 #define GTEST_PATH_MAX_ _MAX_PATH
55 #elif defined(PATH_MAX)
56 #define GTEST_PATH_MAX_ PATH_MAX
57 #elif defined(_XOPEN_PATH_MAX)
58 #define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
59 #else
60 #define GTEST_PATH_MAX_ _POSIX_PATH_MAX
61 #endif // GTEST_OS_WINDOWS
63 #if GTEST_HAS_FILE_SYSTEM
65 namespace testing {
66 namespace internal {
68 #ifdef GTEST_OS_WINDOWS
69 // On Windows, '\\' is the standard path separator, but many tools and the
70 // Windows API also accept '/' as an alternate path separator. Unless otherwise
71 // noted, a file path can contain either kind of path separators, or a mixture
72 // of them.
73 const char kPathSeparator = '\\';
74 const char kAlternatePathSeparator = '/';
75 const char kAlternatePathSeparatorString[] = "/";
76 #ifdef GTEST_OS_WINDOWS_MOBILE
77 // Windows CE doesn't have a current directory. You should not use
78 // the current directory in tests on Windows CE, but this at least
79 // provides a reasonable fallback.
80 const char kCurrentDirectoryString[] = "\\";
81 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
82 const DWORD kInvalidFileAttributes = 0xffffffff;
83 #else
84 const char kCurrentDirectoryString[] = ".\\";
85 #endif // GTEST_OS_WINDOWS_MOBILE
86 #else
87 const char kPathSeparator = '/';
88 const char kCurrentDirectoryString[] = "./";
89 #endif // GTEST_OS_WINDOWS
91 // Returns whether the given character is a valid path separator.
92 static bool IsPathSeparator(char c) {
93 #if GTEST_HAS_ALT_PATH_SEP_
94 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
95 #else
96 return c == kPathSeparator;
97 #endif
100 // Returns the current working directory, or "" if unsuccessful.
101 FilePath FilePath::GetCurrentDir() {
102 #if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \
103 defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_ESP8266) || \
104 defined(GTEST_OS_ESP32) || defined(GTEST_OS_XTENSA) || \
105 defined(GTEST_OS_QURT)
106 // These platforms do not have a current directory, so we just return
107 // something reasonable.
108 return FilePath(kCurrentDirectoryString);
109 #elif defined(GTEST_OS_WINDOWS)
110 char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
111 return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
112 #else
113 char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
114 char* result = getcwd(cwd, sizeof(cwd));
115 #ifdef GTEST_OS_NACL
116 // getcwd will likely fail in NaCl due to the sandbox, so return something
117 // reasonable. The user may have provided a shim implementation for getcwd,
118 // however, so fallback only when failure is detected.
119 return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
120 #endif // GTEST_OS_NACL
121 return FilePath(result == nullptr ? "" : cwd);
122 #endif // GTEST_OS_WINDOWS_MOBILE
125 // Returns a copy of the FilePath with the case-insensitive extension removed.
126 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
127 // FilePath("dir/file"). If a case-insensitive extension is not
128 // found, returns a copy of the original FilePath.
129 FilePath FilePath::RemoveExtension(const char* extension) const {
130 const std::string dot_extension = std::string(".") + extension;
131 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
132 return FilePath(
133 pathname_.substr(0, pathname_.length() - dot_extension.length()));
135 return *this;
138 // Returns a pointer to the last occurrence of a valid path separator in
139 // the FilePath. On Windows, for example, both '/' and '\' are valid path
140 // separators. Returns NULL if no path separator was found.
141 const char* FilePath::FindLastPathSeparator() const {
142 const char* const last_sep = strrchr(c_str(), kPathSeparator);
143 #if GTEST_HAS_ALT_PATH_SEP_
144 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
145 // Comparing two pointers of which only one is NULL is undefined.
146 if (last_alt_sep != nullptr &&
147 (last_sep == nullptr || last_alt_sep > last_sep)) {
148 return last_alt_sep;
150 #endif
151 return last_sep;
154 size_t FilePath::CalculateRootLength() const {
155 const auto& path = pathname_;
156 auto s = path.begin();
157 auto end = path.end();
158 #ifdef GTEST_OS_WINDOWS
159 if (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:"
162 s += 2;
163 if (s != end) {
164 ++s;
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"
169 s += 2;
170 // Skip 2 components and their following separators ("Server\" and "Share\")
171 for (int i = 0; i < 2; ++i) {
172 while (s != end) {
173 bool stop = IsPathSeparator(*s);
174 ++s;
175 if (stop) {
176 break;
180 } else if (s != end && IsPathSeparator(*s)) {
181 // A drive-rooted path like "\Windows"
182 ++s;
184 #else
185 if (s != end && IsPathSeparator(*s)) {
186 ++s;
188 #endif
189 return static_cast<size_t>(s - path.begin());
192 // Returns a copy of the FilePath with the directory part removed.
193 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
194 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
195 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
196 // returns an empty FilePath ("").
197 // On Windows platform, '\' is the path separator, otherwise it is '/'.
198 FilePath FilePath::RemoveDirectoryName() const {
199 const char* const last_sep = FindLastPathSeparator();
200 return last_sep ? FilePath(last_sep + 1) : *this;
203 // 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 returns
206 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
207 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
208 // On Windows platform, '\' is the path separator, otherwise it is '/'.
209 FilePath FilePath::RemoveFileName() const {
210 const char* const last_sep = FindLastPathSeparator();
211 std::string dir;
212 if (last_sep) {
213 dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str()));
214 } else {
215 dir = kCurrentDirectoryString;
217 return FilePath(dir);
220 // Helper functions for naming files in a directory for xml output.
222 // Given directory = "dir", base_name = "test", number = 0,
223 // extension = "xml", returns "dir/test.xml". If number is greater
224 // than zero (e.g., 12), returns "dir/test_12.xml".
225 // On Windows platform, uses \ as the separator rather than /.
226 FilePath FilePath::MakeFileName(const FilePath& directory,
227 const FilePath& base_name, int number,
228 const char* extension) {
229 std::string file;
230 if (number == 0) {
231 file = base_name.string() + "." + extension;
232 } else {
233 file =
234 base_name.string() + "_" + StreamableToString(number) + "." + extension;
236 return ConcatPaths(directory, FilePath(file));
239 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
240 // On Windows, uses \ as the separator rather than /.
241 FilePath FilePath::ConcatPaths(const FilePath& directory,
242 const FilePath& relative_path) {
243 if (directory.IsEmpty()) return relative_path;
244 const FilePath dir(directory.RemoveTrailingPathSeparator());
245 return FilePath(dir.string() + kPathSeparator + relative_path.string());
248 // Returns true if pathname describes something findable in the file-system,
249 // either a file, directory, or whatever.
250 bool FilePath::FileOrDirectoryExists() const {
251 #ifdef GTEST_OS_WINDOWS_MOBILE
252 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
253 const DWORD attributes = GetFileAttributes(unicode);
254 delete[] unicode;
255 return attributes != kInvalidFileAttributes;
256 #else
257 posix::StatStruct file_stat{};
258 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
259 #endif // GTEST_OS_WINDOWS_MOBILE
262 // Returns true if pathname describes a directory in the file-system
263 // that exists.
264 bool FilePath::DirectoryExists() const {
265 bool result = false;
266 #ifdef GTEST_OS_WINDOWS
267 // Don't strip off trailing separator if path is a root directory on
268 // Windows (like "C:\\").
269 const FilePath& path(IsRootDirectory() ? *this
270 : RemoveTrailingPathSeparator());
271 #else
272 const FilePath& path(*this);
273 #endif
275 #ifdef GTEST_OS_WINDOWS_MOBILE
276 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
277 const DWORD attributes = GetFileAttributes(unicode);
278 delete[] unicode;
279 if ((attributes != kInvalidFileAttributes) &&
280 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
281 result = true;
283 #else
284 posix::StatStruct file_stat{};
285 result =
286 posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);
287 #endif // GTEST_OS_WINDOWS_MOBILE
289 return result;
292 // Returns true if pathname describes a root directory. (Windows has one
293 // root directory per disk drive. UNC share roots are also included.)
294 bool FilePath::IsRootDirectory() const {
295 size_t root_length = CalculateRootLength();
296 return root_length > 0 && root_length == pathname_.size() &&
297 IsPathSeparator(pathname_[root_length - 1]);
300 // Returns true if pathname describes an absolute path.
301 bool FilePath::IsAbsolutePath() const { return CalculateRootLength() > 0; }
303 // Returns a pathname for a file that does not currently exist. The pathname
304 // will be directory/base_name.extension or
305 // directory/base_name_<number>.extension if directory/base_name.extension
306 // already exists. The number will be incremented until a pathname is found
307 // 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 this
310 // function at the same time -- they could both pick the same filename.
311 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
312 const FilePath& base_name,
313 const char* extension) {
314 FilePath full_pathname;
315 int number = 0;
316 do {
317 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
318 } while (full_pathname.FileOrDirectoryExists());
319 return full_pathname;
322 // Returns true if FilePath ends with a path separator, which indicates that
323 // it is intended to represent a directory. Returns false otherwise.
324 // This does NOT check that a directory (or file) actually exists.
325 bool FilePath::IsDirectory() const {
326 return !pathname_.empty() &&
327 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
330 // Create directories so that path exists. Returns true if successful or if
331 // the directories already exist; returns false if unable to create directories
332 // for any reason.
333 bool FilePath::CreateDirectoriesRecursively() const {
334 if (!this->IsDirectory()) {
335 return false;
338 if (pathname_.length() == 0 || this->DirectoryExists()) {
339 return true;
342 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
343 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
346 // Create the directory so that path exists. Returns true if successful or
347 // if the directory already exists; returns false if unable to create the
348 // directory for any reason, including if the parent directory does not
349 // exist. Not named "CreateDirectory" because that's a macro on Windows.
350 bool FilePath::CreateFolder() const {
351 #ifdef GTEST_OS_WINDOWS_MOBILE
352 FilePath removed_sep(this->RemoveTrailingPathSeparator());
353 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
354 int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
355 delete[] unicode;
356 #elif defined(GTEST_OS_WINDOWS)
357 int result = _mkdir(pathname_.c_str());
358 #elif defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \
359 defined(GTEST_OS_QURT)
360 // do nothing
361 int result = 0;
362 #else
363 int result = mkdir(pathname_.c_str(), 0777);
364 #endif // GTEST_OS_WINDOWS_MOBILE
366 if (result == -1) {
367 return this->DirectoryExists(); // An error is OK if the directory exists.
369 return true; // No error.
372 // If input name has a trailing separator character, remove it and return the
373 // name, otherwise return the name string unmodified.
374 // On Windows platform, uses \ as the separator, other platforms use /.
375 FilePath FilePath::RemoveTrailingPathSeparator() const {
376 return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))
377 : *this;
380 // Removes any redundant separators that might be in the pathname.
381 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
382 // redundancies that might be in a pathname involving "." or "..".
383 // Note that "\\Host\Share" does not contain a redundancy on Windows!
384 void FilePath::Normalize() {
385 auto out = pathname_.begin();
387 auto i = pathname_.cbegin();
388 #ifdef GTEST_OS_WINDOWS
389 // UNC paths are treated specially
390 if (pathname_.end() - i >= 3 && IsPathSeparator(*i) &&
391 IsPathSeparator(*(i + 1)) && !IsPathSeparator(*(i + 2))) {
392 *(out++) = kPathSeparator;
393 *(out++) = kPathSeparator;
395 #endif
396 while (i != pathname_.end()) {
397 const char character = *i;
398 if (!IsPathSeparator(character)) {
399 *(out++) = character;
400 } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
401 *(out++) = kPathSeparator;
403 ++i;
406 pathname_.erase(out, pathname_.end());
409 } // namespace internal
410 } // namespace testing
412 #endif // GTEST_HAS_FILE_SYSTEM