gtest-filepath.cc 13.9 KB
Newer Older
shiqian's avatar
shiqian committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Authors: keith.ray@gmail.com (Keith Ray)

32
33
#include "gtest/internal/gtest-filepath.h"
#include "gtest/internal/gtest-port.h"
shiqian's avatar
shiqian committed
34

35
36
#include <stdlib.h>

37
#if GTEST_OS_WINDOWS_MOBILE
38
# include <windows.h>
zhanyong.wan's avatar
zhanyong.wan committed
39
#elif GTEST_OS_WINDOWS
40
41
# include <direct.h>
# include <io.h>
42
43
#elif GTEST_OS_SYMBIAN
// Symbian OpenC has PATH_MAX in sys/syslimits.h
44
# include <sys/syslimits.h>
45
#else
46
47
# include <limits.h>
# include <climits>  // Some Linux distributions define PATH_MAX here.
48
#endif  // GTEST_OS_WINDOWS_MOBILE
49

zhanyong.wan's avatar
zhanyong.wan committed
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
shiqian's avatar
shiqian committed
59

60
#include "gtest/internal/gtest-string.h"
shiqian's avatar
shiqian committed
61
62
63
64

namespace testing {
namespace internal {

zhanyong.wan's avatar
zhanyong.wan committed
65
#if GTEST_OS_WINDOWS
66
67
68
69
// On Windows, '\\' is the standard path separator, but many tools and the
// Windows API also accept '/' as an alternate path separator. Unless otherwise
// noted, a file path can contain either kind of path separators, or a mixture
// of them.
shiqian's avatar
shiqian committed
70
const char kPathSeparator = '\\';
71
const char kAlternatePathSeparator = '/';
shiqian's avatar
shiqian committed
72
const char kPathSeparatorString[] = "\\";
73
const char kAlternatePathSeparatorString[] = "/";
74
# if GTEST_OS_WINDOWS_MOBILE
75
76
77
78
79
80
// Windows CE doesn't have a current directory. You should not use
// the current directory in tests on Windows CE, but this at least
// provides a reasonable fallback.
const char kCurrentDirectoryString[] = "\\";
// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
const DWORD kInvalidFileAttributes = 0xffffffff;
81
# else
shiqian's avatar
shiqian committed
82
const char kCurrentDirectoryString[] = ".\\";
83
# endif  // GTEST_OS_WINDOWS_MOBILE
shiqian's avatar
shiqian committed
84
85
86
87
88
89
#else
const char kPathSeparator = '/';
const char kPathSeparatorString[] = "/";
const char kCurrentDirectoryString[] = "./";
#endif  // GTEST_OS_WINDOWS

90
91
92
93
94
95
96
97
98
// Returns whether the given character is a valid path separator.
static bool IsPathSeparator(char c) {
#if GTEST_HAS_ALT_PATH_SEP_
  return (c == kPathSeparator) || (c == kAlternatePathSeparator);
#else
  return c == kPathSeparator;
#endif
}

99
100
// Returns the current working directory, or "" if unsuccessful.
FilePath FilePath::GetCurrentDir() {
101
102
103
#if GTEST_OS_WINDOWS_MOBILE
  // Windows CE doesn't have a current directory, so we just return
  // something reasonable.
104
  return FilePath(kCurrentDirectoryString);
zhanyong.wan's avatar
zhanyong.wan committed
105
#elif GTEST_OS_WINDOWS
106
  char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
107
108
  return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
#else
109
  char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
110
  return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
111
#endif  // GTEST_OS_WINDOWS_MOBILE
112
113
}

shiqian's avatar
shiqian committed
114
115
116
117
118
// Returns a copy of the FilePath with the case-insensitive extension removed.
// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
// FilePath("dir/file"). If a case-insensitive extension is not
// found, returns a copy of the original FilePath.
FilePath FilePath::RemoveExtension(const char* extension) const {
119
120
121
122
  const std::string dot_extension = std::string(".") + extension;
  if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
    return FilePath(pathname_.substr(
        0, pathname_.length() - dot_extension.length()));
shiqian's avatar
shiqian committed
123
124
125
126
  }
  return *this;
}

127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// Returns a pointer to the last occurence of a valid path separator in
// the FilePath. On Windows, for example, both '/' and '\' are valid path
// separators. Returns NULL if no path separator was found.
const char* FilePath::FindLastPathSeparator() const {
  const char* const last_sep = strrchr(c_str(), kPathSeparator);
#if GTEST_HAS_ALT_PATH_SEP_
  const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
  // Comparing two pointers of which only one is NULL is undefined.
  if (last_alt_sep != NULL &&
      (last_sep == NULL || last_alt_sep > last_sep)) {
    return last_alt_sep;
  }
#endif
  return last_sep;
}

shiqian's avatar
shiqian committed
143
144
145
146
147
148
149
// Returns a copy of the FilePath with the directory part removed.
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
// the FilePath unmodified. If there is no file part ("just_a_dir/") it
// returns an empty FilePath ("").
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveDirectoryName() const {
150
  const char* const last_sep = FindLastPathSeparator();
151
  return last_sep ? FilePath(last_sep + 1) : *this;
shiqian's avatar
shiqian committed
152
153
154
155
156
157
158
159
160
}

// RemoveFileName returns the directory path with the filename removed.
// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveFileName() const {
161
  const char* const last_sep = FindLastPathSeparator();
162
  std::string dir;
163
  if (last_sep) {
164
    dir = std::string(c_str(), last_sep + 1 - c_str());
165
166
167
168
  } else {
    dir = kCurrentDirectoryString;
  }
  return FilePath(dir);
shiqian's avatar
shiqian committed
169
170
171
172
173
174
175
176
177
178
179
180
}

