config.go 9.8 KB

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