query.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "sort"
  8. "strings"
  9. aur "github.com/Jguer/aur"
  10. alpm "github.com/Jguer/go-alpm/v2"
  11. "github.com/leonelquinteros/gotext"
  12. "github.com/Jguer/yay/v10/pkg/db"
  13. "github.com/Jguer/yay/v10/pkg/query"
  14. "github.com/Jguer/yay/v10/pkg/settings"
  15. "github.com/Jguer/yay/v10/pkg/settings/parser"
  16. "github.com/Jguer/yay/v10/pkg/stringset"
  17. "github.com/Jguer/yay/v10/pkg/text"
  18. )
  19. // Query is a collection of Results.
  20. type aurQuery []aur.Pkg
  21. // Query holds the results of a repository search.
  22. type repoQuery []alpm.IPackage
  23. func (s repoQuery) Reverse() {
  24. for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
  25. s[i], s[j] = s[j], s[i]
  26. }
  27. }
  28. func (q aurQuery) Len() int {
  29. return len(q)
  30. }
  31. func (q aurQuery) Less(i, j int) bool {
  32. var result bool
  33. switch config.SortBy {
  34. case "votes":
  35. result = q[i].NumVotes > q[j].NumVotes
  36. case "popularity":
  37. result = q[i].Popularity > q[j].Popularity
  38. case "name":
  39. result = text.LessRunes([]rune(q[i].Name), []rune(q[j].Name))
  40. case "base":
  41. result = text.LessRunes([]rune(q[i].PackageBase), []rune(q[j].PackageBase))
  42. case "submitted":
  43. result = q[i].FirstSubmitted < q[j].FirstSubmitted
  44. case "modified":
  45. result = q[i].LastModified < q[j].LastModified
  46. case "id":
  47. result = q[i].ID < q[j].ID
  48. case "baseid":
  49. result = q[i].PackageBaseID < q[j].PackageBaseID
  50. }
  51. if config.SortMode == settings.BottomUp {
  52. return !result
  53. }
  54. return result
  55. }
  56. func (q aurQuery) Swap(i, j int) {
  57. q[i], q[j] = q[j], q[i]
  58. }
  59. func getSearchBy(value string) aur.By {
  60. switch value {
  61. case "name":
  62. return aur.Name
  63. case "maintainer":
  64. return aur.Maintainer
  65. case "depends":
  66. return aur.Depends
  67. case "makedepends":
  68. return aur.MakeDepends
  69. case "optdepends":
  70. return aur.OptDepends
  71. case "checkdepends":
  72. return aur.CheckDepends
  73. default:
  74. return aur.NameDesc
  75. }
  76. }
  77. // NarrowSearch searches AUR and narrows based on subarguments.
  78. func narrowSearch(ctx context.Context, aurClient *aur.Client, pkgS []string, sortS bool) (aurQuery, error) {
  79. var (
  80. r []aur.Pkg
  81. err error
  82. usedIndex int
  83. )
  84. by := getSearchBy(config.SearchBy)
  85. if len(pkgS) == 0 {
  86. return nil, nil
  87. }
  88. for i, word := range pkgS {
  89. r, err = aurClient.Search(ctx, word, by)
  90. if err == nil {
  91. usedIndex = i
  92. break
  93. }
  94. }
  95. if err != nil {
  96. return nil, err
  97. }
  98. if len(pkgS) == 1 {
  99. if sortS {
  100. sort.Sort(aurQuery(r))
  101. }
  102. return r, err
  103. }
  104. var (
  105. aq aurQuery
  106. n int
  107. )
  108. for i := range r {
  109. match := true
  110. for j, pkgN := range pkgS {
  111. if usedIndex == j {
  112. continue
  113. }
  114. if !(strings.Contains(r[i].Name, pkgN) || strings.Contains(strings.ToLower(r[i].Description), pkgN)) {
  115. match = false
  116. break
  117. }
  118. }
  119. if match {
  120. n++
  121. aq = append(aq, r[i])
  122. }
  123. }
  124. if sortS {
  125. sort.Sort(aq)
  126. }
  127. return aq, err
  128. }
  129. // SyncSearch presents a query to the local repos and to the AUR.
  130. func syncSearch(ctx context.Context, pkgS []string, aurClient *aur.Client, dbExecutor db.Executor) (err error) {
  131. pkgS = query.RemoveInvalidTargets(pkgS, config.Runtime.Mode)
  132. var (
  133. aurErr error
  134. aq aurQuery
  135. pq repoQuery
  136. )
  137. if config.Runtime.Mode.AtLeastAUR() {
  138. aq, aurErr = narrowSearch(ctx, aurClient, pkgS, true)
  139. }
  140. if config.Runtime.Mode.AtLeastRepo() {
  141. pq = queryRepo(pkgS, dbExecutor)
  142. }
  143. switch config.SortMode {
  144. case settings.TopDown:
  145. if config.Runtime.Mode.AtLeastRepo() {
  146. pq.printSearch(dbExecutor)
  147. }
  148. if config.Runtime.Mode.AtLeastAUR() {
  149. aq.printSearch(1, dbExecutor)
  150. }
  151. case settings.BottomUp:
  152. if config.Runtime.Mode.AtLeastAUR() {
  153. aq.printSearch(1, dbExecutor)
  154. }
  155. if config.Runtime.Mode.AtLeastRepo() {
  156. pq.printSearch(dbExecutor)
  157. }
  158. default:
  159. return errors.New(gotext.Get("invalid sort mode. Fix with yay -Y --bottomup --save"))
  160. }
  161. if aurErr != nil {
  162. text.Errorln(gotext.Get("error during AUR search: %s", aurErr))
  163. text.Warnln(gotext.Get("Showing repo packages only"))
  164. }
  165. return nil
  166. }
  167. // SyncInfo serves as a pacman -Si for repo packages and AUR packages.
  168. func syncInfo(ctx context.Context, cmdArgs *parser.Arguments, pkgS []string, dbExecutor db.Executor) error {
  169. var (
  170. info []*aur.Pkg
  171. err error
  172. missing = false
  173. )
  174. pkgS = query.RemoveInvalidTargets(pkgS, config.Runtime.Mode)
  175. aurS, repoS := packageSlices(pkgS, dbExecutor)
  176. if len(aurS) != 0 {
  177. noDB := make([]string, 0, len(aurS))
  178. for _, pkg := range aurS {
  179. _, name := text.SplitDBFromName(pkg)
  180. noDB = append(noDB, name)
  181. }
  182. info, err = query.AURInfoPrint(ctx, config.Runtime.AURClient, noDB, config.RequestSplitN)
  183. if err != nil {
  184. missing = true
  185. fmt.Fprintln(os.Stderr, err)
  186. }
  187. }
  188. // Repo always goes first
  189. if len(repoS) != 0 {
  190. arguments := cmdArgs.Copy()
  191. arguments.ClearTargets()
  192. arguments.AddTarget(repoS...)
  193. err = config.Runtime.CmdBuilder.Show(config.Runtime.CmdBuilder.BuildPacmanCmd(ctx,
  194. cmdArgs, config.Runtime.Mode, settings.NoConfirm))
  195. if err != nil {
  196. return err
  197. }
  198. }
  199. if len(aurS) != len(info) {
  200. missing = true
  201. }
  202. if len(info) != 0 {
  203. for _, pkg := range info {
  204. PrintInfo(pkg, cmdArgs.ExistsDouble("i"))
  205. }
  206. }
  207. if missing {
  208. err = fmt.Errorf("")
  209. }
  210. return err
  211. }
  212. // Search handles repo searches. Creates a RepoSearch struct.
  213. func queryRepo(pkgInputN []string, dbExecutor db.Executor) repoQuery {
  214. s := repoQuery(dbExecutor.SyncPackages(pkgInputN...))
  215. if config.SortMode == settings.BottomUp {
  216. s.Reverse()
  217. }
  218. return s
  219. }
  220. // PackageSlices separates an input slice into aur and repo slices.
  221. func packageSlices(toCheck []string, dbExecutor db.Executor) (aurNames, repoNames []string) {
  222. for _, _pkg := range toCheck {
  223. dbName, name := text.SplitDBFromName(_pkg)
  224. if dbName == "aur" || config.Runtime.Mode == parser.ModeAUR {
  225. aurNames = append(aurNames, _pkg)
  226. continue
  227. } else if dbName != "" || config.Runtime.Mode == parser.ModeRepo {
  228. repoNames = append(repoNames, _pkg)
  229. continue
  230. }
  231. if dbExecutor.SyncSatisfierExists(name) ||
  232. len(dbExecutor.PackagesFromGroup(name)) != 0 {
  233. repoNames = append(repoNames, _pkg)
  234. } else {
  235. aurNames = append(aurNames, _pkg)
  236. }
  237. }
  238. return aurNames, repoNames
  239. }
  240. // HangingPackages returns a list of packages installed as deps
  241. // and unneeded by the system
  242. // removeOptional decides whether optional dependencies are counted or not.
  243. func hangingPackages(removeOptional bool, dbExecutor db.Executor) (hanging []string) {
  244. // safePackages represents every package in the system in one of 3 states
  245. // State = 0 - Remove package from the system
  246. // State = 1 - Keep package in the system; need to iterate over dependencies
  247. // State = 2 - Keep package and have iterated over dependencies
  248. safePackages := make(map[string]uint8)
  249. // provides stores a mapping from the provides name back to the original package name
  250. provides := make(stringset.MapStringSet)
  251. packages := dbExecutor.LocalPackages()
  252. // Mark explicit dependencies and enumerate the provides list
  253. for _, pkg := range packages {
  254. if pkg.Reason() == alpm.PkgReasonExplicit {
  255. safePackages[pkg.Name()] = 1
  256. } else {
  257. safePackages[pkg.Name()] = 0
  258. }
  259. for _, dep := range dbExecutor.PackageProvides(pkg) {
  260. provides.Add(dep.Name, pkg.Name())
  261. }
  262. }
  263. iterateAgain := true
  264. for iterateAgain {
  265. iterateAgain = false
  266. for _, pkg := range packages {
  267. if state := safePackages[pkg.Name()]; state == 0 || state == 2 {
  268. continue
  269. }
  270. safePackages[pkg.Name()] = 2
  271. deps := dbExecutor.PackageDepends(pkg)
  272. if !removeOptional {
  273. deps = append(deps, dbExecutor.PackageOptionalDepends(pkg)...)
  274. }
  275. // Update state for dependencies
  276. for _, dep := range deps {
  277. // Don't assume a dependency is installed
  278. state, ok := safePackages[dep.Name]
  279. if !ok {
  280. // Check if dep is a provides rather than actual package name
  281. if pset, ok2 := provides[dep.Name]; ok2 {
  282. for p := range pset {
  283. if safePackages[p] == 0 {
  284. iterateAgain = true
  285. safePackages[p] = 1
  286. }
  287. }
  288. }
  289. continue
  290. }
  291. if state == 0 {
  292. iterateAgain = true
  293. safePackages[dep.Name] = 1
  294. }
  295. }
  296. }
  297. }
  298. // Build list of packages to be removed
  299. for _, pkg := range packages {
  300. if safePackages[pkg.Name()] == 0 {
  301. hanging = append(hanging, pkg.Name())
  302. }
  303. }
  304. return hanging
  305. }
  306. // Statistics returns statistics about packages installed in system.
  307. func statistics(dbExecutor db.Executor) *struct {
  308. Totaln int
  309. Expln int
  310. TotalSize int64
  311. } {
  312. var (
  313. totalSize int64
  314. localPackages = dbExecutor.LocalPackages()
  315. totalInstalls = 0
  316. explicitInstalls = 0
  317. )
  318. for _, pkg := range localPackages {
  319. totalSize += pkg.ISize()
  320. totalInstalls++
  321. if pkg.Reason() == alpm.PkgReasonExplicit {
  322. explicitInstalls++
  323. }
  324. }
  325. info := &struct {
  326. Totaln int
  327. Expln int
  328. TotalSize int64
  329. }{
  330. totalInstalls, explicitInstalls, totalSize,
  331. }
  332. return info
  333. }