|
| 1 | +#if defined(_WIN32) |
| 2 | +# include "win32_fs.h" |
| 3 | +#else |
| 4 | +# include "unistd.h" // for symlink() |
| 5 | +#endif |
| 6 | + |
| 7 | +#include <string> |
| 8 | + |
| 9 | +#if __has_include(<filesystem>) |
| 10 | +# include <filesystem> |
| 11 | +# include <system_error> |
| 12 | +#endif |
| 13 | + |
| 14 | +#include <sys/types.h> |
| 15 | +#include <sys/stat.h> |
| 16 | + |
| 17 | +#include "symlink_fs.h" |
| 18 | + |
| 19 | + |
| 20 | +bool fs_create_symlink(std::string target, std::string link) |
| 21 | +{ |
| 22 | + // confusing program errors if target is "" -- we'd never make such a symlink in real use. |
| 23 | + if(target.empty()) |
| 24 | + return false; |
| 25 | + |
| 26 | + // macOS needs empty check to avoid SIGABRT |
| 27 | + if(link.empty()) |
| 28 | + return false; |
| 29 | + |
| 30 | +#if defined(__MINGW32__) || (defined(_WIN32) && !defined(__cpp_lib_filesystem)) |
| 31 | + |
| 32 | + const DWORD attr = GetFileAttributesA(target.data()); |
| 33 | +// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileattributesa |
| 34 | +// https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants |
| 35 | + |
| 36 | + if (attr == INVALID_FILE_ATTRIBUTES) |
| 37 | + return false; |
| 38 | + |
| 39 | + DWORD p = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE; |
| 40 | + if(attr & FILE_ATTRIBUTE_DIRECTORY) |
| 41 | + p |= SYMBOLIC_LINK_FLAG_DIRECTORY; |
| 42 | + |
| 43 | + return CreateSymbolicLinkA(link.data(), target.data(), p); |
| 44 | +#elif defined(__cpp_lib_filesystem) |
| 45 | + std::error_code ec; |
| 46 | + std::filesystem::path t(target); |
| 47 | + |
| 48 | + bool isdir = std::filesystem::is_directory(t, ec); |
| 49 | + if (ec) |
| 50 | + return false; |
| 51 | + |
| 52 | + isdir |
| 53 | + ? std::filesystem::create_directory_symlink(t, link, ec) |
| 54 | + : std::filesystem::create_symlink(t, link, ec); |
| 55 | + |
| 56 | + return !ec; |
| 57 | +#else |
| 58 | + // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/symlink.2.html |
| 59 | + // https://linux.die.net/man/3/symlink |
| 60 | + return symlink(target.data(), link.data()) == 0; |
| 61 | +#endif |
| 62 | +} |
| 63 | + |
| 64 | + |
| 65 | +bool fs_is_symlink(std::string path) |
| 66 | +{ |
| 67 | + |
| 68 | +#if defined(__MINGW32__) || (defined(_WIN32) && !defined(__cpp_lib_filesystem)) |
| 69 | + return fs_win32_is_symlink(path); |
| 70 | +#elif defined(__cpp_lib_filesystem) |
| 71 | +// std::filesystem::symlink_status doesn't detect symlinks on MinGW |
| 72 | + std::error_code ec; |
| 73 | + const auto s = std::filesystem::symlink_status(path, ec); |
| 74 | + return !ec && std::filesystem::is_symlink(s); |
| 75 | +#else |
| 76 | + struct stat s; |
| 77 | + return lstat(path.data(), &s) == 0 && S_ISLNK(s.st_mode); |
| 78 | +#endif |
| 79 | +} |
0 commit comments