runtime.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package settings
  2. import (
  3. "os"
  4. "path/filepath"
  5. "github.com/Jguer/go-alpm"
  6. "github.com/Morganamilo/go-pacmanconf"
  7. "github.com/leonelquinteros/gotext"
  8. "github.com/pkg/errors"
  9. )
  10. type TargetMode int
  11. // configFileName holds the name of the config file.
  12. const configFileName string = "config.json"
  13. // vcsFileName holds the name of the vcs file.
  14. const vcsFileName string = "vcs.json"
  15. const completionFileName string = "completion.cache"
  16. const (
  17. ModeAny TargetMode = iota
  18. ModeAUR
  19. ModeRepo
  20. )
  21. type Runtime struct {
  22. Mode TargetMode
  23. SaveConfig bool
  24. CompletionPath string
  25. ConfigPath string
  26. VCSPath string
  27. PacmanConf *pacmanconf.Config
  28. AlpmHandle *alpm.Handle
  29. }
  30. func MakeRuntime() (*Runtime, error) {
  31. cacheHome := ""
  32. configHome := ""
  33. runtime := &Runtime{
  34. Mode: ModeAny,
  35. SaveConfig: false,
  36. CompletionPath: "",
  37. }
  38. if configHome = os.Getenv("XDG_CONFIG_HOME"); configHome != "" {
  39. configHome = filepath.Join(configHome, "yay")
  40. } else if configHome = os.Getenv("HOME"); configHome != "" {
  41. configHome = filepath.Join(configHome, ".config/yay")
  42. } else {
  43. return nil, errors.New(gotext.Get("%s and %s unset", "XDG_CONFIG_HOME", "HOME"))
  44. }
  45. if err := initDir(configHome); err != nil {
  46. return nil, err
  47. }
  48. if cacheHome = os.Getenv("XDG_CACHE_HOME"); cacheHome != "" {
  49. cacheHome = filepath.Join(cacheHome, "yay")
  50. } else if cacheHome = os.Getenv("HOME"); cacheHome != "" {
  51. cacheHome = filepath.Join(cacheHome, ".cache/yay")
  52. } else {
  53. return nil, errors.New(gotext.Get("%s and %s unset", "XDG_CACHE_HOME", "HOME"))
  54. }
  55. if err := initDir(cacheHome); err != nil {
  56. return runtime, err
  57. }
  58. runtime.ConfigPath = filepath.Join(configHome, configFileName)
  59. runtime.VCSPath = filepath.Join(cacheHome, vcsFileName)
  60. runtime.CompletionPath = filepath.Join(cacheHome, completionFileName)
  61. return runtime, nil
  62. }
  63. func initDir(dir string) error {
  64. if _, err := os.Stat(dir); os.IsNotExist(err) {
  65. if err = os.MkdirAll(dir, 0755); err != nil {
  66. return errors.New(gotext.Get("failed to create config directory '%s': %s", dir, err))
  67. }
  68. } else if err != nil {
  69. return err
  70. }
  71. return nil
  72. }