Commit 58389d05 authored by Michal 'vorner' Vaner's avatar Michal 'vorner' Vaner

lua: stat returns the permissions as well

parent eab77eaf
......@@ -463,6 +463,45 @@ static int lua_ls(lua_State *L) {
return 1;
}
struct perm_def {
mode_t mask;
size_t pos;
char letter;
};
/*
* Note that some of these are on the same position. They are
* ordered so that the last matching wins, producing the desired
* result.
*/
static const struct perm_def perm_defs[] = {
{ S_IRUSR, 0, 'r' },
{ S_IWUSR, 1, 'w' },
{ S_IXUSR, 2, 'x' },
{ S_IRGRP, 3, 'r' },
{ S_IWGRP, 4, 'w' },
{ S_IXGRP, 5, 'x' },
{ S_IROTH, 6, 'r' },
{ S_IWOTH, 7, 'w' },
{ S_IXOTH, 8, 'x' },
{ S_ISVTX, 8, 't' },
{ S_ISVTX | S_IXOTH, 8, 'T' },
{ S_ISGID, 5, 'S' },
{ S_ISGID | S_IXGRP, 5, 's' },
{ S_ISUID, 2, 'S' },
{ S_ISUID | S_IXUSR, 2, 's' }
};
static const char *perm2str(struct stat *buf) {
static char perm[9];
memset(perm, '-', sizeof perm);
for (size_t i = 0; i < sizeof perm_defs / sizeof *perm_defs; i ++) {
if ((buf->st_mode & perm_defs[i].mask) == perm_defs[i].mask) // All the bits are set according to the mask
perm[perm_defs[i].pos] = perm_defs[i].letter;
}
return perm;
}
static int lua_stat(lua_State *L) {
const char *fname = luaL_checkstring(L, 1);
struct stat buf;
......@@ -475,7 +514,8 @@ static int lua_stat(lua_State *L) {
return luaL_error(L, "Failed to stat '%s': %s", fname, strerror(errno));
}
lua_pushstring(L, stat2str(&buf));
return 1;
lua_pushstring(L, perm2str(&buf));
return 2;
}
struct injected_func {
......
......@@ -113,9 +113,10 @@ ls(directory)::
?;; Failed to determine the type
stat(path)::
Statistics about the given file. It currently returns only the type
of file see the types of `ls`). If it doesn't exist, it returns
nothing.
Statistics about the given file. If the file does not exist, it
returns nothing. Otherwise, the file type is returned (see the types
of `ls`). The second result is the permissions of the file, in the
imitation of shell's `ls -l`, like `rwxr-x---`.
Journal manipulation
--------------------
......
......@@ -45,7 +45,10 @@ function test_fsutils()
mkdir(dir .. "/d1")
assert_table_equal({["d1"] = "d"}, ls(dir))
-- Exists and is a directory
assert_equal("d", stat(dir .. "/d1"))
events_wait(run_command(function () end, nil, nil, -1, -1, "/bin/chmod", "0750", dir .. "/d1"))
local stat_type, stat_perm = stat(dir .. "/d1")
assert_equal("d", stat_type)
assert_equal("rwxr-x---", stat_perm)
-- Doesn't exist
assert_table_equal({}, {stat(dir .. "/d2")})
-- Parent directory doesn't exist
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment