blob: bc610094e118d4e808b73f230de8e7e24aa2b05a [file] [log] [blame]
Misha Brukman7ae6ff42008-12-31 17:34:06 +00001// 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@gmail.com (Keith Ray)
31
Jay Foadb33f8e32011-07-27 09:25:14 +000032#include "gtest/internal/gtest-filepath.h"
33#include "gtest/internal/gtest-port.h"
Misha Brukman7ae6ff42008-12-31 17:34:06 +000034
35#include <stdlib.h>
36
Benjamin Kramer190f8ee2010-06-02 22:02:11 +000037#if GTEST_OS_WINDOWS_MOBILE
Jay Foadb33f8e32011-07-27 09:25:14 +000038# include <windows.h>
Benjamin Kramere4b9c932010-06-02 22:01:25 +000039#elif GTEST_OS_WINDOWS
Jay Foadb33f8e32011-07-27 09:25:14 +000040# include <direct.h>
41# include <io.h>
42#elif GTEST_OS_SYMBIAN || GTEST_OS_NACL
43// Symbian OpenC and NaCl have PATH_MAX in sys/syslimits.h
44# include <sys/syslimits.h>
Misha Brukman7ae6ff42008-12-31 17:34:06 +000045#else
Jay Foadb33f8e32011-07-27 09:25:14 +000046# include <limits.h>
47# include <climits> // Some Linux distributions define PATH_MAX here.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +000048#endif // GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +000049
Benjamin Kramere4b9c932010-06-02 22:01:25 +000050#if GTEST_OS_WINDOWS
Jay Foadb33f8e32011-07-27 09:25:14 +000051# define GTEST_PATH_MAX_ _MAX_PATH
Misha Brukman7ae6ff42008-12-31 17:34:06 +000052#elif defined(PATH_MAX)
Jay Foadb33f8e32011-07-27 09:25:14 +000053# define GTEST_PATH_MAX_ PATH_MAX
Misha Brukman7ae6ff42008-12-31 17:34:06 +000054#elif defined(_XOPEN_PATH_MAX)
Jay Foadb33f8e32011-07-27 09:25:14 +000055# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
Misha Brukman7ae6ff42008-12-31 17:34:06 +000056#else
Jay Foadb33f8e32011-07-27 09:25:14 +000057# define GTEST_PATH_MAX_ _POSIX_PATH_MAX
Misha Brukman7ae6ff42008-12-31 17:34:06 +000058#endif // GTEST_OS_WINDOWS
59
Jay Foadb33f8e32011-07-27 09:25:14 +000060#include "gtest/internal/gtest-string.h"
Misha Brukman7ae6ff42008-12-31 17:34:06 +000061
62namespace testing {
63namespace internal {
64
Benjamin Kramere4b9c932010-06-02 22:01:25 +000065#if GTEST_OS_WINDOWS
Benjamin Kramer57240ff2010-06-02 22:02:30 +000066// 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.
Misha Brukman7ae6ff42008-12-31 17:34:06 +000070const char kPathSeparator = '\\';
Benjamin Kramer57240ff2010-06-02 22:02:30 +000071const char kAlternatePathSeparator = '/';
Misha Brukman7ae6ff42008-12-31 17:34:06 +000072const char kPathSeparatorString[] = "\\";
Benjamin Kramer57240ff2010-06-02 22:02:30 +000073const char kAlternatePathSeparatorString[] = "/";
Jay Foadb33f8e32011-07-27 09:25:14 +000074# if GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +000075// 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.
78const char kCurrentDirectoryString[] = "\\";
79// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
80const DWORD kInvalidFileAttributes = 0xffffffff;
Jay Foadb33f8e32011-07-27 09:25:14 +000081# else
Misha Brukman7ae6ff42008-12-31 17:34:06 +000082const char kCurrentDirectoryString[] = ".\\";
Jay Foadb33f8e32011-07-27 09:25:14 +000083# endif // GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +000084#else
85const char kPathSeparator = '/';
86const char kPathSeparatorString[] = "/";
87const char kCurrentDirectoryString[] = "./";
88#endif // GTEST_OS_WINDOWS
89
Benjamin Kramer57240ff2010-06-02 22:02:30 +000090// Returns whether the given character is a valid path separator.
91static 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
Misha Brukman7ae6ff42008-12-31 17:34:06 +000099// Returns the current working directory, or "" if unsuccessful.
100FilePath FilePath::GetCurrentDir() {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000101#if GTEST_OS_WINDOWS_MOBILE
102 // Windows CE doesn't have a current directory, so we just return
103 // something reasonable.
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000104 return FilePath(kCurrentDirectoryString);
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000105#elif GTEST_OS_WINDOWS
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000106 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000107 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
108#else
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000109 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000110 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000111#endif // GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000112}
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.
118FilePath FilePath::RemoveExtension(const char* extension) const {
119 String dot_extension(String::Format(".%s", extension));
120 if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000121 return FilePath(String(pathname_.c_str(), pathname_.length() - 4));
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000122 }
123 return *this;
124}
125
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000126// Returns a pointer to the last occurrence of a valid path separator in
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000127// the FilePath. On Windows, for example, both '/' and '\' are valid path
128// separators. Returns NULL if no path separator was found.
129const char* FilePath::FindLastPathSeparator() const {
130 const char* const last_sep = strrchr(c_str(), kPathSeparator);
131#if GTEST_HAS_ALT_PATH_SEP_
132 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
133 // Comparing two pointers of which only one is NULL is undefined.
134 if (last_alt_sep != NULL &&
135 (last_sep == NULL || last_alt_sep > last_sep)) {
136 return last_alt_sep;
137 }
138#endif
139 return last_sep;
140}
141
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000142// Returns a copy of the FilePath with the directory part removed.
143// Example: FilePath("path/to/file").RemoveDirectoryName() returns
144// FilePath("file"). If there is no directory part ("just_a_file"), it returns
145// the FilePath unmodified. If there is no file part ("just_a_dir/") it
146// returns an empty FilePath ("").
147// On Windows platform, '\' is the path separator, otherwise it is '/'.
148FilePath FilePath::RemoveDirectoryName() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000149 const char* const last_sep = FindLastPathSeparator();
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000150 return last_sep ? FilePath(String(last_sep + 1)) : *this;
151}
152
153// RemoveFileName returns the directory path with the filename removed.
154// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
155// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
156// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
157// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
158// On Windows platform, '\' is the path separator, otherwise it is '/'.
159FilePath FilePath::RemoveFileName() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000160 const char* const last_sep = FindLastPathSeparator();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000161 String dir;
162 if (last_sep) {
163 dir = String(c_str(), last_sep + 1 - c_str());
164 } else {
165 dir = kCurrentDirectoryString;
166 }
167 return FilePath(dir);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000168}
169
170// Helper functions for naming files in a directory for xml output.
171
172// Given directory = "dir", base_name = "test", number = 0,
173// extension = "xml", returns "dir/test.xml". If number is greater
174// than zero (e.g., 12), returns "dir/test_12.xml".
175// On Windows platform, uses \ as the separator rather than /.
176FilePath FilePath::MakeFileName(const FilePath& directory,
177 const FilePath& base_name,
178 int number,
179 const char* extension) {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000180 String file;
181 if (number == 0) {
182 file = String::Format("%s.%s", base_name.c_str(), extension);
183 } else {
184 file = String::Format("%s_%d.%s", base_name.c_str(), number, extension);
185 }
186 return ConcatPaths(directory, FilePath(file));
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000187}
188
189// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
190// On Windows, uses \ as the separator rather than /.
191FilePath FilePath::ConcatPaths(const FilePath& directory,
192 const FilePath& relative_path) {
193 if (directory.IsEmpty())
194 return relative_path;
195 const FilePath dir(directory.RemoveTrailingPathSeparator());
196 return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator,
197 relative_path.c_str()));
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000198}
199
200// Returns true if pathname describes something findable in the file-system,
201// either a file, directory, or whatever.
202bool FilePath::FileOrDirectoryExists() const {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000203#if GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000204 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
205 const DWORD attributes = GetFileAttributes(unicode);
206 delete [] unicode;
207 return attributes != kInvalidFileAttributes;
208#else
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000209 posix::StatStruct file_stat;
210 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
211#endif // GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000212}
213
214// Returns true if pathname describes a directory in the file-system
215// that exists.
216bool FilePath::DirectoryExists() const {
217 bool result = false;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000218#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000219 // Don't strip off trailing separator if path is a root directory on
220 // Windows (like "C:\\").
221 const FilePath& path(IsRootDirectory() ? *this :
222 RemoveTrailingPathSeparator());
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000223#else
224 const FilePath& path(*this);
225#endif
226
227#if GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000228 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
229 const DWORD attributes = GetFileAttributes(unicode);
230 delete [] unicode;
231 if ((attributes != kInvalidFileAttributes) &&
232 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
233 result = true;
234 }
235#else
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000236 posix::StatStruct file_stat;
237 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
238 posix::IsDir(file_stat);
239#endif // GTEST_OS_WINDOWS_MOBILE
240
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000241 return result;
242}
243
244// Returns true if pathname describes a root directory. (Windows has one
245// root directory per disk drive.)
246bool FilePath::IsRootDirectory() const {
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000247#if GTEST_OS_WINDOWS
248 // TODO(wan@google.com): on Windows a network share like
249 // \\server\share can be a root directory, although it cannot be the
250 // current directory. Handle this properly.
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000251 return pathname_.length() == 3 && IsAbsolutePath();
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000252#else
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000253 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000254#endif
255}
256
257// Returns true if pathname describes an absolute path.
258bool FilePath::IsAbsolutePath() const {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000259 const char* const name = pathname_.c_str();
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000260#if GTEST_OS_WINDOWS
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000261 return pathname_.length() >= 3 &&
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000262 ((name[0] >= 'a' && name[0] <= 'z') ||
263 (name[0] >= 'A' && name[0] <= 'Z')) &&
264 name[1] == ':' &&
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000265 IsPathSeparator(name[2]);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000266#else
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000267 return IsPathSeparator(name[0]);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000268#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 {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000294 return !pathname_.empty() &&
295 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000296}
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
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000306 if (pathname_.length() == 0 || this->DirectoryExists()) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000307 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 {
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000319#if GTEST_OS_WINDOWS_MOBILE
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000320 FilePath removed_sep(this->RemoveTrailingPathSeparator());
321 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
322 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
323 delete [] unicode;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000324#elif GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000325 int result = _mkdir(pathname_.c_str());
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000326#else
327 int result = mkdir(pathname_.c_str(), 0777);
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000328#endif // GTEST_OS_WINDOWS_MOBILE
329
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000330 if (result == -1) {
331 return this->DirectoryExists(); // An error is OK if the directory exists.
332 }
333 return true; // No error.
334}
335
336// If input name has a trailing separator character, remove it and return the
337// name, otherwise return the name string unmodified.
338// On Windows platform, uses \ as the separator, other platforms use /.
339FilePath FilePath::RemoveTrailingPathSeparator() const {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000340 return IsDirectory()
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000341 ? FilePath(String(pathname_.c_str(), pathname_.length() - 1))
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000342 : *this;
343}
344
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000345// Removes any redundant separators that might be in the pathname.
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000346// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
347// redundancies that might be in a pathname involving "." or "..".
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000348// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000349void FilePath::Normalize() {
350 if (pathname_.c_str() == NULL) {
351 pathname_ = "";
352 return;
353 }
354 const char* src = pathname_.c_str();
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000355 char* const dest = new char[pathname_.length() + 1];
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000356 char* dest_ptr = dest;
Benjamin Kramer190f8ee2010-06-02 22:02:11 +0000357 memset(dest_ptr, 0, pathname_.length() + 1);
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000358
359 while (*src != '\0') {
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000360 *dest_ptr = *src;
361 if (!IsPathSeparator(*src)) {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000362 src++;
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000363 } else {
364#if GTEST_HAS_ALT_PATH_SEP_
365 if (*dest_ptr == kAlternatePathSeparator) {
366 *dest_ptr = kPathSeparator;
367 }
368#endif
369 while (IsPathSeparator(*src))
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000370 src++;
Benjamin Kramer57240ff2010-06-02 22:02:30 +0000371 }
372 dest_ptr++;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000373 }
374 *dest_ptr = '\0';
375 pathname_ = dest;
376 delete[] dest;
377}
378
379} // namespace internal
380} // namespace testing