config.go 1.6 KB

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