config.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package config
  2. import (
  3. _ "embed"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. lua "github.com/yuin/gopher-lua"
  8. )
  9. //go:embed config.lua
  10. var LuaConfig []byte
  11. // Config initializes a new Lua state, loads a configuration file, and defines essential micellaneous fields.
  12. type Config struct {
  13. // Path is the path of the configuration file. Its value is the configuration directory until Load() is called.
  14. Path string
  15. State *lua.LState
  16. }
  17. func NewConfig(path string) *Config {
  18. return &Config{
  19. Path: path,
  20. State: lua.NewState(),
  21. }
  22. }
  23. func (c *Config) Load() error {
  24. // Create directories that do not exist and are mentioned in the path recursively.
  25. err := os.MkdirAll(c.Path, os.ModePerm)
  26. if err != nil {
  27. return err
  28. }
  29. c.Path = filepath.Join(c.Path, "config.lua")
  30. // Open the existing configuration file with read-only flag.
  31. f, err := os.Open(c.Path)
  32. // If the configuration file does not exist, create a new configuration file with the read-write flag.
  33. if os.IsNotExist(err) {
  34. f, err = os.Create(c.Path)
  35. if err != nil {
  36. return err
  37. }
  38. defer f.Close()
  39. _, err = f.Write(LuaConfig)
  40. if err != nil {
  41. return err
  42. }
  43. return f.Sync()
  44. }
  45. if err != nil {
  46. return err
  47. }
  48. defer f.Close()
  49. b, err := io.ReadAll(f)
  50. if err != nil {
  51. return err
  52. }
  53. LuaConfig = b
  54. return nil
  55. }
  56. func (c *Config) KeyLua(s *lua.LState) int {
  57. keyTable := s.NewTable()
  58. keyTable.RawSetString("name", s.Get(1))
  59. keyTable.RawSetString("description", s.Get(2))
  60. keyTable.RawSetString("action", s.Get(3))
  61. s.Push(keyTable) // Push the result
  62. return 1 // Number of results
  63. }