Radish alpha
H
rad:z3QDZAW2FAfuLvihrhiyDC9fAD8G9
HardenedBSD Package Manager
Radicle
Git
lua: add pkg.readdir
Baptiste Daroussin committed 4 years ago
commit ef8e71553deb048004d40b70806867d6fa05b26b
parent 3e41a0e
4 files changed +40 -0
modified libpkg/lua.c
@@ -34,6 +34,7 @@
#include <sys/mman.h>
#include <sys/wait.h>

+
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <spawn.h>
@@ -511,3 +512,39 @@ lua_override_ios(lua_State *L, bool sandboxed)
	lua_pushcfunction(L, lua_os_exit);
	lua_setfield(L, -2, "exit");
}
+

+
int
+
lua_readdir(lua_State *L)
+
{
+
	int n = lua_gettop(L);
+
	luaL_argcheck(L, n == 1, n > 1 ? 2 : n,
+
	    "pkg.readdir takes exactly one argument");
+
	const char *path = luaL_checkstring(L, 1);
+
	int fd = -1;
+

+
	if (*path == '/') {
+
		lua_getglobal(L, "rootfd");
+
		int rootfd = lua_tointeger(L, -1);
+
		fd = openat(rootfd, path +1, O_DIRECTORY);
+
	} else {
+
		fd = open(path, O_DIRECTORY);
+
	}
+
	if (fd == -1)
+
		return (luaL_fileresult(L, 0, path));
+

+
	DIR *dir = fdopendir(fd);
+
	if (!dir)
+
		return (luaL_fileresult(L, 0, path));
+
	lua_newtable(L);
+
	struct dirent *e;
+
	int i = 0;
+
	while ((e = readdir(dir))) {
+
		char *name = e->d_name;
+
		if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0)
+
			continue;
+
		lua_pushinteger(L, ++i);
+
		lua_pushstring(L, name);
+
		lua_settable(L, -3);
+
	}
+
	return 1;
+
}
modified libpkg/lua_scripts.c
@@ -86,6 +86,7 @@ pkg_lua_script_run(struct pkg * const pkg, pkg_lua_script type, bool upgrade)
				{ "filecmp", lua_pkg_filecmp },
				{ "copy", lua_pkg_copy },
				{ "stat", lua_stat },
+
				{ "readdir", lua_readdir },
				{ "exec", lua_exec },
				{ NULL, NULL },
			};
modified libpkg/private/lua.h
@@ -35,4 +35,5 @@ int lua_prefix_path(lua_State *L);
int lua_exec(lua_State *L);
void lua_override_ios(lua_State *L, bool);
int lua_stat(lua_State *L);
+
int lua_readdir(lua_State *L);
void lua_args_table(lua_State *L, char **argv, int argc);
modified libpkg/triggers.c
@@ -418,6 +418,7 @@ trigger_execute_lua(const char *script, bool sandbox, pkghash *args)
			{ "filecmp", lua_pkg_filecmp },
			{ "copy", lua_pkg_copy },
			{ "stat", lua_stat },
+
			{ "readdir", lua_readdir },
			{ "exec", lua_exec },
			{ NULL, NULL },
		};