config.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. Notifications struct {
  19. Enabled bool `toml:"enabled"`
  20. Duration int `toml:"duration"`
  21. Sound Sound `toml:"sound"`
  22. }
  23. Sound struct {
  24. Enabled bool `toml:"enabled"`
  25. OnlyOnPing bool `toml:"only_on_ping"`
  26. }
  27. Config struct {
  28. AutoFocus bool `toml:"auto_focus"`
  29. Mouse bool `toml:"mouse"`
  30. Editor string `toml:"editor"`
  31. Status discord.Status `toml:"status"`
  32. Markdown bool `toml:"markdown"`
  33. HideBlockedUsers bool `toml:"hide_blocked_users"`
  34. ShowAttachmentLinks bool `toml:"show_attachment_links"`
  35. // Use 0 to disable
  36. AutocompleteLimit uint8 `toml:"autocomplete_limit"`
  37. MessagesLimit uint8 `toml:"messages_limit"`
  38. Timestamps Timestamps `toml:"timestamps"`
  39. Notifications Notifications `toml:"notifications"`
  40. Keys Keys `toml:"keys"`
  41. Theme Theme `toml:"theme"`
  42. }
  43. )
  44. //go:embed config.toml
  45. var defaultCfg []byte
  46. func DefaultPath() string {
  47. path, err := os.UserConfigDir()
  48. if err != nil {
  49. slog.Info(
  50. "user config dir cannot be determined; falling back to the current dir",
  51. "err", err,
  52. )
  53. path = "."
  54. }
  55. return filepath.Join(path, consts.Name, fileName)
  56. }
  57. // Load reads the configuration file and parses it.
  58. func Load(path string) (*Config, error) {
  59. var cfg Config
  60. if err := toml.Unmarshal(defaultCfg, &cfg); err != nil {
  61. return nil, fmt.Errorf("failed to unmarshal default config: %w", err)
  62. }
  63. file, err := os.Open(path)
  64. if os.IsNotExist(err) {
  65. slog.Info(
  66. "config file does not exist, falling back to the default config",
  67. "path",
  68. path,
  69. "err",
  70. err,
  71. )
  72. } else {
  73. if err != nil {
  74. return nil, fmt.Errorf("failed to open config file: %w", err)
  75. }
  76. defer file.Close()
  77. if _, err := toml.NewDecoder(file).Decode(&cfg); err != nil {
  78. return nil, fmt.Errorf("failed to decode config: %w", err)
  79. }
  80. }
  81. applyDefaults(&cfg)
  82. return &cfg, nil
  83. }
  84. func applyDefaults(cfg *Config) {
  85. if cfg.Editor == "default" {
  86. cfg.Editor = os.Getenv("EDITOR")
  87. }
  88. if cfg.Status == "default" {
  89. cfg.Status = discord.UnknownStatus
  90. }
  91. }