/firmware/tests/gtest-1.4.0/src/gtest-filepath.cc

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