From ef1ced4a04e764b13535f18e1bde0afdc011f61e Mon Sep 17 00:00:00 2001 From: sammyette <38820196+TorchedSammy@users.noreply.github.com> Date: Sun, 16 May 2021 17:13:28 -0400 Subject: [PATCH] refactor: make `hilbish` an already required module and add run function idk how to explain this man in code `hilbish` is now a module, which can also be required like others. but it is already a global export as the variable of the same name. also --- hilbish.go | 43 +++++++++++++++++++++++++++++++++++++++---- lua.go | 5 +++-- main.go | 9 --------- 3 files changed, 42 insertions(+), 15 deletions(-) diff --git a/hilbish.go b/hilbish.go index c3302f9..5125621 100644 --- a/hilbish.go +++ b/hilbish.go @@ -3,9 +3,44 @@ // go here. package main -type Hilbish struct { - Version string // Hilbish's version - User string // Name of the user - Hostname string +import ( + "os" + + "github.com/yuin/gopher-lua" + "mvdan.cc/sh/v3/interp" +) + +var exports = map[string]lua.LGFunction { + "run": run, +} + +func HilbishLoader(L *lua.LState) int { + mod := L.SetFuncs(L.NewTable(), exports) + + host, _ := os.Hostname() + + L.SetField(mod, "ver", lua.LString(version)) + L.SetField(mod, "user", lua.LString(curuser.Username)) + L.SetField(mod, "host", lua.LString(host)) + + L.Push(mod) + + return 1 +} + +// Runs a command +func run(L *lua.LState) int { + var exitcode uint8 = 0 + cmd := L.CheckString(1) + err := execCommand(cmd) + + if code, ok := interp.IsExitStatus(err); ok { + exitcode = code + } else if err != nil { + exitcode = 1 + } + + L.Push(lua.LNumber(exitcode)) + return 1 } diff --git a/lua.go b/lua.go index ffe263c..2fb1ef4 100644 --- a/lua.go +++ b/lua.go @@ -12,7 +12,6 @@ import ( "hilbish/golibs/fs" "github.com/yuin/gopher-lua" - "layeh.com/gopher-luar" ) var minimalconf = ` @@ -32,7 +31,9 @@ func LuaInit() { l.SetGlobal("appendPath", l.NewFunction(hshappendPath)) l.SetGlobal("exec", l.NewFunction(hshexec)) - l.SetGlobal("hilbish", luar.New(l, hilbish)) + // yes this is stupid, i know + l.PreloadModule("hilbish", HilbishLoader) + l.DoString("hilbish = require 'hilbish'") // Add fs module to Lua l.PreloadModule("fs", fs.Loader) diff --git a/main.go b/main.go index d96644d..c7d20d4 100644 --- a/main.go +++ b/main.go @@ -37,7 +37,6 @@ var ( interactive bool login bool // Are we the login shell? noexecute bool // Should we run Lua or only report syntax errors - hilbish *Hilbish // dont ask ) func main() { @@ -109,14 +108,6 @@ func main() { } } - host, _ := os.Hostname() - - hilbish = &Hilbish { - Version: version, - User: curuser.Username, - Hostname: host, - } - go HandleSignals() LuaInit() RunLogin()