config.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package config
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/BurntSushi/toml"
  6. "os"
  7. )
  8. type Config struct {
  9. Context int `toml:"context"`
  10. Timeout int `toml:"timeout"`
  11. Feeds feeds `toml:"feeds"`
  12. Algos algos `toml:"algos"`
  13. MediaHook []string `toml:"media_hook"`
  14. }
  15. type feeds = map[string][]string
  16. type algos = map[string]struct {
  17. Server string `toml:"server"`
  18. Query string `toml:"query"`
  19. }
  20. func Parse() (*Config, error) {
  21. /* Default values */
  22. config := &Config{
  23. Context: 5,
  24. Timeout: 10,
  25. Feeds: feeds{},
  26. Algos: algos{},
  27. MediaHook: []string{"xdg-open", "%u"},
  28. }
  29. location := location()
  30. if location == "" {
  31. return config, nil
  32. }
  33. metadata, err := toml.DecodeFile(location, config)
  34. if errors.Is(err, os.ErrNotExist) {
  35. return config, nil
  36. }
  37. if err != nil {
  38. return nil, err
  39. }
  40. if undecoded := metadata.Undecoded(); len(undecoded) != 0 {
  41. return nil, fmt.Errorf("config file %s contained unrecognized keys: %v", location, undecoded)
  42. }
  43. return config, nil
  44. }
  45. func location() string {
  46. if xdg := os.Getenv("XDG_CONFIG_HOME"); xdg != "" {
  47. return xdg + "/servitor/config.toml"
  48. }
  49. if home := os.Getenv("HOME"); home != "" {
  50. return home + "/.config/servitor/config.toml"
  51. }
  52. return ""
  53. }