query.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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(aurClient *aur.Client, pkgS []string, sortS bool) (aurQuery, error) {
  79. var r []aur.Pkg
  80. var err error
  81. var usedIndex int
  82. by := getSearchBy(config.SearchBy)
  83. if len(pkgS) == 0 {
  84. return nil, nil
  85. }
  86. for i, word := range pkgS {
  87. r, err = aurClient.Search(context.Background(), word, by)
  88. if err == nil {
  89. usedIndex = i
  90. break
  91. }
  92. }
  93. if err != nil {
  94. return nil, err
  95. }
  96. if len(pkgS) == 1 {
  97. if sortS {
  98. sort.Sort(aurQuery(r))
  99. }
  100. return r, err
  101. }
  102. var aq aurQuery
  103. var n int
  104. for i := range r {
  105. match := true
  106. for j, pkgN := range pkgS {
  107. if usedIndex == j {
  108. continue
  109. }
  110. if !(strings.Contains(r[i].Name, pkgN) || strings.Contains(strings.ToLower(r[i].Description), pkgN)) {
  111. match = false
  112. break
  113. }
  114. }
  115. if match {
  116. n++
  117. aq = append(aq, r[i])
  118. }
  119. }
  120. if sortS {
  121. sort.Sort(aq)
  122. }
  123. return aq, err
  124. }
  125. // SyncSearch presents a query to the local repos and to the AUR.
  126. func syncSearch(pkgS []string, aurClient *aur.Client, dbExecutor db.Executor) (err error) {
  127. pkgS = query.RemoveInvalidTargets(pkgS, config.Runtime.Mode)
  128. var aurErr error
  129. var aq aurQuery
  130. var pq repoQuery
  131. if config.Runtime.Mode == parser.ModeAUR || config.Runtime.Mode == parser.ModeAny {
  132. aq, aurErr = narrowSearch(aurClient, pkgS, true)
  133. }
  134. if config.Runtime.Mode == parser.ModeRepo || config.Runtime.Mode == parser.ModeAny {
  135. pq = queryRepo(pkgS, dbExecutor)
  136. }
  137. switch config.SortMode {
  138. case settings.TopDown:
  139. if config.Runtime.Mode == parser.ModeRepo || config.Runtime.Mode == parser.ModeAny {
  140. pq.printSearch(dbExecutor)
  141. }
  142. if config.Runtime.Mode == parser.ModeAUR || config.Runtime.Mode == parser.ModeAny {
  143. aq.printSearch(1, dbExecutor)
  144. }
  145. case settings.BottomUp:
  146. if config.Runtime.Mode == parser.ModeAUR || config.Runtime.Mode == parser.ModeAny {
  147. aq.printSearch(1, dbExecutor)
  148. }
  149. if config.Runtime.Mode == parser.ModeRepo || config.Runtime.Mode == parser.ModeAny {
  150. pq.printSearch(dbExecutor)
  151. }
  152. default:
  153. return errors.New(gotext.Get("invalid sort mode. Fix with yay -Y --bottomup --save"))
  154. }
  155. if aurErr != nil {
  156. text.Errorln(gotext.Get("error during AUR search: %s", aurErr))
  157. text.Warnln(gotext.Get("Showing repo packages only"))
  158. }
  159. return nil
  160. }
  161. // SyncInfo serves as a pacman -Si for repo packages and AUR packages.
  162. func syncInfo(cmdArgs *parser.Arguments, pkgS []string, dbExecutor db.Executor) error {
  163. var info []*aur.Pkg
  164. var err error
  165. missing := false
  166. pkgS = query.RemoveInvalidTargets(pkgS, config.Runtime.Mode)
  167. aurS, repoS := packageSlices(pkgS, dbExecutor)
  168. if len(aurS) != 0 {
  169. noDB := make([]string, 0, len(aurS))
  170. for _, pkg := range aurS {
  171. _, name := text.SplitDBFromName(pkg)
  172. noDB = append(noDB, name)
  173. }
  174. info, err = query.AURInfoPrint(config.Runtime.AURClient, noDB, config.RequestSplitN)
  175. if err != nil {
  176. missing = true
  177. fmt.Fprintln(os.Stderr, err)
  178. }
  179. }
  180. // Repo always goes first
  181. if len(repoS) != 0 {
  182. arguments := cmdArgs.Copy()
  183. arguments.ClearTargets()
  184. arguments.AddTarget(repoS...)
  185. err = config.Runtime.CmdRunner.Show(config.Runtime.CmdBuilder.BuildPacmanCmd(
  186. cmdArgs, config.Runtime.Mode, settings.NoConfirm))
  187. if err != nil {
  188. return err
  189. }
  190. }
  191. if len(aurS) != len(info) {
  192. missing = true
  193. }
  194. if len(info) != 0 {
  195. for _, pkg := range info {
  196. PrintInfo(pkg, cmdArgs.ExistsDouble("i"))
  197. }
  198. }
  199. if missing {
  200. err = fmt.Errorf("")
  201. }
  202. return err
  203. }
  204. // Search handles repo searches. Creates a RepoSearch struct.
  205. func queryRepo(pkgInputN []string, dbExecutor db.Executor) repoQuery {
  206. s := repoQuery(dbExecutor.SyncPackages(pkgInputN...))
  207. if config.SortMode == settings.BottomUp {
  208. s.Reverse()
  209. }
  210. return s
  211. }
  212. // PackageSlices separates an input slice into aur and repo slices
  213. func packageSlices(toCheck []string, dbExecutor db.Executor) (aurNames, repoNames []string) {
  214. for _, _pkg := range toCheck {
  215. dbName, name := text.SplitDBFromName(_pkg)
  216. if dbName == "aur" || config.Runtime.Mode == parser.ModeAUR {
  217. aurNames = append(aurNames, _pkg)
  218. continue
  219. } else if dbName != "" || config.Runtime.Mode == parser.ModeRepo {
  220. repoNames = append(repoNames, _pkg)
  221. continue
  222. }
  223. if dbExecutor.SyncSatisfierExists(name) ||
  224. len(dbExecutor.PackagesFromGroup(name)) != 0 {
  225. repoNames = append(repoNames, _pkg)
  226. } else {
  227. aurNames = append(aurNames, _pkg)
  228. }
  229. }
  230. return aurNames, repoNames
  231. }
  232. // HangingPackages returns a list of packages installed as deps
  233. // and unneeded by the system
  234. // removeOptional decides whether optional dependencies are counted or not
  235. func hangingPackages(removeOptional bool, dbExecutor db.Executor) (hanging []string) {
  236. // safePackages represents every package in the system in one of 3 states
  237. // State = 0 - Remove package from the system
  238. // State = 1 - Keep package in the system; need to iterate over dependencies
  239. // State = 2 - Keep package and have iterated over dependencies
  240. safePackages := make(map[string]uint8)
  241. // provides stores a mapping from the provides name back to the original package name
  242. provides := make(stringset.MapStringSet)
  243. packages := dbExecutor.LocalPackages()
  244. // Mark explicit dependencies and enumerate the provides list
  245. for _, pkg := range packages {
  246. if pkg.Reason() == alpm.PkgReasonExplicit {
  247. safePackages[pkg.Name()] = 1
  248. } else {
  249. safePackages[pkg.Name()] = 0
  250. }
  251. for _, dep := range dbExecutor.PackageProvides(pkg) {
  252. provides.Add(dep.Name, pkg.Name())
  253. }
  254. }
  255. iterateAgain := true
  256. for iterateAgain {
  257. iterateAgain = false
  258. for _, pkg := range packages {
  259. if state := safePackages[pkg.Name()]; state == 0 || state == 2 {
  260. continue
  261. }
  262. safePackages[pkg.Name()] = 2
  263. deps := dbExecutor.PackageDepends(pkg)
  264. if !removeOptional {
  265. deps = append(deps, dbExecutor.PackageOptionalDepends(pkg)...)
  266. }
  267. // Update state for dependencies
  268. for _, dep := range deps {
  269. // Don't assume a dependency is installed
  270. state, ok := safePackages[dep.Name]
  271. if !ok {
  272. // Check if dep is a provides rather than actual package name
  273. if pset, ok2 := provides[dep.Name]; ok2 {
  274. for p := range pset {
  275. if safePackages[p] == 0 {
  276. iterateAgain = true
  277. safePackages[p] = 1
  278. }
  279. }
  280. }
  281. continue
  282. }
  283. if state == 0 {
  284. iterateAgain = true
  285. safePackages[dep.Name] = 1
  286. }
  287. }
  288. }
  289. }
  290. // Build list of packages to be removed
  291. for _, pkg := range packages {
  292. if safePackages[pkg.Name()] == 0 {
  293. hanging = append(hanging, pkg.Name())
  294. }
  295. }
  296. return hanging
  297. }
  298. // Statistics returns statistics about packages installed in system
  299. func statistics(dbExecutor db.Executor) *struct {
  300. Totaln int
  301. Expln int
  302. TotalSize int64
  303. } {
  304. var totalSize int64
  305. localPackages := dbExecutor.LocalPackages()
  306. totalInstalls := 0
  307. explicitInstalls := 0
  308. for _, pkg := range localPackages {
  309. totalSize += pkg.ISize()
  310. totalInstalls++
  311. if pkg.Reason() == alpm.PkgReasonExplicit {
  312. explicitInstalls++
  313. }
  314. }
  315. info := &struct {
  316. Totaln int
  317. Expln int
  318. TotalSize int64
  319. }{
  320. totalInstalls, explicitInstalls, totalSize,
  321. }
  322. return info
  323. }