fileAPI.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2020 to 2022 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. // Include fileAPI without falling back on local syntax implicitly.
  24. // This prevents any local syntax from being implied in functions that are supposed to use variable pathSyntax.
  25. #define NO_IMPLICIT_PATH_SYNTAX
  26. #include "fileAPI.h"
  27. #ifdef USE_MICROSOFT_WINDOWS
  28. #include <windows.h>
  29. #else
  30. #include <unistd.h>
  31. #include <sys/stat.h>
  32. #include <dirent.h>
  33. #endif
  34. #include <fstream>
  35. #include <cstdlib>
  36. #include "bufferAPI.h"
  37. namespace dsr {
  38. constexpr const char32_t* getPathSeparator(PathSyntax pathSyntax) {
  39. if (pathSyntax == PathSyntax::Windows) {
  40. return U"\\";
  41. } else if (pathSyntax == PathSyntax::Posix) {
  42. return U"/";
  43. } else {
  44. return U"?";
  45. }
  46. }
  47. #ifdef USE_MICROSOFT_WINDOWS
  48. using NativeChar = wchar_t; // UTF-16
  49. static const CharacterEncoding nativeEncoding = CharacterEncoding::BOM_UTF16LE;
  50. #define FILE_ACCESS_FUNCTION _wfopen
  51. #define FILE_ACCESS_SELECTION (write ? L"wb" : L"rb")
  52. List<String> file_impl_getInputArguments() {
  53. // Get a pointer to static memory with the command
  54. LPWSTR cmd = GetCommandLineW();
  55. // Split the arguments into an array of arguments
  56. int argc = 0;
  57. LPWSTR *argv = CommandLineToArgvW(cmd, &argc);
  58. // Convert the arguments into dsr::List<dsr::String>
  59. List<String> args = file_impl_convertInputArguments(argc, (void**)argv);
  60. // Free the native list of arguments
  61. LocalFree(argv);
  62. return args;
  63. }
  64. #else
  65. using NativeChar = char; // UTF-8
  66. static const CharacterEncoding nativeEncoding = CharacterEncoding::BOM_UTF8;
  67. #define FILE_ACCESS_FUNCTION fopen
  68. #define FILE_ACCESS_SELECTION (write ? "wb" : "rb")
  69. List<String> file_impl_getInputArguments() { return List<String>(); }
  70. #endif
  71. // Length of fixed size buffers.
  72. const int maxLength = 512;
  73. static const NativeChar* toNativeString(const ReadableString &filename, Buffer &buffer) {
  74. buffer = string_saveToMemory(filename, nativeEncoding, LineEncoding::CrLf, false, true);
  75. return (const NativeChar*)buffer_dangerous_getUnsafeData(buffer);
  76. }
  77. static String fromNativeString(const NativeChar *text) {
  78. return string_dangerous_decodeFromData(text, nativeEncoding);
  79. }
  80. List<String> file_impl_convertInputArguments(int argn, void **argv) {
  81. List<String> result;
  82. result.reserve(argn);
  83. for (int a = 0; a < argn; a++) {
  84. result.push(fromNativeString((NativeChar*)(argv[a])));
  85. }
  86. return result;
  87. }
  88. static FILE* accessFile(const ReadableString &filename, bool write) {
  89. Buffer buffer;
  90. return FILE_ACCESS_FUNCTION(toNativeString(filename, buffer), FILE_ACCESS_SELECTION);
  91. }
  92. Buffer file_loadBuffer(const ReadableString& filename, bool mustExist) {
  93. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  94. FILE *file = accessFile(modifiedFilename, false);
  95. if (file != nullptr) {
  96. // Get the file's size by going to the end, measuring, and going back
  97. fseek(file, 0L, SEEK_END);
  98. int64_t fileSize = ftell(file);
  99. rewind(file);
  100. // Allocate a buffer of the file's size
  101. Buffer buffer = buffer_create(fileSize);
  102. fread((void*)buffer_dangerous_getUnsafeData(buffer), fileSize, 1, file);
  103. fclose(file);
  104. return buffer;
  105. } else {
  106. if (mustExist) {
  107. throwError(U"Failed to load ", modifiedFilename, ".\n");
  108. }
  109. // If the file cound not be found and opened, an empty buffer is returned
  110. return Buffer();
  111. }
  112. }
  113. bool file_saveBuffer(const ReadableString& filename, Buffer buffer, bool mustWork) {
  114. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  115. if (!buffer_exists(buffer)) {
  116. if (mustWork) {
  117. throwError(U"buffer_save: Can't save a buffer that don't exist to a file.\n");
  118. }
  119. return false;
  120. } else {
  121. FILE *file = accessFile(modifiedFilename, true);
  122. if (file != nullptr) {
  123. fwrite((void*)buffer_dangerous_getUnsafeData(buffer), buffer_getSize(buffer), 1, file);
  124. fclose(file);
  125. } else {
  126. if (mustWork) {
  127. throwError("Failed to save ", modifiedFilename, ".\n");
  128. }
  129. return false;
  130. }
  131. }
  132. // Success if there are no errors.
  133. return true;
  134. }
  135. const char32_t* file_separator() {
  136. return getPathSeparator(LOCAL_PATH_SYNTAX);
  137. }
  138. bool file_isSeparator(DsrChar c) {
  139. return c == U'\\' || c == U'/';
  140. }
  141. // Returns the index of the first / or \ in path, or defaultIndex if none existed.
  142. int64_t file_findFirstSeparator(const ReadableString &path, int64_t defaultIndex, int64_t startIndex) {
  143. for (int64_t i = startIndex; i < string_length(path); i++) {
  144. DsrChar c = path[i];
  145. if (file_isSeparator(c)) {
  146. return i;
  147. }
  148. }
  149. return defaultIndex;
  150. }
  151. // Returns the index of the last / or \ in path, or defaultIndex if none existed.
  152. int64_t file_findLastSeparator(const ReadableString &path, int64_t defaultIndex) {
  153. for (int64_t i = string_length(path) - 1; i >= 0; i--) {
  154. DsrChar c = path[i];
  155. if (file_isSeparator(c)) {
  156. return i;
  157. }
  158. }
  159. return defaultIndex;
  160. }
  161. String file_optimizePath(const ReadableString &path, PathSyntax pathSyntax) {
  162. String result; // The final output being appended.
  163. String currentEntry; // The current entry.
  164. bool hadSeparator = false;
  165. bool hadContent = false;
  166. int64_t inputLength = string_length(path);
  167. string_reserve(result, inputLength);
  168. // Read null terminator from one element outside of the path to allow concluding an entry not followed by any separator.
  169. // The null terminator is not actually stored, but reading out of bound gives a null terminator.
  170. for (int64_t i = 0; i <= inputLength; i++) {
  171. DsrChar c = path[i];
  172. bool separator = file_isSeparator(c);
  173. if (separator || i == inputLength) {
  174. bool appendEntry = true;
  175. bool appendSeparator = separator;
  176. if (hadSeparator) {
  177. if (hadContent && string_length(currentEntry) == 0) {
  178. // Reduce non-leading // into / by skipping "" entries.
  179. // Any leading multiples of slashes have their count preserved, because some systems use them to indicate special use cases.
  180. appendEntry = false;
  181. appendSeparator = false;
  182. } else if (string_match(currentEntry, U".")) {
  183. // Reduce /./ into / by skipping "." entries.
  184. appendEntry = false;
  185. appendSeparator = false;
  186. } else if (string_match(currentEntry, U"..")) {
  187. // Reduce the parent directory against the reverse ".." entry.
  188. result = file_getRelativeParentFolder(result, pathSyntax);
  189. if (string_match(result, U"?")) {
  190. return U"?";
  191. }
  192. appendEntry = false;
  193. }
  194. }
  195. if (appendEntry) {
  196. string_append(result, string_removeOuterWhiteSpace(currentEntry));
  197. }
  198. if (appendSeparator) {
  199. string_append(result, getPathSeparator(pathSyntax));
  200. }
  201. currentEntry = U"";
  202. if (separator) {
  203. hadSeparator = true;
  204. }
  205. } else {
  206. string_appendChar(currentEntry, c);
  207. hadContent = true;
  208. }
  209. }
  210. // Remove trailing separators if we had content.
  211. if (hadSeparator && hadContent) {
  212. int64_t lastNonSeparator = -1;
  213. for (int64_t i = string_length(result) - 1; i >= 0; i--) {
  214. if (!file_isSeparator(result[i])) {
  215. lastNonSeparator = i;
  216. break;
  217. }
  218. }
  219. result = string_until(result, lastNonSeparator);
  220. }
  221. return result;
  222. }
  223. ReadableString file_getPathlessName(const ReadableString &path) {
  224. return string_after(path, file_findLastSeparator(path));
  225. }
  226. ReadableString file_getExtension(const String& filename) {
  227. int64_t lastDotIndex = string_findLast(filename, U'.');
  228. int64_t lastSeparatorIndex = file_findLastSeparator(filename);
  229. // Only use the last dot if there is no folder separator after it.
  230. if (lastDotIndex != -1 && lastSeparatorIndex < lastDotIndex) {
  231. return string_removeOuterWhiteSpace(string_after(filename, lastDotIndex));
  232. } else {
  233. return U"";
  234. }
  235. }
  236. String file_getRelativeParentFolder(const ReadableString &path, PathSyntax pathSyntax) {
  237. String optimizedPath = file_optimizePath(path, pathSyntax);
  238. if (string_length(optimizedPath) == 0) {
  239. // Use .. to go outside of the current directory.
  240. return U"..";
  241. } else if (string_match(file_getPathlessName(optimizedPath), U"?")) {
  242. // From unknown to unknown.
  243. return U"?";
  244. } else if (file_isRoot(optimizedPath, false, pathSyntax)) {
  245. // If it's the known true root, then we know that it does not have a parent and must fail.
  246. return U"?";
  247. } else if (file_isRoot(optimizedPath, true, pathSyntax)) {
  248. // If it's an alias for an arbitrary folder, use .. to leave it.
  249. return file_combinePaths(optimizedPath, U"..", pathSyntax);
  250. } else if (string_match(file_getPathlessName(optimizedPath), U"..")) {
  251. // Add more dots to the path.
  252. return file_combinePaths(optimizedPath, U"..", pathSyntax);
  253. } else {
  254. // Inside of something.
  255. int64_t lastSeparator = file_findLastSeparator(optimizedPath, 0);
  256. if (pathSyntax == PathSyntax::Windows) {
  257. // Return everything before the last separator.
  258. return string_before(optimizedPath, lastSeparator);
  259. } else { // PathSyntax::Posix
  260. if (file_hasRoot(path, false, pathSyntax) && lastSeparator == 0) {
  261. // Keep the absolute root.
  262. return U"/";
  263. } else {
  264. // Keep everything before the last separator.
  265. return string_before(optimizedPath, lastSeparator);
  266. }
  267. }
  268. }
  269. }
  270. String file_getTheoreticalAbsoluteParentFolder(const ReadableString &path, const ReadableString &currentPath, PathSyntax pathSyntax) {
  271. if (file_hasRoot(path, true, LOCAL_PATH_SYNTAX)) {
  272. // Absolute paths should be treated the same as a theoretical path.
  273. return file_getRelativeParentFolder(path, pathSyntax);
  274. } else {
  275. // If the input is not absolute, convert it before taking the parent directory.
  276. return file_getRelativeParentFolder(file_getTheoreticalAbsolutePath(path, currentPath, pathSyntax), pathSyntax);
  277. }
  278. }
  279. String file_getAbsoluteParentFolder(const ReadableString &path) {
  280. return file_getTheoreticalAbsoluteParentFolder(path, file_getCurrentPath(), LOCAL_PATH_SYNTAX);
  281. }
  282. bool file_isRoot(const ReadableString &path, bool treatHomeFolderAsRoot, PathSyntax pathSyntax) {
  283. ReadableString cleanPath = string_removeOuterWhiteSpace(path);
  284. int64_t length = string_length(cleanPath);
  285. if (length == 0) {
  286. // Relative path is not a root.
  287. return false;
  288. } else if (length == 1) {
  289. DsrChar c = cleanPath[0];
  290. if (pathSyntax == PathSyntax::Windows) {
  291. return c == U'\\'; // Implicit drive root.
  292. } else { // PathSyntax::Posix
  293. return c == U'/' || (c == U'~' && treatHomeFolderAsRoot); // Root over all drives or home folder.
  294. }
  295. } else {
  296. if (pathSyntax == PathSyntax::Windows && cleanPath[length - 1] == U':') {
  297. // C:, D:, ...
  298. return true;
  299. } else {
  300. return false;
  301. }
  302. }
  303. }
  304. bool file_hasRoot(const ReadableString &path, bool treatHomeFolderAsRoot, PathSyntax pathSyntax) {
  305. int64_t firstSeparator = file_findFirstSeparator(path);
  306. if (firstSeparator == -1) {
  307. // If there is no separator, path has a root if it is a root.
  308. return file_isRoot(path, treatHomeFolderAsRoot, pathSyntax);
  309. } else if (firstSeparator == 0) {
  310. // Starting with a separator. Either an implicit drive on Windows or the whole system's root on Posix.
  311. return true;
  312. } else {
  313. // Has a root if the first entry before the first slash is a root.
  314. return file_isRoot(string_before(path, firstSeparator), treatHomeFolderAsRoot, pathSyntax);
  315. }
  316. }
  317. bool file_setCurrentPath(const ReadableString &path) {
  318. Buffer buffer;
  319. const NativeChar *nativePath = toNativeString(file_optimizePath(path, LOCAL_PATH_SYNTAX), buffer);
  320. #ifdef USE_MICROSOFT_WINDOWS
  321. return SetCurrentDirectoryW(nativePath);
  322. #else
  323. return chdir(nativePath) == 0;
  324. #endif
  325. }
  326. String file_getCurrentPath() {
  327. #ifdef USE_MICROSOFT_WINDOWS
  328. NativeChar resultBuffer[maxLength + 1] = {0};
  329. GetCurrentDirectoryW(maxLength, resultBuffer);
  330. return fromNativeString(resultBuffer);
  331. #else
  332. NativeChar resultBuffer[maxLength + 1] = {0};
  333. getcwd(resultBuffer, maxLength);
  334. return fromNativeString(resultBuffer);
  335. #endif
  336. }
  337. String file_followSymbolicLink(const ReadableString &path, bool mustExist) {
  338. String modifiedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  339. Buffer buffer;
  340. const NativeChar *nativePath = toNativeString(modifiedPath, buffer);
  341. #ifdef USE_MICROSOFT_WINDOWS
  342. // TODO: Is there anything that can be used as a symbolic link on Windows?
  343. #else
  344. NativeChar resultBuffer[maxLength + 1] = {0};
  345. if (readlink(nativePath, resultBuffer, maxLength) != -1) {
  346. return fromNativeString(resultBuffer);
  347. }
  348. #endif
  349. if (mustExist) { throwError(U"The symbolic link ", path, " could not be found!\n"); }
  350. return U"?";
  351. }
  352. String file_getApplicationFolder(bool allowFallback) {
  353. #ifdef USE_MICROSOFT_WINDOWS
  354. NativeChar resultBuffer[maxLength + 1] = {0};
  355. GetModuleFileNameW(nullptr, resultBuffer, maxLength);
  356. return file_getRelativeParentFolder(fromNativeString(resultBuffer), LOCAL_PATH_SYNTAX);
  357. #else
  358. NativeChar resultBuffer[maxLength + 1] = {0};
  359. if (readlink("/proc/self/exe", resultBuffer, maxLength) != -1) {
  360. // Linux detected
  361. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  362. } else if (readlink("/proc/curproc/file", resultBuffer, maxLength) != -1) {
  363. // BSD detected
  364. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  365. } else if (readlink("/proc/self/path/a.out", resultBuffer, maxLength) != -1) {
  366. // Solaris detected
  367. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  368. } else if (allowFallback) {
  369. return file_getCurrentPath();
  370. } else {
  371. throwError("file_getApplicationFolder is not implemented for the current system!\n");
  372. return U"";
  373. }
  374. #endif
  375. }
  376. String file_combinePaths(const ReadableString &a, const ReadableString &b, PathSyntax pathSyntax) {
  377. ReadableString cleanA = string_removeOuterWhiteSpace(a);
  378. ReadableString cleanB = string_removeOuterWhiteSpace(b);
  379. int64_t lengthA = string_length(cleanA);
  380. int64_t lengthB = string_length(cleanB);
  381. if (file_hasRoot(b, true, pathSyntax)) {
  382. // Restarting from root or home folder.
  383. return cleanB;
  384. } else if (lengthA == 0) {
  385. // Ignoring initial relative path, so that relative paths are not suddenly moved to the root by a new separator.
  386. return cleanB;
  387. } else if (lengthB == 0) {
  388. // Ignoring initial relative path, so that relative paths are not suddenly moved to the root by a new separator.
  389. return cleanA;
  390. } else {
  391. if (file_isSeparator(a[lengthA - 1])) {
  392. // Already ending with a separator.
  393. return string_combine(cleanA, cleanB);
  394. } else {
  395. // Combine using a separator.
  396. return string_combine(cleanA, getPathSeparator(pathSyntax), cleanB);
  397. }
  398. }
  399. }
  400. // Returns path with the drive letter applied from currentPath if missing in path.
  401. // Used for converting drive relative paths into true absolute paths on MS-Windows.
  402. static String applyDriveLetter(const ReadableString &path, const ReadableString &currentPath) {
  403. // Convert implicit drive into a named drive.
  404. if (path[0] == U'\\') {
  405. int64_t colonIndex = string_findFirst(currentPath, U':', -1);
  406. if (colonIndex == -1) {
  407. return U"?";
  408. } else {
  409. // Get the drive letter from the current path.
  410. String drive = string_until(currentPath, colonIndex);
  411. return string_combine(drive, path);
  412. }
  413. } else {
  414. // Already absolute.
  415. return path;
  416. }
  417. }
  418. String file_getTheoreticalAbsolutePath(const ReadableString &path, const ReadableString &currentPath, PathSyntax pathSyntax) {
  419. // Home folders are absolute enough, because we don't want to lose the account ambiguity by mangling it into hardcoded usernames.
  420. if (file_hasRoot(path, true, pathSyntax)) {
  421. if (pathSyntax == PathSyntax::Windows) {
  422. // Make sure that no drive letter is missing.
  423. return applyDriveLetter(file_optimizePath(path, pathSyntax), currentPath);
  424. } else {
  425. // Already absolute.
  426. return file_optimizePath(path, pathSyntax);
  427. }
  428. } else {
  429. // Convert from relative path.
  430. return file_optimizePath(file_combinePaths(currentPath, path, pathSyntax), pathSyntax);
  431. }
  432. }
  433. String file_getAbsolutePath(const ReadableString &path) {
  434. return file_getTheoreticalAbsolutePath(path, file_getCurrentPath(), LOCAL_PATH_SYNTAX);
  435. }
  436. int64_t file_getFileSize(const ReadableString& filename) {
  437. int64_t result = -1;
  438. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  439. Buffer buffer;
  440. const NativeChar *nativePath = toNativeString(modifiedFilename, buffer);
  441. #ifdef USE_MICROSOFT_WINDOWS
  442. LARGE_INTEGER fileSize;
  443. HANDLE fileHandle = CreateFileW(nativePath, 0, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  444. if (fileHandle != INVALID_HANDLE_VALUE) {
  445. if (GetFileSizeEx(fileHandle, &fileSize)) {
  446. result = fileSize.QuadPart;
  447. }
  448. CloseHandle(fileHandle);
  449. }
  450. #else
  451. struct stat info;
  452. if (stat(nativePath, &info) == 0) {
  453. result = info.st_size;
  454. }
  455. #endif
  456. return result;
  457. }
  458. String& string_toStreamIndented(String& target, const EntryType& source, const ReadableString& indentation) {
  459. string_append(target, indentation);
  460. if (source == EntryType::NotFound) {
  461. string_append(target, U"not found");
  462. } else if (source == EntryType::File) {
  463. string_append(target, U"a file");
  464. } else if (source == EntryType::Folder) {
  465. string_append(target, U"a folder");
  466. } else if (source == EntryType::SymbolicLink) {
  467. string_append(target, U"a symbolic link");
  468. } else {
  469. string_append(target, U"unhandled");
  470. }
  471. return target;
  472. }
  473. EntryType file_getEntryType(const ReadableString &path) {
  474. EntryType result = EntryType::NotFound;
  475. String optimizedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  476. Buffer buffer;
  477. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  478. #ifdef USE_MICROSOFT_WINDOWS
  479. DWORD dwAttrib = GetFileAttributesW(nativePath);
  480. if (dwAttrib != INVALID_FILE_ATTRIBUTES) {
  481. if (dwAttrib & FILE_ATTRIBUTE_DIRECTORY) {
  482. result = EntryType::Folder;
  483. } else {
  484. result = EntryType::File;
  485. }
  486. }
  487. #else
  488. struct stat info;
  489. int errorCode = stat(nativePath, &info);
  490. if (errorCode == 0) {
  491. if (S_ISDIR(info.st_mode)) {
  492. result = EntryType::Folder;
  493. } else if (S_ISREG(info.st_mode)) {
  494. result = EntryType::File;
  495. } else if (S_ISLNK(info.st_mode)) {
  496. result = EntryType::SymbolicLink;
  497. } else {
  498. result = EntryType::UnhandledType;
  499. }
  500. }
  501. #endif
  502. return result;
  503. }
  504. bool file_getFolderContent(const ReadableString& folderPath, std::function<void(const ReadableString& entryPath, const ReadableString& entryName, EntryType entryType)> action) {
  505. String optimizedPath = file_optimizePath(folderPath, LOCAL_PATH_SYNTAX);
  506. #ifdef USE_MICROSOFT_WINDOWS
  507. String pattern = file_combinePaths(optimizedPath, U"*.*", LOCAL_PATH_SYNTAX);
  508. Buffer buffer;
  509. const NativeChar *nativePattern = toNativeString(pattern, buffer);
  510. WIN32_FIND_DATAW findData;
  511. HANDLE findHandle = FindFirstFileW(nativePattern, &findData);
  512. if (findHandle == INVALID_HANDLE_VALUE) {
  513. return false;
  514. } else {
  515. while (true) {
  516. String entryName = fromNativeString(findData.cFileName);
  517. if (!string_match(entryName, U".") && !string_match(entryName, U"..")) {
  518. String entryPath = file_combinePaths(optimizedPath, entryName, LOCAL_PATH_SYNTAX);
  519. EntryType entryType = EntryType::UnhandledType;
  520. if(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  521. entryType = EntryType::Folder;
  522. } else {
  523. entryType = EntryType::File;
  524. }
  525. action(entryPath, entryName, entryType);
  526. }
  527. if (!FindNextFileW(findHandle, &findData)) { break; }
  528. }
  529. FindClose(findHandle);
  530. }
  531. #else
  532. Buffer buffer;
  533. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  534. DIR *directory = opendir(nativePath);
  535. if (directory == nullptr) {
  536. return false;
  537. } else {
  538. while (true) {
  539. dirent *entry = readdir(directory);
  540. if (entry != nullptr) {
  541. String entryName = fromNativeString(entry->d_name);
  542. if (!string_match(entryName, U".") && !string_match(entryName, U"..")) {
  543. String entryPath = file_combinePaths(optimizedPath, entryName, LOCAL_PATH_SYNTAX);
  544. EntryType entryType = file_getEntryType(entryPath);
  545. action(entryPath, entryName, entryType);
  546. }
  547. } else {
  548. break;
  549. }
  550. }
  551. }
  552. closedir(directory);
  553. #endif
  554. return true;
  555. }
  556. void file_getPathEntries(const ReadableString& path, std::function<void(ReadableString, int64_t, int64_t)> action) {
  557. int64_t sectionStart = 0;
  558. int64_t length = string_length(path);
  559. for (int64_t i = 0; i < string_length(path); i++) {
  560. DsrChar c = path[i];
  561. if (file_isSeparator(c)) {
  562. int64_t sectionEnd = i - 1; // Inclusive end
  563. ReadableString content = string_inclusiveRange(path, sectionStart, sectionEnd);
  564. if (string_length(content)) { action(content, sectionStart, sectionEnd); }
  565. sectionStart = i + 1;
  566. }
  567. }
  568. if (length > sectionStart) {
  569. int64_t sectionEnd = length - 1; // Inclusive end
  570. ReadableString content = string_inclusiveRange(path, sectionStart, sectionEnd);
  571. if (string_length(content)) { action(content, sectionStart, sectionEnd); }
  572. }
  573. }
  574. bool file_createFolder(const ReadableString &path) {
  575. bool result = false;
  576. String optimizedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  577. Buffer buffer;
  578. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  579. #ifdef USE_MICROSOFT_WINDOWS
  580. // Create folder with permissions inherited.
  581. result = (CreateDirectoryW(nativePath, nullptr) != 0);
  582. #else
  583. // Create folder with default permissions. Read, write and search for owner and group. Read and search for others.
  584. result = (mkdir(nativePath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
  585. #endif
  586. return result;
  587. }
  588. }