dirs.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package settings
  2. import (
  3. "os"
  4. "path/filepath"
  5. "github.com/leonelquinteros/gotext"
  6. "github.com/pkg/errors"
  7. )
  8. // configFileName holds the name of the config file.
  9. const configFileName string = "config.json"
  10. // vcsFileName holds the name of the vcs file.
  11. const vcsFileName string = "vcs.json"
  12. const completionFileName string = "completion.cache"
  13. func getConfigPath() string {
  14. if configHome := os.Getenv("XDG_CONFIG_HOME"); configHome != "" {
  15. if err := initDir(configHome); err == nil {
  16. return filepath.Join(configHome, "yay", configFileName)
  17. }
  18. }
  19. if configHome := os.Getenv("HOME"); configHome != "" {
  20. if err := initDir(configHome); err == nil {
  21. return filepath.Join(configHome, ".config", "yay", configFileName)
  22. }
  23. }
  24. return ""
  25. }
  26. func getCacheHome() string {
  27. uid := os.Geteuid()
  28. if cacheHome := os.Getenv("XDG_CACHE_HOME"); cacheHome != "" && uid != 0 {
  29. if err := initDir(cacheHome); err == nil {
  30. return filepath.Join(cacheHome, "yay")
  31. }
  32. }
  33. if cacheHome := os.Getenv("HOME"); cacheHome != "" && uid != 0 {
  34. if err := initDir(cacheHome); err == nil {
  35. return filepath.Join(cacheHome, ".cache", "yay")
  36. }
  37. }
  38. return os.TempDir()
  39. }
  40. func initDir(dir string) error {
  41. if _, err := os.Stat(dir); os.IsNotExist(err) {
  42. if err = os.MkdirAll(dir, 0o755); err != nil {
  43. return errors.New(gotext.Get("failed to create config directory '%s': %s", dir, err))
  44. }
  45. } else if err != nil {
  46. return err
  47. }
  48. return nil
  49. }