parse.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package config
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "path"
  7. "github.com/mitchellh/go-homedir"
  8. )
  9. var confFileName = "papero.toml"
  10. var ErrConfigNotFound = errors.New("unable to find configuration")
  11. var ErrFailedToParseConfig = errors.New("unable to cast into usable configuration")
  12. func Parse(filePath string) (*MemConfig, error) {
  13. fileConfig, err := parseFile(filePath)
  14. if err != nil {
  15. return nil, err
  16. }
  17. memConfig, castingErrs := parseConfig(fileConfig)
  18. if !castingErrs.Check() {
  19. return nil, ErrFailedToParseConfig
  20. }
  21. return memConfig, nil
  22. }
  23. // Find looks for the configuration file in the following order:
  24. // - $PWD/papero.toml
  25. // - ~/.config/papero/papero.toml
  26. // - ~/.papero.toml
  27. // - /etc/papero.toml
  28. // returns and error if no file has been found
  29. func Find() (string, error) {
  30. var paths []string
  31. // Try to append $PWD/papero.toml
  32. cwd, err := os.Getwd()
  33. if err == nil {
  34. paths = append(paths, path.Join(cwd, confFileName))
  35. }
  36. // Try to append ~/.config/papero/papero.toml and ~/.papero.toml
  37. home, err := homedir.Dir()
  38. if err == nil {
  39. paths = append(paths, path.Join(home, ".config", "papero", confFileName))
  40. paths = append(paths, path.Join(home, fmt.Sprintf(".%s", confFileName)))
  41. }
  42. // Append /etc/papero.toml
  43. paths = append(paths, path.Join("/etc", confFileName))
  44. for _, file := range paths {
  45. info, err := os.Stat(file)
  46. if err == nil && !info.IsDir() {
  47. return file, nil
  48. }
  49. }
  50. return "", ErrConfigNotFound
  51. }