config.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package config
  2. import (
  3. "errors"
  4. "os"
  5. "path/filepath"
  6. "gopkg.in/yaml.v3"
  7. )
  8. const Name = "discordo"
  9. var Current = defConfig()
  10. type Config struct {
  11. // Mouse indicates whether the mouse is usable or not.
  12. Mouse bool `yaml:"mouse"`
  13. // MessagesLimit is the number of messages to fetch when a text-based channel is selected.
  14. MessagesLimit uint `yaml:"messages_limit"`
  15. // Timestamps indicates whether to draw the timestamp in front of the message or not.
  16. Timestamps bool `yaml:"timestamps"`
  17. // Editor is the program to open when the `LaunchEditor` key is pressed. If the value of the field is "default", the `$EDITOR` environment variable is used instead.
  18. Editor string `yaml:"editor"`
  19. Keys Keys `yaml:"keys"`
  20. Theme Theme `yaml:"theme"`
  21. }
  22. func defConfig() Config {
  23. return Config{
  24. Mouse: true,
  25. Timestamps: false,
  26. MessagesLimit: 50,
  27. Editor: "default",
  28. Keys: defKeys(),
  29. Theme: defTheme(),
  30. }
  31. }
  32. func getPath(optionalPath string) (string, error) {
  33. // Trigger an error if config flag used but is empty.
  34. if optionalPath == "" {
  35. return "", errors.New("Optional path cannot be empty.")
  36. }
  37. // Use the path provided by flags.
  38. if optionalPath != "none" {
  39. return optionalPath, nil
  40. }
  41. // Use the default for the OS.
  42. path, err := os.UserConfigDir()
  43. if err != nil {
  44. return "", err
  45. }
  46. path = filepath.Join(path, Name)
  47. if err != nil {
  48. return "", err
  49. }
  50. path = filepath.Join(path, "config.yml")
  51. if err != nil {
  52. return "", err
  53. }
  54. return path, nil
  55. }
  56. func Load(optionalPath string) error {
  57. path, err := getPath(optionalPath)
  58. if err != nil {
  59. return err
  60. }
  61. // Split the directory from the configuration file.
  62. dir, file := filepath.Split(path)
  63. // Create the configuration directory if it does not exist already.
  64. err = os.MkdirAll(dir, os.ModePerm)
  65. if err != nil {
  66. return err
  67. }
  68. path = filepath.Join(dir, file)
  69. _, err = os.Stat(path)
  70. if os.IsNotExist(err) {
  71. f, err := os.Create(path)
  72. if err != nil {
  73. return err
  74. }
  75. defer f.Close()
  76. err = yaml.NewEncoder(f).Encode(Current)
  77. if err != nil {
  78. return err
  79. }
  80. } else {
  81. f, err := os.Open(path)
  82. if err != nil {
  83. return err
  84. }
  85. defer f.Close()
  86. err = yaml.NewDecoder(f).Decode(&Current)
  87. if err != nil {
  88. return err
  89. }
  90. }
  91. return nil
  92. }