blob: 07f828c9146670810016e41183b0ed96c5d7979c [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
32#include <gtest/internal/gtest-filepath.h>
33#include <gtest/internal/gtest-port.h>
34
35#include <stdlib.h>
36
37#ifdef _WIN32_WCE
38#include <windows.h>
Benjamin Kramere4b9c932010-06-02 22:01:25 +000039#elif GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +000040#include <direct.h>
41#include <io.h>
42#include <sys/stat.h>
Benjamin Kramere4b9c932010-06-02 22:01:25 +000043#elif GTEST_OS_SYMBIAN
Misha Brukman7ae6ff42008-12-31 17:34:06 +000044// Symbian OpenC has PATH_MAX in sys/syslimits.h
45#include <sys/syslimits.h>
46#include <unistd.h>
47#else
48#include <limits.h>
Benjamin Kramere4b9c932010-06-02 22:01:25 +000049#include <sys/stat.h> // NOLINT
50#include <unistd.h> // NOLINT
51#include <climits> // Some Linux distributions define PATH_MAX here.
Misha Brukman7ae6ff42008-12-31 17:34:06 +000052#endif // _WIN32_WCE or _WIN32
53
Benjamin Kramere4b9c932010-06-02 22:01:25 +000054#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +000055#define GTEST_PATH_MAX_ _MAX_PATH
56#elif defined(PATH_MAX)
57#define GTEST_PATH_MAX_ PATH_MAX
58#elif defined(_XOPEN_PATH_MAX)
59#define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
60#else
61#define GTEST_PATH_MAX_ _POSIX_PATH_MAX
62#endif // GTEST_OS_WINDOWS
63
64#include <gtest/internal/gtest-string.h>
65
66namespace testing {
67namespace internal {
68
Benjamin Kramere4b9c932010-06-02 22:01:25 +000069#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +000070const char kPathSeparator = '\\';
71const char kPathSeparatorString[] = "\\";
72#ifdef _WIN32_WCE
73// Windows CE doesn't have a current directory. You should not use
74// the current directory in tests on Windows CE, but this at least
75// provides a reasonable fallback.
76const char kCurrentDirectoryString[] = "\\";
77// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
78const DWORD kInvalidFileAttributes = 0xffffffff;
79#else
80const char kCurrentDirectoryString[] = ".\\";
81#endif // _WIN32_WCE
82#else
83const char kPathSeparator = '/';
84const char kPathSeparatorString[] = "/";
85const char kCurrentDirectoryString[] = "./";
86#endif // GTEST_OS_WINDOWS
87
88// Returns the current working directory, or "" if unsuccessful.
89FilePath FilePath::GetCurrentDir() {
90#ifdef _WIN32_WCE
91// Windows CE doesn't have a current directory, so we just return
92// something reasonable.
93 return FilePath(kCurrentDirectoryString);
Benjamin Kramere4b9c932010-06-02 22:01:25 +000094#elif GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +000095 char cwd[GTEST_PATH_MAX_ + 1] = {};
96 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
97#else
98 char cwd[GTEST_PATH_MAX_ + 1] = {};
99 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
100#endif
101}
102
103// Returns a copy of the FilePath with the case-insensitive extension removed.
104// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
105// FilePath("dir/file"). If a case-insensitive extension is not
106// found, returns a copy of the original FilePath.
107FilePath FilePath::RemoveExtension(const char* extension) const {
108 String dot_extension(String::Format(".%s", extension));
109 if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) {
110 return FilePath(String(pathname_.c_str(), pathname_.GetLength() - 4));
111 }
112 return *this;
113}
114
115// Returns a copy of the FilePath with the directory part removed.
116// Example: FilePath("path/to/file").RemoveDirectoryName() returns
117// FilePath("file"). If there is no directory part ("just_a_file"), it returns
118// the FilePath unmodified. If there is no file part ("just_a_dir/") it
119// returns an empty FilePath ("").
120// On Windows platform, '\' is the path separator, otherwise it is '/'.
121FilePath FilePath::RemoveDirectoryName() const {
122 const char* const last_sep = strrchr(c_str(), kPathSeparator);
123 return last_sep ? FilePath(String(last_sep + 1)) : *this;
124}
125
126// RemoveFileName returns the directory path with the filename removed.
127// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
128// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
129// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
130// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
131// On Windows platform, '\' is the path separator, otherwise it is '/'.
132FilePath FilePath::RemoveFileName() const {
133 const char* const last_sep = strrchr(c_str(), kPathSeparator);
134 return FilePath(last_sep ? String(c_str(), last_sep + 1 - c_str())
135 : String(kCurrentDirectoryString));
136}
137
138// Helper functions for naming files in a directory for xml output.
139
140// Given directory = "dir", base_name = "test", number = 0,
141// extension = "xml", returns "dir/test.xml". If number is greater
142// than zero (e.g., 12), returns "dir/test_12.xml".
143// On Windows platform, uses \ as the separator rather than /.
144FilePath FilePath::MakeFileName(const FilePath& directory,
145 const FilePath& base_name,
146 int number,
147 const char* extension) {
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000148 const FilePath file_name(
149 (number == 0) ?
150 String::Format("%s.%s", base_name.c_str(), extension) :
151 String::Format("%s_%d.%s", base_name.c_str(), number, extension));
152 return ConcatPaths(directory, file_name);
153}
154
155// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
156// On Windows, uses \ as the separator rather than /.
157FilePath FilePath::ConcatPaths(const FilePath& directory,
158 const FilePath& relative_path) {
159 if (directory.IsEmpty())
160 return relative_path;
161 const FilePath dir(directory.RemoveTrailingPathSeparator());
162 return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator,
163 relative_path.c_str()));
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000164}
165
166// Returns true if pathname describes something findable in the file-system,
167// either a file, directory, or whatever.
168bool FilePath::FileOrDirectoryExists() const {
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000169#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000170#ifdef _WIN32_WCE
171 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
172 const DWORD attributes = GetFileAttributes(unicode);
173 delete [] unicode;
174 return attributes != kInvalidFileAttributes;
175#else
176 struct _stat file_stat = {};
177 return _stat(pathname_.c_str(), &file_stat) == 0;
178#endif // _WIN32_WCE
179#else
Chris Lattnerf06b8592010-04-18 03:30:32 +0000180 struct stat file_stat;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000181 return stat(pathname_.c_str(), &file_stat) == 0;
182#endif // GTEST_OS_WINDOWS
183}
184
185// Returns true if pathname describes a directory in the file-system
186// that exists.
187bool FilePath::DirectoryExists() const {
188 bool result = false;
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000189#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000190 // Don't strip off trailing separator if path is a root directory on
191 // Windows (like "C:\\").
192 const FilePath& path(IsRootDirectory() ? *this :
193 RemoveTrailingPathSeparator());
194#ifdef _WIN32_WCE
195 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
196 const DWORD attributes = GetFileAttributes(unicode);
197 delete [] unicode;
198 if ((attributes != kInvalidFileAttributes) &&
199 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
200 result = true;
201 }
202#else
203 struct _stat file_stat = {};
204 result = _stat(path.c_str(), &file_stat) == 0 &&
205 (_S_IFDIR & file_stat.st_mode) != 0;
206#endif // _WIN32_WCE
207#else
Chris Lattnerf06b8592010-04-18 03:30:32 +0000208 struct stat file_stat;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000209 result = stat(pathname_.c_str(), &file_stat) == 0 &&
210 S_ISDIR(file_stat.st_mode);
211#endif // GTEST_OS_WINDOWS
212 return result;
213}
214
215// Returns true if pathname describes a root directory. (Windows has one
216// root directory per disk drive.)
217bool FilePath::IsRootDirectory() const {
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000218#if GTEST_OS_WINDOWS
219 // TODO(wan@google.com): on Windows a network share like
220 // \\server\share can be a root directory, although it cannot be the
221 // current directory. Handle this properly.
222 return pathname_.GetLength() == 3 && IsAbsolutePath();
223#else
224 return pathname_ == kPathSeparatorString;
225#endif
226}
227
228// Returns true if pathname describes an absolute path.
229bool FilePath::IsAbsolutePath() const {
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000230 const char* const name = pathname_.c_str();
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000231#if GTEST_OS_WINDOWS
232 return pathname_.GetLength() >= 3 &&
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000233 ((name[0] >= 'a' && name[0] <= 'z') ||
234 (name[0] >= 'A' && name[0] <= 'Z')) &&
235 name[1] == ':' &&
236 name[2] == kPathSeparator;
237#else
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000238 return name[0] == kPathSeparator;
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000239#endif
240}
241
242// Returns a pathname for a file that does not currently exist. The pathname
243// will be directory/base_name.extension or
244// directory/base_name_<number>.extension if directory/base_name.extension
245// already exists. The number will be incremented until a pathname is found
246// that does not already exist.
247// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
248// There could be a race condition if two or more processes are calling this
249// function at the same time -- they could both pick the same filename.
250FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
251 const FilePath& base_name,
252 const char* extension) {
253 FilePath full_pathname;
254 int number = 0;
255 do {
256 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
257 } while (full_pathname.FileOrDirectoryExists());
258 return full_pathname;
259}
260
261// Returns true if FilePath ends with a path separator, which indicates that
262// it is intended to represent a directory. Returns false otherwise.
263// This does NOT check that a directory (or file) actually exists.
264bool FilePath::IsDirectory() const {
265 return pathname_.EndsWith(kPathSeparatorString);
266}
267
268// Create directories so that path exists. Returns true if successful or if
269// the directories already exist; returns false if unable to create directories
270// for any reason.
271bool FilePath::CreateDirectoriesRecursively() const {
272 if (!this->IsDirectory()) {
273 return false;
274 }
275
276 if (pathname_.GetLength() == 0 || this->DirectoryExists()) {
277 return true;
278 }
279
280 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
281 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
282}
283
284// Create the directory so that path exists. Returns true if successful or
285// if the directory already exists; returns false if unable to create the
286// directory for any reason, including if the parent directory does not
287// exist. Not named "CreateDirectory" because that's a macro on Windows.
288bool FilePath::CreateFolder() const {
Benjamin Kramere4b9c932010-06-02 22:01:25 +0000289#if GTEST_OS_WINDOWS
Misha Brukman7ae6ff42008-12-31 17:34:06 +0000290#ifdef _WIN32_WCE
291 FilePath removed_sep(this->RemoveTrailingPathSeparator());
292 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
293 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
294 delete [] unicode;
295#else
296 int result = _mkdir(pathname_.c_str());
297#endif // !WIN32_WCE
298#else
299 int result = mkdir(pathname_.c_str(), 0777);
300#endif // _WIN32
301 if (result == -1) {
302 return this->DirectoryExists(); // An error is OK if the directory exists.
303 }
304 return true; // No error.
305}
306
307// If input name has a trailing separator character, remove it and return the
308// name, otherwise return the name string unmodified.
309// On Windows platform, uses \ as the separator, other platforms use /.
310FilePath FilePath::RemoveTrailingPathSeparator() const {
311 return pathname_.EndsWith(kPathSeparatorString)
312 ? FilePath(String(pathname_.c_str(), pathname_.GetLength() - 1))
313 : *this;
314}
315
316// Normalize removes any redundant separators that might be in the pathname.
317// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
318// redundancies that might be in a pathname involving "." or "..".
319void FilePath::Normalize() {
320 if (pathname_.c_str() == NULL) {
321 pathname_ = "";
322 return;
323 }
324 const char* src = pathname_.c_str();
325 char* const dest = new char[pathname_.GetLength() + 1];
326 char* dest_ptr = dest;
327 memset(dest_ptr, 0, pathname_.GetLength() + 1);
328
329 while (*src != '\0') {
330 *dest_ptr++ = *src;
331 if (*src != kPathSeparator)
332 src++;
333 else
334 while (*src == kPathSeparator)
335 src++;
336 }
337 *dest_ptr = '\0';
338 pathname_ = dest;
339 delete[] dest;
340}
341
342} // namespace internal
343} // namespace testing