config.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. AURRPCURL string `json:"aurrpcurl"`
  28. BuildDir string `json:"buildDir"`
  29. Editor string `json:"editor"`
  30. EditorFlags string `json:"editorflags"`
  31. MakepkgBin string `json:"makepkgbin"`
  32. MakepkgConf string `json:"makepkgconf"`
  33. PacmanBin string `json:"pacmanbin"`
  34. PacmanConf string `json:"pacmanconf"`
  35. ReDownload string `json:"redownload"`
  36. ReBuild string `json:"rebuild"`
  37. AnswerClean string `json:"answerclean"`
  38. AnswerDiff string `json:"answerdiff"`
  39. AnswerEdit string `json:"answeredit"`
  40. AnswerUpgrade string `json:"answerupgrade"`
  41. GitBin string `json:"gitbin"`
  42. GpgBin string `json:"gpgbin"`
  43. GpgFlags string `json:"gpgflags"`
  44. MFlags string `json:"mflags"`
  45. SortBy string `json:"sortby"`
  46. SearchBy string `json:"searchby"`
  47. GitFlags string `json:"gitflags"`
  48. RemoveMake string `json:"removemake"`
  49. SudoBin string `json:"sudobin"`
  50. SudoFlags string `json:"sudoflags"`
  51. RequestSplitN int `json:"requestsplitn"`
  52. CompletionInterval int `json:"completionrefreshtime"`
  53. MaxConcurrentDownloads int `json:"maxconcurrentdownloads"`
  54. BottomUp bool `json:"bottomup"`
  55. SudoLoop bool `json:"sudoloop"`
  56. TimeUpdate bool `json:"timeupdate"`
  57. Devel bool `json:"devel"`
  58. CleanAfter bool `json:"cleanAfter"`
  59. Provides bool `json:"provides"`
  60. PGPFetch bool `json:"pgpfetch"`
  61. UpgradeMenu bool `json:"upgrademenu"`
  62. CleanMenu bool `json:"cleanmenu"`
  63. DiffMenu bool `json:"diffmenu"`
  64. EditMenu bool `json:"editmenu"`
  65. CombinedUpgrade bool `json:"combinedupgrade"`
  66. UseAsk bool `json:"useask"`
  67. BatchInstall bool `json:"batchinstall"`
  68. SingleLineResults bool `json:"singlelineresults"`
  69. SeparateSources bool `json:"separatesources"`
  70. Runtime *Runtime `json:"-"`
  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.AURRPCURL = os.ExpandEnv(c.AURRPCURL)
  101. c.BuildDir = os.ExpandEnv(c.BuildDir)
  102. c.Editor = os.ExpandEnv(c.Editor)
  103. c.EditorFlags = os.ExpandEnv(c.EditorFlags)
  104. c.MakepkgBin = os.ExpandEnv(c.MakepkgBin)
  105. c.MakepkgConf = os.ExpandEnv(c.MakepkgConf)
  106. c.PacmanBin = os.ExpandEnv(c.PacmanBin)
  107. c.PacmanConf = os.ExpandEnv(c.PacmanConf)
  108. c.GpgFlags = os.ExpandEnv(c.GpgFlags)
  109. c.MFlags = os.ExpandEnv(c.MFlags)
  110. c.GitFlags = os.ExpandEnv(c.GitFlags)
  111. c.SortBy = os.ExpandEnv(c.SortBy)
  112. c.SearchBy = os.ExpandEnv(c.SearchBy)
  113. c.GitBin = os.ExpandEnv(c.GitBin)
  114. c.GpgBin = os.ExpandEnv(c.GpgBin)
  115. c.SudoBin = os.ExpandEnv(c.SudoBin)
  116. c.SudoFlags = os.ExpandEnv(c.SudoFlags)
  117. c.ReDownload = os.ExpandEnv(c.ReDownload)
  118. c.ReBuild = os.ExpandEnv(c.ReBuild)
  119. c.AnswerClean = os.ExpandEnv(c.AnswerClean)
  120. c.AnswerDiff = os.ExpandEnv(c.AnswerDiff)
  121. c.AnswerEdit = os.ExpandEnv(c.AnswerEdit)
  122. c.AnswerUpgrade = os.ExpandEnv(c.AnswerUpgrade)
  123. c.RemoveMake = os.ExpandEnv(c.RemoveMake)
  124. }
  125. func (c *Configuration) String() string {
  126. var buf bytes.Buffer
  127. enc := json.NewEncoder(&buf)
  128. enc.SetIndent("", "\t")
  129. if err := enc.Encode(c); err != nil {
  130. fmt.Fprintln(os.Stderr, err)
  131. }
  132. return buf.String()
  133. }
  134. // check privilege elevator exists otherwise try to find another one.
  135. func (c *Configuration) setPrivilegeElevator() error {
  136. if auth := os.Getenv("PACMAN_AUTH"); auth != "" {
  137. c.SudoBin = auth
  138. if auth != "sudo" {
  139. c.SudoFlags = ""
  140. c.SudoLoop = false
  141. }
  142. }
  143. for _, bin := range [...]string{c.SudoBin, "sudo"} {
  144. if _, err := exec.LookPath(bin); err == nil {
  145. c.SudoBin = bin
  146. return nil // wrapper or sudo command existing. Retrocompatiblity
  147. }
  148. }
  149. c.SudoFlags = ""
  150. c.SudoLoop = false
  151. for _, bin := range [...]string{"doas", "pkexec", "su"} {
  152. if _, err := exec.LookPath(bin); err == nil {
  153. c.SudoBin = bin
  154. return nil // command existing
  155. }
  156. }
  157. return &ErrPrivilegeElevatorNotFound{confValue: c.SudoBin}
  158. }
  159. func DefaultConfig(version string) *Configuration {
  160. return &Configuration{
  161. AURURL: "https://aur.archlinux.org",
  162. BuildDir: os.ExpandEnv("$HOME/.cache/yay"),
  163. CleanAfter: false,
  164. Editor: "",
  165. EditorFlags: "",
  166. Devel: false,
  167. MakepkgBin: "makepkg",
  168. MakepkgConf: "",
  169. PacmanBin: "pacman",
  170. PGPFetch: true,
  171. PacmanConf: "/etc/pacman.conf",
  172. GpgFlags: "",
  173. MFlags: "",
  174. GitFlags: "",
  175. BottomUp: true,
  176. CompletionInterval: 7,
  177. MaxConcurrentDownloads: 0,
  178. SortBy: "votes",
  179. SearchBy: "name-desc",
  180. SudoLoop: false,
  181. GitBin: "git",
  182. GpgBin: "gpg",
  183. SudoBin: "sudo",
  184. SudoFlags: "",
  185. TimeUpdate: false,
  186. RequestSplitN: 150,
  187. ReDownload: "no",
  188. ReBuild: "no",
  189. BatchInstall: false,
  190. AnswerClean: "",
  191. AnswerDiff: "",
  192. AnswerEdit: "",
  193. AnswerUpgrade: "",
  194. RemoveMake: "ask",
  195. Provides: false,
  196. UpgradeMenu: true,
  197. CleanMenu: true,
  198. DiffMenu: true,
  199. EditMenu: false,
  200. UseAsk: false,
  201. CombinedUpgrade: false,
  202. SeparateSources: true,
  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. }
  249. var errAUR error
  250. newConfig.Runtime.AURClient, errAUR = aur.NewClient(aur.WithHTTPClient(newConfig.Runtime.HTTPClient),
  251. aur.WithRequestEditorFn(func(ctx context.Context, req *http.Request) error {
  252. req.Header.Set("User-Agent", userAgent)
  253. return nil
  254. }))
  255. if errAUR != nil {
  256. return nil, errAUR
  257. }
  258. newConfig.Runtime.VCSStore = vcs.NewInfoStore(
  259. filepath.Join(cacheHome, vcsFileName), newConfig.Runtime.CmdBuilder)
  260. err := newConfig.Runtime.VCSStore.Load()
  261. return newConfig, err
  262. }
  263. func (c *Configuration) load(configPath string) {
  264. cfile, err := os.Open(configPath)
  265. if !os.IsNotExist(err) && err != nil {
  266. fmt.Fprintln(os.Stderr,
  267. gotext.Get("failed to open config file '%s': %s", configPath, err))
  268. return
  269. }
  270. defer cfile.Close()
  271. if !os.IsNotExist(err) {
  272. decoder := json.NewDecoder(cfile)
  273. if err = decoder.Decode(c); err != nil {
  274. fmt.Fprintln(os.Stderr,
  275. gotext.Get("failed to read config file '%s': %s", configPath, err))
  276. }
  277. }
  278. }
  279. func (c *Configuration) CmdBuilder(runner exe.Runner) exe.ICmdBuilder {
  280. if runner == nil {
  281. runner = &exe.OSRunner{}
  282. }
  283. return &exe.CmdBuilder{
  284. GitBin: c.GitBin,
  285. GitFlags: strings.Fields(c.GitFlags),
  286. MakepkgFlags: strings.Fields(c.MFlags),
  287. MakepkgConfPath: c.MakepkgConf,
  288. MakepkgBin: c.MakepkgBin,
  289. SudoBin: c.SudoBin,
  290. SudoFlags: strings.Fields(c.SudoFlags),
  291. SudoLoopEnabled: c.SudoLoop,
  292. PacmanBin: c.PacmanBin,
  293. PacmanConfigPath: c.PacmanConf,
  294. PacmanDBPath: "",
  295. Runner: runner,
  296. }
  297. }