config.go 10 KB

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