Lab_1 0.1.1
Matrix Library
Loading...
Searching...
No Matches
gtest-filepath.cc
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 || GTEST_OS_QURT
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
148size_t FilePath::CalculateRootLength() const {
149 const auto &path = pathname_;
150 auto s = path.begin();
151 auto end = path.end();
152#if GTEST_OS_WINDOWS
153 if (end - s >= 2 && s[1] == ':' &&
154 (end - s == 2 || IsPathSeparator(s[2])) &&
155 (('A' <= s[0] && s[0] <= 'Z') || ('a' <= s[0] && s[0] <= 'z'))) {
156 // A typical absolute path like "C:\Windows" or "D:"
157 s += 2;
158 if (s != end) {
159 ++s;
160 }
161 } else if (end - s >= 3 && IsPathSeparator(*s) && IsPathSeparator(*(s + 1))
162 && !IsPathSeparator(*(s + 2))) {
163 // Move past the "\\" prefix in a UNC path like "\\Server\Share\Folder"
164 s += 2;
165 // Skip 2 components and their following separators ("Server\" and "Share\")
166 for (int i = 0; i < 2; ++i) {
167 while (s != end) {
168 bool stop = IsPathSeparator(*s);
169 ++s;
170 if (stop) {
171 break;
172 }
173 }
174 }
175 } else if (s != end && IsPathSeparator(*s)) {
176 // A drive-rooted path like "\Windows"
177 ++s;
178 }
179#else
180 if (s != end && IsPathSeparator(*s)) {
181 ++s;
182 }
183#endif
184 return static_cast<size_t>(s - path.begin());
185}
186
187// Returns a copy of the FilePath with the directory part removed.
188// Example: FilePath("path/to/file").RemoveDirectoryName() returns
189// FilePath("file"). If there is no directory part ("just_a_file"), it returns
190// the FilePath unmodified. If there is no file part ("just_a_dir/") it
191// returns an empty FilePath ("").
192// On Windows platform, '\' is the path separator, otherwise it is '/'.
193FilePath FilePath::RemoveDirectoryName() const {
194 const char* const last_sep = FindLastPathSeparator();
195 return last_sep ? FilePath(last_sep + 1) : *this;
196}
197
198// RemoveFileName returns the directory path with the filename removed.
199// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
200// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
201// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
202// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
203// On Windows platform, '\' is the path separator, otherwise it is '/'.
204FilePath FilePath::RemoveFileName() const {
205 const char* const last_sep = FindLastPathSeparator();
206 std::string dir;
207 if (last_sep) {
208 dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str()));
209 } else {
210 dir = kCurrentDirectoryString;
211 }
212 return FilePath(dir);
213}
214
215// Helper functions for naming files in a directory for xml output.
216
217// Given directory = "dir", base_name = "test", number = 0,
218// extension = "xml", returns "dir/test.xml". If number is greater
219// than zero (e.g., 12), returns "dir/test_12.xml".
220// On Windows platform, uses \ as the separator rather than /.
221FilePath FilePath::MakeFileName(const FilePath& directory,
222 const FilePath& base_name, int number,
223 const char* extension) {
224 std::string file;
225 if (number == 0) {
226 file = base_name.string() + "." + extension;
227 } else {
228 file =
229 base_name.string() + "_" + StreamableToString(number) + "." + extension;
230 }
231 return ConcatPaths(directory, FilePath(file));
232}
233
234// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
235// On Windows, uses \ as the separator rather than /.
236FilePath FilePath::ConcatPaths(const FilePath& directory,
237 const FilePath& relative_path) {
238 if (directory.IsEmpty()) return relative_path;
239 const FilePath dir(directory.RemoveTrailingPathSeparator());
240 return FilePath(dir.string() + kPathSeparator + relative_path.string());
241}
242
243// Returns true if pathname describes something findable in the file-system,
244// either a file, directory, or whatever.
245bool FilePath::FileOrDirectoryExists() const {
246#if GTEST_OS_WINDOWS_MOBILE
247 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
248 const DWORD attributes = GetFileAttributes(unicode);
249 delete[] unicode;
250 return attributes != kInvalidFileAttributes;
251#else
252 posix::StatStruct file_stat{};
253 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
254#endif // GTEST_OS_WINDOWS_MOBILE
255}
256
257// Returns true if pathname describes a directory in the file-system
258// that exists.
259bool FilePath::DirectoryExists() const {
260 bool result = false;
261#if GTEST_OS_WINDOWS
262 // Don't strip off trailing separator if path is a root directory on
263 // Windows (like "C:\\").
264 const FilePath& path(IsRootDirectory() ? *this
265 : RemoveTrailingPathSeparator());
266#else
267 const FilePath& path(*this);
268#endif
269
270#if GTEST_OS_WINDOWS_MOBILE
271 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
272 const DWORD attributes = GetFileAttributes(unicode);
273 delete[] unicode;
274 if ((attributes != kInvalidFileAttributes) &&
275 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
276 result = true;
277 }
278#else
279 posix::StatStruct file_stat{};
280 result =
281 posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);
282#endif // GTEST_OS_WINDOWS_MOBILE
283
284 return result;
285}
286
287// Returns true if pathname describes a root directory. (Windows has one
288// root directory per disk drive. UNC share roots are also included.)
289bool FilePath::IsRootDirectory() const {
290 size_t root_length = CalculateRootLength();
291 return root_length > 0 && root_length == pathname_.size() &&
292 IsPathSeparator(pathname_[root_length - 1]);
293}
294
295// Returns true if pathname describes an absolute path.
296bool FilePath::IsAbsolutePath() const {
297 return CalculateRootLength() > 0;
298}
299
300// Returns a pathname for a file that does not currently exist. The pathname
301// will be directory/base_name.extension or
302// directory/base_name_<number>.extension if directory/base_name.extension
303// already exists. The number will be incremented until a pathname is found
304// that does not already exist.
305// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
306// There could be a race condition if two or more processes are calling this
307// function at the same time -- they could both pick the same filename.
308FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
309 const FilePath& base_name,
310 const char* extension) {
311 FilePath full_pathname;
312 int number = 0;
313 do {
314 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
315 } while (full_pathname.FileOrDirectoryExists());
316 return full_pathname;
317}
318
319// Returns true if FilePath ends with a path separator, which indicates that
320// it is intended to represent a directory. Returns false otherwise.
321// This does NOT check that a directory (or file) actually exists.
322bool FilePath::IsDirectory() const {
323 return !pathname_.empty() &&
324 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
325}
326
327// Create directories so that path exists. Returns true if successful or if
328// the directories already exist; returns false if unable to create directories
329// for any reason.
330bool FilePath::CreateDirectoriesRecursively() const {
331 if (!this->IsDirectory()) {
332 return false;
333 }
334
335 if (pathname_.length() == 0 || this->DirectoryExists()) {
336 return true;
337 }
338
339 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
340 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
341}
342
343// Create the directory so that path exists. Returns true if successful or
344// if the directory already exists; returns false if unable to create the
345// directory for any reason, including if the parent directory does not
346// exist. Not named "CreateDirectory" because that's a macro on Windows.
347bool FilePath::CreateFolder() const {
348#if GTEST_OS_WINDOWS_MOBILE
349 FilePath removed_sep(this->RemoveTrailingPathSeparator());
350 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
351 int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
352 delete[] unicode;
353#elif GTEST_OS_WINDOWS
354 int result = _mkdir(pathname_.c_str());
355#elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA || GTEST_OS_QURT
356 // do nothing
357 int result = 0;
358#else
359 int result = mkdir(pathname_.c_str(), 0777);
360#endif // GTEST_OS_WINDOWS_MOBILE
361
362 if (result == -1) {
363 return this->DirectoryExists(); // An error is OK if the directory exists.
364 }
365 return true; // No error.
366}
367
368// If input name has a trailing separator character, remove it and return the
369// name, otherwise return the name string unmodified.
370// On Windows platform, uses \ as the separator, other platforms use /.
371FilePath FilePath::RemoveTrailingPathSeparator() const {
372 return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))
373 : *this;
374}
375
376// Removes any redundant separators that might be in the pathname.
377// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
378// redundancies that might be in a pathname involving "." or "..".
379// Note that "\\Host\Share" does not contain a redundancy on Windows!
380void FilePath::Normalize() {
381 auto out = pathname_.begin();
382
383 auto i = pathname_.cbegin();
384#if GTEST_OS_WINDOWS
385 // UNC paths are treated specially
386 if (pathname_.end() - i >= 3 && IsPathSeparator(*i) &&
387 IsPathSeparator(*(i + 1)) && !IsPathSeparator(*(i + 2))) {
388 *(out++) = kPathSeparator;
389 *(out++) = kPathSeparator;
390 }
391#endif
392 while (i != pathname_.end()) {
393 const char character = *i;
394 if (!IsPathSeparator(character)) {
395 *(out++) = character;
396 } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
397 *(out++) = kPathSeparator;
398 }
399 ++i;
400 }
401
402 pathname_.erase(out, pathname_.end());
403}
404
405} // namespace internal
406} // namespace testing