gtest-filepath.cc 14 KB

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