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