/testlibs/gtest/src/gtest-filepath.cc

https://github.com/deltaforge/nebu-app-hadoop · C++ · 380 lines · 240 code · 33 blank · 107 comment · 48 complexity · f01dd369910f168cdf0ca372a74bc71d MD5 · raw file

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