// Helper functions for naming files in a directory for xml output.

// Given directory = "dir", base_name = "test", number = 0,
// extension = "xml", returns "dir/test.xml". If number is greater
// than zero (e.g., 12), returns "dir/test_12.xml".
// On Windows platform, uses \ as the separator rather than /.
FilePath FilePath::MakeFileName(const FilePath& directory,
                                const FilePath& base_name,
                                int number,
                                const char* extension) {
181
  std::string file;
182
  if (number == 0) {
183
    file = base_name.string() + "." + extension;
184
  } else {
185
186
    file = base_name.string() + "_" + String::Format("%d", number).c_str()
        + "." + extension;
187
188
  }
  return ConcatPaths(directory, FilePath(file));
189
190
191
192
193
194
195
196
197
}

// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
// On Windows, uses \ as the separator rather than /.
FilePath FilePath::ConcatPaths(const FilePath& directory,
                               const FilePath& relative_path) {
  if (directory.IsEmpty())
    return relative_path;
  const FilePath dir(directory.RemoveTrailingPathSeparator());
198
  return FilePath(dir.string() + kPathSeparator + relative_path.string());
shiqian's avatar
shiqian committed
199
200
201
202
203
}

// Returns true if pathname describes something findable in the file-system,
// either a file, directory, or whatever.
bool FilePath::FileOrDirectoryExists() const {
204
#if GTEST_OS_WINDOWS_MOBILE
205
206
207
208
  LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
  const DWORD attributes = GetFileAttributes(unicode);
  delete [] unicode;
  return attributes != kInvalidFileAttributes;
shiqian's avatar
shiqian committed
209
#else
210
211
  posix::StatStruct file_stat;
  return posix::Stat(pathname_.c_str(), &file_stat) == 0;
212
#endif  // GTEST_OS_WINDOWS_MOBILE
shiqian's avatar
shiqian committed
213
214
215
216
217
218
}

// Returns true if pathname describes a directory in the file-system
// that exists.
bool FilePath::DirectoryExists() const {
  bool result = false;
zhanyong.wan's avatar
zhanyong.wan committed
219
#if GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
220
221
222
223
  // Don't strip off trailing separator if path is a root directory on
  // Windows (like "C:\\").
  const FilePath& path(IsRootDirectory() ? *this :
                                           RemoveTrailingPathSeparator());
224
225
226
227
#else
  const FilePath& path(*this);
#endif

228
#if GTEST_OS_WINDOWS_MOBILE
shiqian's avatar
shiqian committed
229
  LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
230
231
232
233
234
235
236
  const DWORD attributes = GetFileAttributes(unicode);
  delete [] unicode;
  if ((attributes != kInvalidFileAttributes) &&
      (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
    result = true;
  }
#else
237
238
  posix::StatStruct file_stat;
  result = posix::Stat(path.c_str(), &file_stat) == 0 &&
239
      posix::IsDir(file_stat);
240
#endif  // GTEST_OS_WINDOWS_MOBILE
241

shiqian's avatar
shiqian committed
242
243
244
  return result;
}

shiqian's avatar
shiqian committed
245
246
247
// Returns true if pathname describes a root directory. (Windows has one
// root directory per disk drive.)
bool FilePath::IsRootDirectory() const {
zhanyong.wan's avatar
zhanyong.wan committed
248
#if GTEST_OS_WINDOWS
249
250
251
  // TODO(wan@google.com): on Windows a network share like
  // \\server\share can be a root directory, although it cannot be the
  // current directory.  Handle this properly.
252
  return pathname_.length() == 3 && IsAbsolutePath();
253
#else
254
  return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
255
256
257
258
259
260
#endif
}

// Returns true if pathname describes an absolute path.
bool FilePath::IsAbsolutePath() const {
  const char* const name = pathname_.c_str();
zhanyong.wan's avatar
zhanyong.wan committed
261
#if GTEST_OS_WINDOWS
262
  return pathname_.length() >= 3 &&
shiqian's avatar
shiqian committed
263
264
265
     ((name[0] >= 'a' && name[0] <= 'z') ||
      (name[0] >= 'A' && name[0] <= 'Z')) &&
     name[1] == ':' &&
266
     IsPathSeparator(name[2]);
shiqian's avatar
shiqian committed
267
#else
268
  return IsPathSeparator(name[0]);
shiqian's avatar
shiqian committed
269
270
271
#endif
}

shiqian's avatar
shiqian committed
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Returns a pathname for a file that does not currently exist. The pathname
// will be directory/base_name.extension or
// directory/base_name_<number>.extension if directory/base_name.extension
// already exists. The number will be incremented until a pathname is found
// that does not already exist.
// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
// There could be a race condition if two or more processes are calling this
// function at the same time -- they could both pick the same filename.
FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
                                          const FilePath& base_name,
                                          const char* extension) {
  FilePath full_pathname;
  int number = 0;
  do {
    full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
  } while (full_pathname.FileOrDirectoryExists());
  return full_pathname;
}

