shithub: lu9-p9

Download patch

ref: cc43a4edaba3e332a975ed4df82cf5e919cd0c39
parent: 5ec928da062ba2fe97c3f7f0e9aed7473bbfa90e
author: kvik <[email protected]>
date: Sun Apr 18 19:43:39 EDT 2021

fs: implement p9.access()

--- a/fs.c
+++ b/fs.c
@@ -356,3 +356,43 @@
 	filenew(L, fd[1]);
 	return 2;
 }
+
+static int
+accessmode(lua_State *L, const char *s)
+{
+	int i, n, mode;
+	char buf[64], *f[10], *p;
+	
+	snprint(buf, sizeof buf, "%s", s);
+	n = getfields(buf, f, sizeof f, 1, " \t\n");
+	mode = 0;
+	for(i = 0; p = f[i], i < n; i++){
+		if(strcmp(p, "exist") == 0 || strcmp(p, "exists") == 0)
+			mode |= AEXIST;
+		else if(strcmp(p, "r") == 0 || strcmp(p, "read") == 0)
+			mode |= AREAD;
+		else if(strcmp(p, "w") == 0 || strcmp(p, "write") == 0)
+			mode |= AWRITE;
+		else if(strcmp(p, "rw") == 0 || strcmp(p, "rdwr") == 0)
+			mode |= AREAD|AWRITE;
+		else if(strcmp(p, "x") == 0 || strcmp(p, "exec") == 0)
+			mode |= AEXEC;
+		else
+			return luaL_error(L, "unknown access flag '%s'", p);
+	}
+	return mode;
+}
+
+static int
+p9_access(lua_State *L)
+{
+	const char *path;
+	int mode;
+
+	path = luaL_checkstring(L, 1);
+	mode = accessmode(L, luaL_optstring(L, 2, "exists"));
+	lua_pushboolean(L, 
+		access(path, mode) == 0 ? 1 : 0
+	);
+	return 1;
+}
--- a/p9.c
+++ b/p9.c
@@ -156,6 +156,7 @@
 	{"file", p9_file},
 	{"pipe", p9_pipe},
 	{"remove", p9_remove},
+	{"access", p9_access},
 	
 	{"stat", p9_stat},
 	{"walk", p9_walk},
--- a/test.lua
+++ b/test.lua
@@ -99,6 +99,13 @@
 	b:seek(0)
 	assert(b:read() == buf)
 end
+
+-- access
+do
+	assert(p9.access("/dev/null"))
+	assert(p9.access("/dev/null", "read write"))
+	assert(p9.access("/bin/rc", "exec"))
+end
 	
 -- pipe
 do