config.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. }
  20. Notifications struct {
  21. Enabled bool `toml:"enabled"`
  22. Duration int `toml:"duration"`
  23. Sound Sound `toml:"sound"`
  24. }
  25. Sound struct {
  26. Enabled bool `toml:"enabled"`
  27. OnlyOnPing bool `toml:"only_on_ping"`
  28. }
  29. Config struct {
  30. Mouse bool `toml:"mouse"`
  31. Editor string `toml:"editor"`
  32. Status discord.Status `toml:"status"`
  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 config dir cannot be determined; falling back to the current dir",
  53. "err", err,
  54. )
  55. path = "."
  56. }
  57. return filepath.Join(path, consts.Name, fileName)
  58. }
  59. // Load reads the configuration file and parses it.
  60. func Load(path string) (*Config, error) {
  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. file, err := os.Open(path)
  66. if os.IsNotExist(err) {
  67. slog.Info(
  68. "config file does not exist, falling back to the default config",
  69. "path",
  70. path,
  71. "err",
  72. err,
  73. )
  74. } else {
  75. if err != nil {
  76. return nil, fmt.Errorf("failed to open config file: %w", err)
  77. }
  78. defer file.Close()
  79. if _, err := toml.NewDecoder(file).Decode(&cfg); err != nil {
  80. return nil, fmt.Errorf("failed to decode config: %w", err)
  81. }
  82. }
  83. // set defaults
  84. if cfg.Editor == "default" {
  85. cfg.Editor = os.Getenv("EDITOR")
  86. }
  87. if cfg.Status == "default" {
  88. cfg.Status = ""
  89. }
  90. return &cfg, nil
  91. }