config.go 2.2 KB

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