config.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package config
  2. import (
  3. "os"
  4. "path/filepath"
  5. "gopkg.in/yaml.v3"
  6. )
  7. const Name = "discordo"
  8. type Config struct {
  9. // Mouse indicates whether the mouse is usable or not.
  10. Mouse bool `yaml:"mouse"`
  11. // MessagesLimit is the number of messages to be retrieved when a text-based channel is selected.
  12. MessagesLimit uint `yaml:"messages_limit"`
  13. // Timestamps indicates whether the message is to be prefixed with the timestamp or not.
  14. Timestamps bool `yaml:"timestamps"`
  15. // Editor is the editor program to open when the `LaunchEditor` key is pressed. If the value of the field is "default", the `$EDITOR` environment variable is used instead.
  16. Editor string `yaml:"editor"`
  17. Keys Keys `yaml:"keys"`
  18. Theme Theme `yaml:"theme"`
  19. }
  20. // Load reads the configuration file and decodes the configuration file or creates a new one if it does not exist already and writes the default configuration to the newly-created configuration file.
  21. func Load() (*Config, error) {
  22. path, err := os.UserConfigDir()
  23. if err != nil {
  24. return nil, err
  25. }
  26. path = filepath.Join(path, Name)
  27. err = os.MkdirAll(path, os.ModePerm)
  28. if err != nil {
  29. return nil, err
  30. }
  31. c := Config{
  32. Mouse: true,
  33. Timestamps: false,
  34. MessagesLimit: 50,
  35. Editor: "default",
  36. Keys: newKeys(),
  37. Theme: newTheme(),
  38. }
  39. path = filepath.Join(path, "config.yml")
  40. _, err = os.Stat(path)
  41. if os.IsNotExist(err) {
  42. f, err := os.Create(path)
  43. if err != nil {
  44. return nil, err
  45. }
  46. defer f.Close()
  47. err = yaml.NewEncoder(f).Encode(c)
  48. if err != nil {
  49. return nil, err
  50. }
  51. } else {
  52. f, err := os.Open(path)
  53. if err != nil {
  54. return nil, err
  55. }
  56. defer f.Close()
  57. err = yaml.NewDecoder(f).Decode(&c)
  58. if err != nil {
  59. return nil, err
  60. }
  61. }
  62. return &c, nil
  63. }