// Returns true if FilePath ends with a path separator, which indicates that
// it is intended to represent a directory. Returns false otherwise.
// This does NOT check that a directory (or file) actually exists.
bool FilePath::IsDirectory() const {
295
296
  return !pathname_.empty() &&
         IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
shiqian's avatar
shiqian committed
297
298
299
300
301
302
303
304
305
306
}

// Create directories so that path exists. Returns true if successful or if
// the directories already exist; returns false if unable to create directories
// for any reason.
bool FilePath::CreateDirectoriesRecursively() const {
  if (!this->IsDirectory()) {
    return false;
  }

307
  if (pathname_.length() == 0 || this->DirectoryExists()) {
shiqian's avatar
shiqian committed
308
309
310
311
312
313
314
315
316
317
318
319
    return true;
  }

  const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
  return parent.CreateDirectoriesRecursively() && this->CreateFolder();
}

// Create the directory so that path exists. Returns true if successful or
// if the directory already exists; returns false if unable to create the
// directory for any reason, including if the parent directory does not
// exist. Not named "CreateDirectory" because that's a macro on Windows.
bool FilePath::CreateFolder() const {
320
#if GTEST_OS_WINDOWS_MOBILE
321
322
323
324
  FilePath removed_sep(this->RemoveTrailingPathSeparator());
  LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
  int result = CreateDirectory(unicode, NULL) ? 0 : -1;
  delete [] unicode;
325
#elif GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
326
327
328
  int result = _mkdir(pathname_.c_str());
#else
  int result = mkdir(pathname_.c_str(), 0777);
329
330
#endif  // GTEST_OS_WINDOWS_MOBILE

shiqian's avatar
shiqian committed
331
332
333
334
335
336
337
338
339
340
  if (result == -1) {
    return this->DirectoryExists();  // An error is OK if the directory exists.
  }
  return true;  // No error.
}

// If input name has a trailing separator character, remove it and return the
// name, otherwise return the name string unmodified.
// On Windows platform, uses \ as the separator, other platforms use /.
FilePath FilePath::RemoveTrailingPathSeparator() const {
341
  return IsDirectory()
342
      ? FilePath(pathname_.substr(0, pathname_.length() - 1))
shiqian's avatar
shiqian committed
343
344
345
      : *this;
}

346
// Removes any redundant separators that might be in the pathname.
shiqian's avatar
shiqian committed
347
348
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
// redundancies that might be in a pathname involving "." or "..".
349
// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
shiqian's avatar
shiqian committed
350
351
352
353
354
355
void FilePath::Normalize() {
  if (pathname_.c_str() == NULL) {
    pathname_ = "";
    return;
  }
  const char* src = pathname_.c_str();
356
  char* const dest = new char[pathname_.length() + 1];
shiqian's avatar
shiqian committed
357
  char* dest_ptr = dest;
358
  memset(dest_ptr, 0, pathname_.length() + 1);
shiqian's avatar
shiqian committed
359
360

  while (*src != '\0') {
361
362
    *dest_ptr = *src;
    if (!IsPathSeparator(*src)) {
shiqian's avatar
shiqian committed
363
      src++;
364
365
366
367
368
369
370
    } else {
#if GTEST_HAS_ALT_PATH_SEP_
      if (*dest_ptr == kAlternatePathSeparator) {
        *dest_ptr = kPathSeparator;
      }
#endif
      while (IsPathSeparator(*src))
shiqian's avatar
shiqian committed
371
        src++;
372
373
    }
    dest_ptr++;
shiqian's avatar
shiqian committed
374
375
376
377
378
379
  }
  *dest_ptr = '\0';
  pathname_ = dest;
  delete[] dest;
}

shiqian's avatar
shiqian committed
380
381
}  // namespace internal
}  // namespace testing