runtime.go 2.0 KB

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