config.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. package settings
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "strings"
  12. "github.com/leonelquinteros/gotext"
  13. "github.com/pkg/errors"
  14. "github.com/Jguer/aur"
  15. "github.com/Jguer/votar/pkg/vote"
  16. "github.com/Jguer/yay/v11/pkg/metadata"
  17. "github.com/Jguer/yay/v11/pkg/settings/exe"
  18. "github.com/Jguer/yay/v11/pkg/settings/parser"
  19. "github.com/Jguer/yay/v11/pkg/text"
  20. "github.com/Jguer/yay/v11/pkg/vcs"
  21. )
  22. // HideMenus indicates if pacman's provider menus must be hidden.
  23. var HideMenus = false
  24. // NoConfirm indicates if user input should be skipped.
  25. var NoConfirm = false
  26. // Configuration stores yay's config.
  27. type Configuration struct {
  28. Runtime *Runtime `json:"-"`
  29. AURURL string `json:"aururl"`
  30. BuildDir string `json:"buildDir"`
  31. Editor string `json:"editor"`
  32. EditorFlags string `json:"editorflags"`
  33. MakepkgBin string `json:"makepkgbin"`
  34. MakepkgConf string `json:"makepkgconf"`
  35. PacmanBin string `json:"pacmanbin"`
  36. PacmanConf string `json:"pacmanconf"`
  37. ReDownload string `json:"redownload"`
  38. ReBuild string `json:"rebuild"`
  39. AnswerClean string `json:"answerclean"`
  40. AnswerDiff string `json:"answerdiff"`
  41. AnswerEdit string `json:"answeredit"`
  42. AnswerUpgrade string `json:"answerupgrade"`
  43. GitBin string `json:"gitbin"`
  44. GpgBin string `json:"gpgbin"`
  45. GpgFlags string `json:"gpgflags"`
  46. MFlags string `json:"mflags"`
  47. SortBy string `json:"sortby"`
  48. SearchBy string `json:"searchby"`
  49. GitFlags string `json:"gitflags"`
  50. RemoveMake string `json:"removemake"`
  51. SudoBin string `json:"sudobin"`
  52. SudoFlags string `json:"sudoflags"`
  53. Version string `json:"version"`
  54. RequestSplitN int `json:"requestsplitn"`
  55. CompletionInterval int `json:"completionrefreshtime"`
  56. MaxConcurrentDownloads int `json:"maxconcurrentdownloads"`
  57. BottomUp bool `json:"bottomup"`
  58. SudoLoop bool `json:"sudoloop"`
  59. TimeUpdate bool `json:"timeupdate"`
  60. Devel bool `json:"devel"`
  61. CleanAfter bool `json:"cleanAfter"`
  62. Provides bool `json:"provides"`
  63. PGPFetch bool `json:"pgpfetch"`
  64. UpgradeMenu bool `json:"upgrademenu"`
  65. CleanMenu bool `json:"cleanmenu"`
  66. DiffMenu bool `json:"diffmenu"`
  67. EditMenu bool `json:"editmenu"`
  68. CombinedUpgrade bool `json:"combinedupgrade"`
  69. UseAsk bool `json:"useask"`
  70. BatchInstall bool `json:"batchinstall"`
  71. SingleLineResults bool `json:"singlelineresults"`
  72. SeparateSources bool `json:"separatesources"`
  73. NewInstallEngine bool `json:"newinstallengine"`
  74. Debug bool `json:"debug"`
  75. }
  76. // SaveConfig writes yay config to file.
  77. func (c *Configuration) Save(configPath string) error {
  78. c.Version = c.Runtime.Version
  79. marshalledinfo, err := json.MarshalIndent(c, "", "\t")
  80. if err != nil {
  81. return err
  82. }
  83. // https://github.com/Jguer/yay/issues/1325
  84. marshalledinfo = append(marshalledinfo, '\n')
  85. // https://github.com/Jguer/yay/issues/1399
  86. if _, err = os.Stat(filepath.Dir(configPath)); os.IsNotExist(err) && err != nil {
  87. if mkErr := os.MkdirAll(filepath.Dir(configPath), 0o755); mkErr != nil {
  88. return mkErr
  89. }
  90. }
  91. in, err := os.OpenFile(configPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
  92. if err != nil {
  93. return err
  94. }
  95. defer in.Close()
  96. if _, err = in.Write(marshalledinfo); err != nil {
  97. return err
  98. }
  99. return in.Sync()
  100. }
  101. func (c *Configuration) expandEnv() {
  102. c.AURURL = os.ExpandEnv(c.AURURL)
  103. c.BuildDir = os.ExpandEnv(c.BuildDir)
  104. c.Editor = os.ExpandEnv(c.Editor)
  105. c.EditorFlags = os.ExpandEnv(c.EditorFlags)
  106. c.MakepkgBin = os.ExpandEnv(c.MakepkgBin)
  107. c.MakepkgConf = os.ExpandEnv(c.MakepkgConf)
  108. c.PacmanBin = os.ExpandEnv(c.PacmanBin)
  109. c.PacmanConf = os.ExpandEnv(c.PacmanConf)
  110. c.GpgFlags = os.ExpandEnv(c.GpgFlags)
  111. c.MFlags = os.ExpandEnv(c.MFlags)
  112. c.GitFlags = os.ExpandEnv(c.GitFlags)
  113. c.SortBy = os.ExpandEnv(c.SortBy)
  114. c.SearchBy = os.ExpandEnv(c.SearchBy)
  115. c.GitBin = os.ExpandEnv(c.GitBin)
  116. c.GpgBin = os.ExpandEnv(c.GpgBin)
  117. c.SudoBin = os.ExpandEnv(c.SudoBin)
  118. c.SudoFlags = os.ExpandEnv(c.SudoFlags)
  119. c.ReDownload = os.ExpandEnv(c.ReDownload)
  120. c.ReBuild = os.ExpandEnv(c.ReBuild)
  121. c.AnswerClean = os.ExpandEnv(c.AnswerClean)
  122. c.AnswerDiff = os.ExpandEnv(c.AnswerDiff)
  123. c.AnswerEdit = os.ExpandEnv(c.AnswerEdit)
  124. c.AnswerUpgrade = os.ExpandEnv(c.AnswerUpgrade)
  125. c.RemoveMake = os.ExpandEnv(c.RemoveMake)
  126. }
  127. func (c *Configuration) String() string {
  128. var buf bytes.Buffer
  129. enc := json.NewEncoder(&buf)
  130. enc.SetIndent("", "\t")
  131. if err := enc.Encode(c); err != nil {
  132. fmt.Fprintln(os.Stderr, err)
  133. }
  134. return buf.String()
  135. }
  136. // check privilege elevator exists otherwise try to find another one.
  137. func (c *Configuration) setPrivilegeElevator() error {
  138. if auth := os.Getenv("PACMAN_AUTH"); auth != "" {
  139. c.SudoBin = auth
  140. if auth != "sudo" {
  141. c.SudoFlags = ""
  142. c.SudoLoop = false
  143. }
  144. }
  145. for _, bin := range [...]string{c.SudoBin, "sudo"} {
  146. if _, err := exec.LookPath(bin); err == nil {
  147. c.SudoBin = bin
  148. return nil // wrapper or sudo command existing. Retrocompatiblity
  149. }
  150. }
  151. c.SudoFlags = ""
  152. c.SudoLoop = false
  153. for _, bin := range [...]string{"doas", "pkexec", "su"} {
  154. if _, err := exec.LookPath(bin); err == nil {
  155. c.SudoBin = bin
  156. return nil // command existing
  157. }
  158. }
  159. return &ErrPrivilegeElevatorNotFound{confValue: c.SudoBin}
  160. }
  161. func DefaultConfig(version string) *Configuration {
  162. return &Configuration{
  163. AURURL: "https://aur.archlinux.org",
  164. BuildDir: os.ExpandEnv("$HOME/.cache/yay"),
  165. CleanAfter: false,
  166. Editor: "",
  167. EditorFlags: "",
  168. Devel: false,
  169. MakepkgBin: "makepkg",
  170. MakepkgConf: "",
  171. PacmanBin: "pacman",
  172. PGPFetch: true,
  173. PacmanConf: "/etc/pacman.conf",
  174. GpgFlags: "",
  175. MFlags: "",
  176. GitFlags: "",
  177. BottomUp: true,
  178. CompletionInterval: 7,
  179. MaxConcurrentDownloads: 0,
  180. SortBy: "votes",
  181. SearchBy: "name-desc",
  182. SudoLoop: false,
  183. GitBin: "git",
  184. GpgBin: "gpg",
  185. SudoBin: "sudo",
  186. SudoFlags: "",
  187. TimeUpdate: false,
  188. RequestSplitN: 150,
  189. ReDownload: "no",
  190. ReBuild: "no",
  191. BatchInstall: false,
  192. AnswerClean: "",
  193. AnswerDiff: "",
  194. AnswerEdit: "",
  195. AnswerUpgrade: "",
  196. RemoveMake: "ask",
  197. Provides: false,
  198. UpgradeMenu: true,
  199. CleanMenu: true,
  200. DiffMenu: true,
  201. EditMenu: false,
  202. UseAsk: false,
  203. CombinedUpgrade: false,
  204. SeparateSources: true,
  205. NewInstallEngine: false,
  206. Version: version,
  207. Debug: false,
  208. }
  209. }
  210. func NewConfig(version string) (*Configuration, error) {
  211. newConfig := DefaultConfig(version)
  212. cacheHome, errCache := getCacheHome()
  213. if errCache != nil {
  214. text.Errorln(errCache)
  215. }
  216. newConfig.BuildDir = cacheHome
  217. configPath := getConfigPath()
  218. newConfig.load(configPath)
  219. if aurdest := os.Getenv("AURDEST"); aurdest != "" {
  220. newConfig.BuildDir = aurdest
  221. }
  222. newConfig.expandEnv()
  223. if newConfig.BuildDir != systemdCache {
  224. errBuildDir := initDir(newConfig.BuildDir)
  225. if errBuildDir != nil {
  226. return nil, errBuildDir
  227. }
  228. }
  229. if errPE := newConfig.setPrivilegeElevator(); errPE != nil {
  230. return nil, errPE
  231. }
  232. userAgent := fmt.Sprintf("Yay/%s", version)
  233. voteClient, errVote := vote.NewClient(vote.WithUserAgent(userAgent))
  234. if errVote != nil {
  235. return nil, errVote
  236. }
  237. voteClient.SetCredentials(
  238. os.Getenv("AUR_USERNAME"),
  239. os.Getenv("AUR_PASSWORD"))
  240. newConfig.Runtime = &Runtime{
  241. ConfigPath: configPath,
  242. Version: version,
  243. Mode: parser.ModeAny,
  244. SaveConfig: false,
  245. CompletionPath: filepath.Join(cacheHome, completionFileName),
  246. CmdBuilder: newConfig.CmdBuilder(nil),
  247. PacmanConf: nil,
  248. VCSStore: nil,
  249. HTTPClient: &http.Client{},
  250. AURClient: nil,
  251. VoteClient: voteClient,
  252. QueryBuilder: nil,
  253. }
  254. var errAURCache error
  255. newConfig.Runtime.AURCache, errAURCache = metadata.NewAURCache(filepath.Join(newConfig.BuildDir, "aur.json"))
  256. if errAURCache != nil {
  257. return nil, errors.Wrap(errAURCache, gotext.Get("failed to retrieve aur Cache"))
  258. }
  259. var errAUR error
  260. newConfig.Runtime.AURClient, errAUR = aur.NewClient(aur.WithHTTPClient(newConfig.Runtime.HTTPClient),
  261. aur.WithRequestEditorFn(func(ctx context.Context, req *http.Request) error {
  262. req.Header.Set("User-Agent", userAgent)
  263. return nil
  264. }))
  265. if errAUR != nil {
  266. return nil, errAUR
  267. }
  268. newConfig.Runtime.VCSStore = vcs.NewInfoStore(
  269. filepath.Join(cacheHome, vcsFileName), newConfig.Runtime.CmdBuilder)
  270. err := newConfig.Runtime.VCSStore.Load()
  271. return newConfig, err
  272. }
  273. func (c *Configuration) load(configPath string) {
  274. cfile, err := os.Open(configPath)
  275. if !os.IsNotExist(err) && err != nil {
  276. fmt.Fprintln(os.Stderr,
  277. gotext.Get("failed to open config file '%s': %s", configPath, err))
  278. return
  279. }
  280. defer cfile.Close()
  281. if !os.IsNotExist(err) {
  282. decoder := json.NewDecoder(cfile)
  283. if err = decoder.Decode(c); err != nil {
  284. fmt.Fprintln(os.Stderr,
  285. gotext.Get("failed to read config file '%s': %s", configPath, err))
  286. }
  287. }
  288. }
  289. func (c *Configuration) CmdBuilder(runner exe.Runner) exe.ICmdBuilder {
  290. if runner == nil {
  291. runner = &exe.OSRunner{}
  292. }
  293. return &exe.CmdBuilder{
  294. GitBin: c.GitBin,
  295. GitFlags: strings.Fields(c.GitFlags),
  296. MakepkgFlags: strings.Fields(c.MFlags),
  297. MakepkgConfPath: c.MakepkgConf,
  298. MakepkgBin: c.MakepkgBin,
  299. SudoBin: c.SudoBin,
  300. SudoFlags: strings.Fields(c.SudoFlags),
  301. SudoLoopEnabled: c.SudoLoop,
  302. PacmanBin: c.PacmanBin,
  303. PacmanConfigPath: c.PacmanConf,
  304. PacmanDBPath: "",
  305. Runner: runner,
  306. }
  307. }