parse.go 1.5 KB

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