From 86b8b0e8705d77ab0e428e713699bc264d11604c Mon Sep 17 00:00:00 2001 From: BanceDev Date: Tue, 3 Sep 2024 22:31:57 -0400 Subject: added cd to lua api --- src/lua_api.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) (limited to 'src/lua_api.c') diff --git a/src/lua_api.c b/src/lua_api.c index 4b5de86..7bac763 100644 --- a/src/lua_api.c +++ b/src/lua_api.c @@ -20,9 +20,11 @@ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #include #include #include +#include #include #include #include +#include #include // global for checking if debug_mode is toggled @@ -110,6 +112,48 @@ static int l_debug(lua_State *L) { return 0; } +static int l_cd(lua_State *L) { + bool rc; + uid_t uid = getuid(); + struct passwd *pw = getpwuid(uid); + if (!pw) { + perror("retrieve home dir"); + rc = false; + lua_pushboolean(L, rc); + return 1; + } + + const char *newdir = luaL_checkstring(L, 1); + if (newdir == NULL) { + if (chdir(pw->pw_dir) != 0) { + perror("lush: cd"); + } + } else { + char path[PATH_MAX]; + char extended_path[PATH_MAX]; + char *tilda = strchr(newdir, '~'); + if (tilda) { + strcpy(path, pw->pw_dir); + strcat(path, tilda + 1); + } else { + strcpy(path, newdir); + } + char *exp_path = realpath(path, extended_path); + if (!exp_path) { + perror("realpath"); + rc = false; + lua_pushboolean(L, rc); + return 1; + } + if (chdir(exp_path) != 0) { + perror("lush: cd"); + } + } + rc = true; + lua_pushboolean(L, rc); + return 1; +} + // -- register Lua functions -- void lua_register_api(lua_State *L) { -- cgit v1.2.3-59-g8ed1b