config.go 9.9 KB

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