config.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package config
  2. import (
  3. "os"
  4. "path/filepath"
  5. "gopkg.in/yaml.v3"
  6. )
  7. const Name = "discordo"
  8. var Current = defConfig()
  9. type Config struct {
  10. // Mouse indicates whether the mouse is usable or not.
  11. Mouse bool `yaml:"mouse"`
  12. // MessagesLimit is the number of messages to be retrieved when a text-based channel is selected.
  13. MessagesLimit uint `yaml:"messages_limit"`
  14. // Timestamps indicates whether the message is to be prefixed with the timestamp or not.
  15. Timestamps bool `yaml:"timestamps"`
  16. // 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.
  17. Editor string `yaml:"editor"`
  18. Keys Keys `yaml:"keys"`
  19. Theme Theme `yaml:"theme"`
  20. }
  21. func defConfig() Config {
  22. return Config{
  23. Mouse: true,
  24. Timestamps: false,
  25. MessagesLimit: 50,
  26. Editor: "default",
  27. Keys: defKeys(),
  28. Theme: defTheme(),
  29. }
  30. }
  31. func Load() error {
  32. path, err := os.UserConfigDir()
  33. if err != nil {
  34. return err
  35. }
  36. // Create the configuration directory if it does not exist already.
  37. path = filepath.Join(path, Name)
  38. err = os.MkdirAll(path, os.ModePerm)
  39. if err != nil {
  40. return err
  41. }
  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 err
  48. }
  49. defer f.Close()
  50. err = yaml.NewEncoder(f).Encode(Current)
  51. if err != nil {
  52. return err
  53. }
  54. } else {
  55. f, err := os.Open(path)
  56. if err != nil {
  57. return err
  58. }
  59. defer f.Close()
  60. err = yaml.NewDecoder(f).Decode(&Current)
  61. if err != nil {
  62. return err
  63. }
  64. }
  65. return nil
  66. }