gitivity/config.go

71 lines
1.7 KiB
Go
Raw Normal View History

2024-03-16 17:05:19 -05:00
package main
import (
"errors"
"github.com/yuin/gopher-lua"
)
// Server holds information about a Gitea server.
type Server struct {
servername string
url string
username string
token string
2024-03-16 17:05:19 -05:00
}
// Configuration holds data retrieved from a Lua script.
type Configuration struct {
servers map[string]*Server
2024-03-16 17:05:19 -05:00
}
// parseText parses a text value from the configuration file.
func getStringFromTable(L *lua.LState, lobj lua.LValue, key string, out *string) error {
lv := L.GetTable(lobj, lua.LString(key))
if text, ok := lv.(lua.LString); ok {
*out = string(text)
} else {
return errors.New("Text is not a string!")
}
return nil
}
// parseServerFromTable parses a Lua table into a Server structure.
func parseServerFromTable(L *lua.LState, table lua.LValue) (Server, error) {
server := Server{}
if err := getStringFromTable(L, table, "servername", &server.servername); err != nil {
return server, err
}
if err := getStringFromTable(L, table, "username", &server.username); err != nil {
return server, err
}
if err := getStringFromTable(L, table, "token", &server.token); err != nil {
return server, err
}
if err := getStringFromTable(L, table, "url", &server.url); err != nil {
return server, err
}
2024-03-16 17:05:19 -05:00
return server, nil
}
// Configuration.Parse parses a Lua configuration file into a Configuration struct.
func (config *Configuration) Parse(fname string) error {
config.servers = make(map[string]*Server)
2024-03-16 17:05:19 -05:00
L := lua.NewState()
defer L.Close()
L.DoFile(fname)
table := L.Get(-1)
for i := 1; i <= L.ObjLen(table); i++ {
lserver := L.GetTable(table, lua.LNumber(i))
if server, err := parseServerFromTable(L, lserver); err == nil {
config.servers[server.servername] = &server
2024-03-16 17:05:19 -05:00
} else {
return err
}
}
2024-03-16 17:05:19 -05:00
return nil
}