Hilbish/aliases.go

122 lines
2.2 KiB
Go
Raw Normal View History

package main
import (
"strings"
2021-12-20 02:37:44 +00:00
"sync"
2022-03-29 22:03:57 +00:00
"hilbish/util"
rt "github.com/arnodel/golua/runtime"
)
var aliases *aliasHandler
type aliasHandler struct {
aliases map[string]string
2021-12-20 02:37:44 +00:00
mu *sync.RWMutex
}
// initialize aliases map
func newAliases() *aliasHandler {
return &aliasHandler{
aliases: make(map[string]string),
2021-12-20 02:37:44 +00:00
mu: &sync.RWMutex{},
}
}
func (a *aliasHandler) Add(alias, cmd string) {
a.mu.Lock()
defer a.mu.Unlock()
2021-12-20 02:37:44 +00:00
a.aliases[alias] = cmd
}
func (a *aliasHandler) All() map[string]string {
return a.aliases
}
func (a *aliasHandler) Delete(alias string) {
a.mu.Lock()
defer a.mu.Unlock()
2021-12-20 02:37:44 +00:00
delete(a.aliases, alias)
}
func (a *aliasHandler) Resolve(cmdstr string) string {
a.mu.RLock()
defer a.mu.RUnlock()
2021-12-20 02:37:44 +00:00
args := strings.Split(cmdstr, " ")
for a.aliases[args[0]] != "" {
alias := a.aliases[args[0]]
cmdstr = alias + strings.TrimPrefix(cmdstr, args[0])
cmdArgs, _ := splitInput(cmdstr)
args = cmdArgs
if a.aliases[args[0]] == alias {
break
}
if a.aliases[args[0]] != "" {
continue
}
}
return cmdstr
}
// lua section
2022-03-30 00:16:03 +00:00
func (a *aliasHandler) Loader(rtm *rt.Runtime) *rt.Table {
// create a lua module with our functions
2022-03-29 22:03:57 +00:00
hshaliasesLua := map[string]util.LuaExport{
"add": util.LuaExport{a.luaAdd, 2, false},
"list": util.LuaExport{a.luaList, 0, false},
"del": util.LuaExport{a.luaDelete, 1, false},
}
2022-03-30 00:16:03 +00:00
2022-03-29 22:03:57 +00:00
mod := rt.NewTable()
util.SetExports(rtm, mod, hshaliasesLua)
return mod
}
2022-03-29 22:03:57 +00:00
func (a *aliasHandler) luaAdd(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.CheckNArgs(2); err != nil {
return nil, err
}
alias, err := c.StringArg(0)
if err != nil {
return nil, err
}
cmd, err := c.StringArg(1)
if err != nil {
return nil, err
}
a.Add(alias, cmd)
2022-03-29 22:03:57 +00:00
return c.Next(), nil
}
2022-03-29 22:03:57 +00:00
func (a *aliasHandler) luaList(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
aliasesList := rt.NewTable()
for k, v := range a.All() {
2022-03-29 22:03:57 +00:00
aliasesList.Set(rt.StringValue(k), rt.StringValue(v))
}
2022-03-29 22:03:57 +00:00
return c.PushingNext1(t.Runtime, rt.TableValue(aliasesList)), nil
}
2022-03-29 22:03:57 +00:00
func (a *aliasHandler) luaDelete(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
}
alias, err := c.StringArg(0)
if err != nil {
return nil, err
}
a.Delete(alias)
2022-03-29 22:03:57 +00:00
return c.Next(), nil
}