F´ Flight Software - C/C++ Documentation NASA-v1.6.0
A framework for building embedded system applications to NASA flight quality standards.
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
gtest-filepath.cc
Go to the documentation of this file.
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
60namespace testing {
61namespace internal {
62
63#if GTEST_OS_WINDOWS
64// On Windows, '\\' is the standard path separator, but many tools and the
65// Windows API also accept '/' as an alternate path separator. Unless otherwise
66// noted, a file path can contain either kind of path separators, or a mixture
67// of them.
68const char kPathSeparator = '\\';
69const char kAlternatePathSeparator = '/';
70const char kAlternatePathSeparatorString[] = "/";
71#if GTEST_OS_WINDOWS_MOBILE
72// Windows CE doesn't have a current directory. You should not use
73// the current directory in tests on Windows CE, but this at least
74// provides a reasonable fallback.
75const char kCurrentDirectoryString[] = "\\";
76// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
77const DWORD kInvalidFileAttributes = 0xffffffff;
78#else
79const char kCurrentDirectoryString[] = ".\\";
80#endif // GTEST_OS_WINDOWS_MOBILE
81#else
82const char kPathSeparator = '/';
83const char kCurrentDirectoryString[] = "./";
84#endif // GTEST_OS_WINDOWS
85
86// Returns whether the given character is a valid path separator.
87static bool IsPathSeparator(char c) {
88#if GTEST_HAS_ALT_PATH_SEP_
89 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
90#else
91 return c == kPathSeparator;
92#endif
93}
94
95// Returns the current working directory, or "" if unsuccessful.
96FilePath FilePath::GetCurrentDir() {
97#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
98 GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \
99 GTEST_OS_XTENSA
100 // These platforms do not have a current directory, so we just return
101 // something reasonable.
102 return FilePath(kCurrentDirectoryString);
103#elif GTEST_OS_WINDOWS
104 char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
105 return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
106#else
107 char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
108 char* result = getcwd(cwd, sizeof(cwd));
109#if GTEST_OS_NACL
110 // getcwd will likely fail in NaCl due to the sandbox, so return something
111 // reasonable. The user may have provided a shim implementation for getcwd,
112 // however, so fallback only when failure is detected.
113 return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
114#endif // GTEST_OS_NACL
115 return FilePath(result == nullptr ? "" : cwd);
116#endif // GTEST_OS_WINDOWS_MOBILE
117}
118
119// Returns a copy of the FilePath with the case-insensitive extension removed.
120// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
121// FilePath("dir/file"). If a case-insensitive extension is not
122// found, returns a copy of the original FilePath.
123FilePath FilePath::RemoveExtension(const char* extension) const {
124 const std::string dot_extension = std::string(".") + extension;
125 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
126 return FilePath(
127 pathname_.substr(0, pathname_.length() - dot_extension.length()));
128 }
129 return *this;
130}
131
132// Returns a pointer to the last occurrence of a valid path separator in
133// the FilePath. On Windows, for example, both '/' and '\' are valid path
134// separators. Returns NULL if no path separator was found.
135const char* FilePath::FindLastPathSeparator() const {
136 const char* const last_sep = strrchr(c_str(), kPathSeparator);
137#if GTEST_HAS_ALT_PATH_SEP_
138 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
139 // Comparing two pointers of which only one is NULL is undefined.
140 if (last_alt_sep != nullptr &&
141 (last_sep == nullptr || last_alt_sep > last_sep)) {
142 return last_alt_sep;
143 }
144#endif
145 return last_sep;
146}
147
148// Returns a copy of the FilePath with the directory part removed.
149// Example: FilePath("path/to/file").RemoveDirectoryName() returns
150// FilePath("file"). If there is no directory part ("just_a_file"), it returns
151// the FilePath unmodified. If there is no file part ("just_a_dir/") it
152// returns an empty FilePath ("").
153// On Windows platform, '\' is the path separator, otherwise it is '/'.
154FilePath FilePath::RemoveDirectoryName() const {
155 const char* const last_sep = FindLastPathSeparator();
156 return last_sep ? FilePath(last_sep + 1) : *this;
157}
158
159// RemoveFileName returns the directory path with the filename removed.
160// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
161// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
162// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
163// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
164// On Windows platform, '\' is the path separator, otherwise it is '/'.
165FilePath FilePath::RemoveFileName() const {
166 const char* const last_sep = FindLastPathSeparator();
167 std::string dir;
168 if (last_sep) {
169 dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str()));
170 } else {
172 }
173 return FilePath(dir);
174}
175
176// Helper functions for naming files in a directory for xml output.
177
178// Given directory = "dir", base_name = "test", number = 0,
179// extension = "xml", returns "dir/test.xml". If number is greater
180// than zero (e.g., 12), returns "dir/test_12.xml".
181// On Windows platform, uses \ as the separator rather than /.
182FilePath FilePath::MakeFileName(const FilePath& directory,
183 const FilePath& base_name, int number,
184 const char* extension) {
185 std::string file;
186 if (number == 0) {
187 file = base_name.string() + "." + extension;
188 } else {
189 file =
190 base_name.string() + "_" + StreamableToString(number) + "." + extension;
191 }
192 return ConcatPaths(directory, FilePath(file));
193}
194
195// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
196// On Windows, uses \ as the separator rather than /.
197FilePath FilePath::ConcatPaths(const FilePath& directory,
198 const FilePath& relative_path) {
199 if (directory.IsEmpty()) return relative_path;
200 const FilePath dir(directory.RemoveTrailingPathSeparator());
201 return FilePath(dir.string() + kPathSeparator + relative_path.string());
202}
203
204// Returns true if pathname describes something findable in the file-system,
205// either a file, directory, or whatever.
206bool FilePath::FileOrDirectoryExists() const {
207#if GTEST_OS_WINDOWS_MOBILE
208 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
209 const DWORD attributes = GetFileAttributes(unicode);
210 delete[] unicode;
211 return attributes != kInvalidFileAttributes;
212#else
213 posix::StatStruct file_stat{};
214 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
215#endif // GTEST_OS_WINDOWS_MOBILE
216}
217
218// Returns true if pathname describes a directory in the file-system
219// that exists.
220bool FilePath::DirectoryExists() const {
221 bool result = false;
222#if GTEST_OS_WINDOWS
223 // Don't strip off trailing separator if path is a root directory on
224 // Windows (like "C:\\").
225 const FilePath& path(IsRootDirectory() ? *this
226 : RemoveTrailingPathSeparator());
227#else
228 const FilePath& path(*this);
229#endif
230
231#if GTEST_OS_WINDOWS_MOBILE
232 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
233 const DWORD attributes = GetFileAttributes(unicode);
234 delete[] unicode;
235 if ((attributes != kInvalidFileAttributes) &&
236 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
237 result = true;
238 }
239#else
240 posix::StatStruct file_stat{};
241 result =
242 posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);
243#endif // GTEST_OS_WINDOWS_MOBILE
244
245 return result;
246}
247
248// Returns true if pathname describes a root directory. (Windows has one
249// root directory per disk drive.)
250bool FilePath::IsRootDirectory() const {
251#if GTEST_OS_WINDOWS
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.
259bool 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] == ':' && IsPathSeparator(name[2]);
266#else
267 return IsPathSeparator(name[0]);
268#endif
269}
270
271// Returns a pathname for a file that does not currently exist. The pathname
272// will be directory/base_name.extension or
273// directory/base_name_<number>.extension if directory/base_name.extension
274// already exists. The number will be incremented until a pathname is found
275// that does not already exist.
276// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
277// There could be a race condition if two or more processes are calling this
278// function at the same time -- they could both pick the same filename.
279FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
280 const FilePath& base_name,
281 const char* extension) {
282 FilePath full_pathname;
283 int number = 0;
284 do {
285 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
286 } while (full_pathname.FileOrDirectoryExists());
287 return full_pathname;
288}
289
290// Returns true if FilePath ends with a path separator, which indicates that
291// it is intended to represent a directory. Returns false otherwise.
292// This does NOT check that a directory (or file) actually exists.
293bool FilePath::IsDirectory() const {
294 return !pathname_.empty() &&
295 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
296}
297
298// Create directories so that path exists. Returns true if successful or if
299// the directories already exist; returns false if unable to create directories
300// for any reason.
301bool FilePath::CreateDirectoriesRecursively() const {
302 if (!this->IsDirectory()) {
303 return false;
304 }
305
306 if (pathname_.length() == 0 || this->DirectoryExists()) {
307 return true;
308 }
309
310 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
311 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
312}
313
314// Create the directory so that path exists. Returns true if successful or
315// if the directory already exists; returns false if unable to create the
316// directory for any reason, including if the parent directory does not
317// exist. Not named "CreateDirectory" because that's a macro on Windows.
318bool FilePath::CreateFolder() const {
319#if GTEST_OS_WINDOWS_MOBILE
320 FilePath removed_sep(this->RemoveTrailingPathSeparator());
321 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
322 int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
323 delete[] unicode;
324#elif GTEST_OS_WINDOWS
325 int result = _mkdir(pathname_.c_str());
326#elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA
327 // do nothing
328 int result = 0;
329#else
330 int result = mkdir(pathname_.c_str(), 0777);
331#endif // GTEST_OS_WINDOWS_MOBILE
332
333 if (result == -1) {
334 return this->DirectoryExists(); // An error is OK if the directory exists.
335 }
336 return true; // No error.
337}
338
339// If input name has a trailing separator character, remove it and return the
340// name, otherwise return the name string unmodified.
341// On Windows platform, uses \ as the separator, other platforms use /.
342FilePath FilePath::RemoveTrailingPathSeparator() const {
343 return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))
344 : *this;
345}
346
347// Removes any redundant separators that might be in the pathname.
348// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
349// redundancies that might be in a pathname involving "." or "..".
350void FilePath::Normalize() {
351 auto out = pathname_.begin();
352
353 for (const char character : pathname_) {
354 if (!IsPathSeparator(character)) {
355 *(out++) = character;
356 } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
357 *(out++) = kPathSeparator;
358 } else {
359 continue;
360 }
361 }
362
363 pathname_.erase(out, pathname_.end());
364}
365
366} // namespace internal
367} // namespace testing
#define GTEST_PATH_MAX_
const char kCurrentDirectoryString[]
static bool IsPathSeparator(char c)
const char kPathSeparator