You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

filesystem.cpp 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // \file filesystem.cpp
  2. //
  3. // Copyright (C) 2014 MicroNeil Research Corporation.
  4. //
  5. // This program is part of the MicroNeil Research Open Library Project. For
  6. // more information go to http://www.microneil.com/OpenLibrary/index.html
  7. //
  8. // This program is free software; you can redistribute it and/or modify it
  9. // under the terms of the GNU General Public License as published by the
  10. // Free Software Foundation; either version 2 of the License, or (at your
  11. // option) any later version.
  12. //
  13. // This program is distributed in the hope that it will be useful, but WITHOUT
  14. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  16. // more details.
  17. //
  18. // You should have received a copy of the GNU General Public License along with
  19. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  20. // Place, Suite 330, Boston, MA 02111-1307 USA
  21. //==============================================================================
  22. #ifdef _WIN32
  23. #include <windows.h>
  24. #include <Shlwapi.h>
  25. #else
  26. #include <dirent.h>
  27. #include <unistd.h>
  28. #include <sys/types.h>
  29. #include <cstdlib>
  30. #include <cstring>
  31. #include <cerrno>
  32. #endif
  33. #include <sys/stat.h>
  34. #include <stdexcept>
  35. #include "filesystem.hpp"
  36. namespace CodeDweller {
  37. #ifdef _WIN32
  38. char const FilePath::DirectorySeparator = '\\';
  39. #else
  40. char const FilePath::DirectorySeparator = '/';
  41. #endif
  42. bool FilePath::isAbsolute(std::string const &path) {
  43. #ifdef _WIN32
  44. return !PathIsRelative(path.c_str());
  45. #else
  46. if (path.empty()) {
  47. return false;
  48. }
  49. return ('/' == path[0]);
  50. #endif
  51. }
  52. std::string FilePath::join(std::initializer_list<std::string> components) {
  53. std::string path;
  54. for (auto &component : components) {
  55. if (!path.empty() &&
  56. path.back() != FilePath::DirectorySeparator) {
  57. path += FilePath::DirectorySeparator;
  58. if (isAbsolute(component)) {
  59. throw std::invalid_argument("Attempted to use absolute path \"" +
  60. component + "\" where a relative path "
  61. "is required.");
  62. }
  63. }
  64. path += component;
  65. }
  66. if (!path.empty() &&
  67. path.back() == FilePath::DirectorySeparator) {
  68. path.pop_back();
  69. }
  70. return path;
  71. }
  72. FileReference::FileReference(std::string fileName) :
  73. name(fileName),
  74. modTimestamp(0),
  75. size_bytes(0),
  76. fileExists(false),
  77. fileIsDirectory(false) {
  78. refresh();
  79. }
  80. std::string FileReference::FileName() const {
  81. return name;
  82. }
  83. void FileReference::refresh() {
  84. reset();
  85. // Load info.
  86. struct stat statBuffer;
  87. int status = stat(name.c_str(), &statBuffer);
  88. if (-1 == status) {
  89. // File no longer exists.
  90. if (ENOENT == errno) {
  91. return;
  92. }
  93. // Something went wrong.
  94. throw std::runtime_error("Error updating status of file \"" +
  95. name + "\": " + getErrorText());
  96. }
  97. modTimestamp = statBuffer.st_mtime;
  98. size_bytes = statBuffer.st_size;
  99. fileExists = true;
  100. fileIsDirectory = S_ISDIR(statBuffer.st_mode);
  101. }
  102. void FileReference:: reset() {
  103. modTimestamp = 0;
  104. size_bytes = 0;
  105. fileExists = false;
  106. fileIsDirectory = false;
  107. path.clear();
  108. }
  109. time_t FileReference::ModTimestamp() const {
  110. return modTimestamp;
  111. }
  112. size_t FileReference::Size() const {
  113. return size_bytes;
  114. }
  115. std::string FileReference::FullPath() {
  116. if (!path.empty()) {
  117. return path;
  118. }
  119. if (!fileExists) {
  120. return "";
  121. }
  122. #ifdef _WIN32
  123. // Get the size of the full path name.
  124. DWORD nTchars = GetFullPathName(name.c_str(), 0, NULL, NULL);
  125. if (0 == nTchars) {
  126. throw std::runtime_error("Error getting full path length for \"" + name
  127. + "\": " + getErrorText());
  128. }
  129. size_t bufSize = nTchars * sizeof(TCHAR);
  130. TCHAR fullPath[bufSize];
  131. nTchars = GetFullPathName(name.c_str(), bufSize, fullPath, NULL);
  132. if (0 == nTchars) {
  133. throw std::runtime_error("Error getting full path for \"" + name
  134. + "\": " + getErrorText());
  135. }
  136. path.assign(fullPath);
  137. #else
  138. char *realPath = realpath(name.c_str(), NULL);
  139. if (NULL == realPath) {
  140. // Nothing to do if the file doesn't exist.
  141. if (ENOENT == errno) {
  142. reset();
  143. return "";
  144. }
  145. // Something went wrong.
  146. throw std::runtime_error("Error checking file \"" + name + "\": " +
  147. getErrorText());
  148. }
  149. path.assign(realPath);
  150. free(realPath);
  151. #endif
  152. return path;
  153. }
  154. bool FileReference::exists() const {
  155. return fileExists;
  156. }
  157. bool FileReference::isDirectory() const {
  158. return fileIsDirectory;
  159. }
  160. std::string FileReference::getErrorText() {
  161. #ifdef _WIN32
  162. LPVOID winMsgBuf;
  163. DWORD lastError = GetLastError();
  164. FormatMessage(
  165. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  166. FORMAT_MESSAGE_FROM_SYSTEM |
  167. FORMAT_MESSAGE_IGNORE_INSERTS,
  168. NULL,
  169. lastError,
  170. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  171. (char *) &winMsgBuf,
  172. 0, NULL );
  173. std::string errMsg((char *) winMsgBuf);
  174. LocalFree(winMsgBuf);
  175. return errMsg;
  176. #else
  177. return strerror(errno);
  178. #endif
  179. }
  180. DirectoryReference::DirectoryReference(std::string dirName,
  181. bool (*dirFilter)(std::string)) :
  182. name(dirName),
  183. filter(dirFilter) {
  184. refresh();
  185. }
  186. void DirectoryReference::refresh() {
  187. // Clear any entries in this object.
  188. this->clear();
  189. #ifdef _WIN32
  190. HANDLE hDirList;
  191. WIN32_FIND_DATA dirListData;
  192. std::string searchString = FilePath::join({name, "*"});
  193. hDirList = FindFirstFile(searchString.c_str(), &dirListData);
  194. if (INVALID_HANDLE_VALUE == hDirList) {
  195. throw std::runtime_error("Error getting file list for \"" + name +
  196. "\": " + FileReference::getErrorText());
  197. }
  198. std::string tempName;
  199. while (INVALID_HANDLE_VALUE != hDirList) {
  200. tempName = FilePath::join({name, dirListData.cFileName});
  201. if ( (0 == filter) || (*filter)(dirListData.cFileName)) {
  202. emplace_back(tempName);
  203. }
  204. if (!FindNextFile(hDirList, &dirListData)) {
  205. FindClose(hDirList);
  206. hDirList = INVALID_HANDLE_VALUE;
  207. }
  208. }
  209. #else
  210. // Get new list.
  211. struct dirent **entries;
  212. int nEntries = scandir(name.c_str(), &entries, 0, 0);
  213. if (nEntries < 0) {
  214. throw std::runtime_error("Error getting file list for \"" + name +
  215. "\": " + FileReference::getErrorText());
  216. }
  217. // Create the FileReference objects.
  218. while (nEntries--) {
  219. std::string tempName;
  220. tempName = FilePath::join({name, entries[nEntries]->d_name});
  221. if ( (0 == filter) || (*filter)(entries[nEntries]->d_name)) {
  222. emplace_back(tempName);
  223. }
  224. free(entries[nEntries]);
  225. }
  226. free(entries);
  227. #endif
  228. }
  229. }