config.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package config
  2. import (
  3. _ "embed"
  4. "fmt"
  5. "log/slog"
  6. "os"
  7. "path/filepath"
  8. "github.com/BurntSushi/toml"
  9. "github.com/ayn2op/discordo/internal/consts"
  10. "github.com/diamondburned/arikawa/v3/discord"
  11. )
  12. const fileName = "config.toml"
  13. type (
  14. Timestamps struct {
  15. Enabled bool `toml:"enabled"`
  16. Format string `toml:"format"`
  17. }
  18. Identify struct {
  19. Status discord.Status `toml:"status"`
  20. }
  21. Notifications struct {
  22. Enabled bool `toml:"enabled"`
  23. Duration int `toml:"duration"`
  24. Sound Sound `toml:"sound"`
  25. }
  26. Sound struct {
  27. Enabled bool `toml:"enabled"`
  28. OnlyOnPing bool `toml:"only_on_ping"`
  29. }
  30. Config struct {
  31. Mouse bool `toml:"mouse"`
  32. Editor string `toml:"editor"`
  33. Markdown bool `toml:"markdown"`
  34. HideBlockedUsers bool `toml:"hide_blocked_users"`
  35. ShowAttachmentLinks bool `toml:"show_attachment_links"`
  36. // Use 0 to disable
  37. AutocompleteLimit uint8 `toml:"autocomplete_limit"`
  38. MessagesLimit uint8 `toml:"messages_limit"`
  39. Timestamps Timestamps `toml:"timestamps"`
  40. Identify Identify `toml:"identify"`
  41. Notifications Notifications `toml:"notifications"`
  42. Keys Keys `toml:"keys"`
  43. Theme Theme `toml:"theme"`
  44. }
  45. )
  46. //go:embed config.toml
  47. var defaultCfg []byte
  48. func DefaultPath() string {
  49. path, err := os.UserConfigDir()
  50. if err != nil {
  51. slog.Info(
  52. "user configuration directory path cannot be determined; falling back to the current directory path",
  53. )
  54. path = "."
  55. }
  56. return filepath.Join(path, consts.Name, fileName)
  57. }
  58. // Load reads the configuration file and parses it.
  59. func Load(path string) (*Config, error) {
  60. file, err := os.Open(path)
  61. var cfg *Config
  62. if err := toml.Unmarshal(defaultCfg, &cfg); err != nil {
  63. return nil, fmt.Errorf("failed to unmarshal default config: %w", err)
  64. }
  65. if os.IsNotExist(err) {
  66. slog.Info(
  67. "the configuration file does not exist, falling back to the default configuration",
  68. "path",
  69. path,
  70. "err",
  71. err,
  72. )
  73. } else {
  74. if err != nil {
  75. return nil, fmt.Errorf("failed to open config file: %w", err)
  76. }
  77. defer file.Close()
  78. if _, err := toml.NewDecoder(file).Decode(&cfg); err != nil {
  79. return nil, fmt.Errorf("failed to decode config: %w", err)
  80. }
  81. }
  82. if cfg.Editor == "default" {
  83. cfg.Editor = os.Getenv("EDITOR")
  84. }
  85. return cfg, nil
  86. }