|
| 1 | +/** |
| 2 | + * \file os_linkdir.c |
| 3 | + * \brief Creates a symbolic link to a directory. |
| 4 | + * \author Copyright (c) 2024 Jess Perkins and the Premake project |
| 5 | + */ |
| 6 | + |
| 7 | +#include <sys/stat.h> |
| 8 | +#include "premake.h" |
| 9 | + |
| 10 | +int do_linkdir(lua_State* L, const char* src, const char* dst) |
| 11 | +{ |
| 12 | +#if PLATFORM_WINDOWS |
| 13 | + // Prepend the drive letter if a relative path is given |
| 14 | + char dstPath[MAX_PATH]; |
| 15 | + char srcPath[MAX_PATH]; |
| 16 | + |
| 17 | + do_normalize(L, srcPath, src); |
| 18 | + do_normalize(L, dstPath, dst); |
| 19 | + do_translate(dstPath, '\\'); |
| 20 | + do_translate(srcPath, '\\'); |
| 21 | + |
| 22 | + // Promote to wide path |
| 23 | + wchar_t wSrcPath[MAX_PATH]; |
| 24 | + wchar_t wDstPath[MAX_PATH]; |
| 25 | + |
| 26 | + MultiByteToWideChar(CP_UTF8, 0, srcPath, -1, wSrcPath, MAX_PATH); |
| 27 | + MultiByteToWideChar(CP_UTF8, 0, dstPath, -1, wDstPath, MAX_PATH); |
| 28 | + |
| 29 | + // If the source path is relative, prepend the current working directory |
| 30 | + if (!do_isabsolute(src)) |
| 31 | + { |
| 32 | + // Get the current working directory |
| 33 | + wchar_t cwd[MAX_PATH]; |
| 34 | + GetCurrentDirectoryW(MAX_PATH, cwd); |
| 35 | + do_translate_w(cwd, L'\\'); |
| 36 | + |
| 37 | + // Convert the source path to a relative path |
| 38 | + wchar_t relSrcPath[MAX_PATH]; |
| 39 | + swprintf(relSrcPath, MAX_PATH, L"%c:%s", cwd[0], wSrcPath); |
| 40 | + |
| 41 | + BOOLEAN res = CreateSymbolicLinkW(wDstPath, relSrcPath, SYMBOLIC_LINK_FLAG_DIRECTORY | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE); |
| 42 | + return res != 0; |
| 43 | + } |
| 44 | + else |
| 45 | + { |
| 46 | + BOOLEAN res = CreateSymbolicLinkW(wDstPath, wSrcPath, SYMBOLIC_LINK_FLAG_DIRECTORY | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE); |
| 47 | + return res != 0; |
| 48 | + } |
| 49 | +#else |
| 50 | + int res = symlink(src, dst); |
| 51 | + return res == 0; |
| 52 | +#endif |
| 53 | +} |
| 54 | + |
| 55 | +int os_linkdir(lua_State* L) |
| 56 | +{ |
| 57 | + const char* src = luaL_checkstring(L, 1); |
| 58 | + const char* dst = luaL_checkstring(L, 2); |
| 59 | + |
| 60 | + int result = do_linkdir(L, src, dst); |
| 61 | + if (!result) |
| 62 | + { |
| 63 | + lua_pushnil(L); |
| 64 | + lua_pushfstring(L, "Unable to create link from '%s' to '%s'", src, dst); |
| 65 | + return 2; |
| 66 | + } |
| 67 | + |
| 68 | + lua_pushboolean(L, 1); |
| 69 | + return 1; |
| 70 | +} |
0 commit comments