mirror of
https://github.com/lunarmodules/luafilesystem.git
synced 2026-07-23 19:43:06 +00:00
Add a 'target' field for symlinkattributes.
It returns the resolved path of the symlink. Original version by Hisham <hisham@gobolinux.org>, modified to use a different strategy for sizing the readlink() buffer.
This commit is contained in:
49
src/lfs.c
49
src/lfs.c
@@ -849,11 +849,58 @@ static int file_info (lua_State *L) {
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Push the symlink target to the top of the stack.
|
||||
** Assumes the file name is at position 1 of the stack.
|
||||
** Returns 1 if successful (with the target on top of the stack),
|
||||
** 0 on failure (with stack unchanged, and errno set).
|
||||
*/
|
||||
static int push_link_target(lua_State *L) {
|
||||
#ifdef _WIN32
|
||||
errno = ENOSYS;
|
||||
return 0;
|
||||
#else
|
||||
const char *file = luaL_checkstring(L, 1);
|
||||
char *target = NULL;
|
||||
int tsize, size = 256; /* size = initial buffer capacity */
|
||||
while (1) {
|
||||
target = realloc(target, size);
|
||||
if (!target) /* failed to allocate */
|
||||
return 0;
|
||||
tsize = readlink(file, target, size);
|
||||
if (tsize < 0) { /* a readlink() error occurred */
|
||||
free(target);
|
||||
return 0;
|
||||
}
|
||||
if (tsize < size)
|
||||
break;
|
||||
/* possibly truncated readlink() result, double size and retry */
|
||||
size *= 2;
|
||||
}
|
||||
target[tsize] = '\0';
|
||||
lua_pushlstring(L, target, tsize);
|
||||
free(target);
|
||||
return 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
/*
|
||||
** Get symbolic link information using lstat.
|
||||
*/
|
||||
static int link_info (lua_State *L) {
|
||||
return _file_info_ (L, LSTAT_FUNC);
|
||||
int ret;
|
||||
if (lua_isstring (L, 2) && (strcmp(lua_tostring(L, 2), "target") == 0)) {
|
||||
int ok = push_link_target(L);
|
||||
return ok ? 1 : pusherror(L, "could not obtain link target");
|
||||
}
|
||||
ret = _file_info_ (L, LSTAT_FUNC);
|
||||
if (ret == 1 && lua_type(L, -1) == LUA_TTABLE) {
|
||||
int ok = push_link_target(L);
|
||||
if (ok) {
|
||||
lua_setfield(L, -2, "target");
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user