config.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. func new() Config {
  21. return Config{
  22. Mouse: true,
  23. Timestamps: false,
  24. MessagesLimit: 50,
  25. Editor: "default",
  26. Keys: newKeys(),
  27. Theme: newTheme(),
  28. }
  29. }
  30. // 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.
  31. func Load() (*Config, error) {
  32. path, err := os.UserConfigDir()
  33. if err != nil {
  34. return nil, err
  35. }
  36. path = filepath.Join(path, Name)
  37. err = os.MkdirAll(path, os.ModePerm)
  38. if err != nil {
  39. return nil, err
  40. }
  41. c := new()
  42. path = filepath.Join(path, "config.yml")
  43. _, err = os.Stat(path)
  44. if os.IsNotExist(err) {
  45. f, err := os.Create(path)
  46. if err != nil {
  47. return nil, err
  48. }
  49. defer f.Close()
  50. err = yaml.NewEncoder(f).Encode(c)
  51. if err != nil {
  52. return nil, err
  53. }
  54. } else {
  55. f, err := os.Open(path)
  56. if err != nil {
  57. return nil, err
  58. }
  59. defer f.Close()
  60. err = yaml.NewDecoder(f).Decode(&c)
  61. if err != nil {
  62. return nil, err
  63. }
  64. }
  65. return &c, nil
  66. }