runtime.go 2.1 KB

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