query.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. alpm "github.com/Jguer/go-alpm"
  11. "github.com/leonelquinteros/gotext"
  12. rpc "github.com/mikkeloscar/aur"
  13. "github.com/Jguer/yay/v10/pkg/intrange"
  14. "github.com/Jguer/yay/v10/pkg/multierror"
  15. "github.com/Jguer/yay/v10/pkg/stringset"
  16. "github.com/Jguer/yay/v10/pkg/text"
  17. )
  18. type aurWarnings struct {
  19. Orphans []string
  20. OutOfDate []string
  21. Missing []string
  22. Ignore stringset.StringSet
  23. }
  24. func makeWarnings() *aurWarnings {
  25. return &aurWarnings{Ignore: make(stringset.StringSet)}
  26. }
  27. // Query is a collection of Results
  28. type aurQuery []rpc.Pkg
  29. // Query holds the results of a repository search.
  30. type repoQuery []alpm.Package
  31. func (q aurQuery) Len() int {
  32. return len(q)
  33. }
  34. func (q aurQuery) Less(i, j int) bool {
  35. var result bool
  36. switch config.SortBy {
  37. case "votes":
  38. result = q[i].NumVotes > q[j].NumVotes
  39. case "popularity":
  40. result = q[i].Popularity > q[j].Popularity
  41. case "name":
  42. result = LessRunes([]rune(q[i].Name), []rune(q[j].Name))
  43. case "base":
  44. result = LessRunes([]rune(q[i].PackageBase), []rune(q[j].PackageBase))
  45. case "submitted":
  46. result = q[i].FirstSubmitted < q[j].FirstSubmitted
  47. case "modified":
  48. result = q[i].LastModified < q[j].LastModified
  49. case "id":
  50. result = q[i].ID < q[j].ID
  51. case "baseid":
  52. result = q[i].PackageBaseID < q[j].PackageBaseID
  53. }
  54. if config.SortMode == bottomUp {
  55. return !result
  56. }
  57. return result
  58. }
  59. func (q aurQuery) Swap(i, j int) {
  60. q[i], q[j] = q[j], q[i]
  61. }
  62. // FilterPackages filters packages based on source and type from local repository.
  63. func filterPackages() (
  64. local, remote []alpm.Package,
  65. localNames, remoteNames []string,
  66. err error) {
  67. localDB, err := alpmHandle.LocalDB()
  68. if err != nil {
  69. return
  70. }
  71. dbList, err := alpmHandle.SyncDBs()
  72. if err != nil {
  73. return
  74. }
  75. f := func(k alpm.Package) error {
  76. found := false
  77. // For each DB search for our secret package.
  78. _ = dbList.ForEach(func(d alpm.DB) error {
  79. if found {
  80. return nil
  81. }
  82. if d.Pkg(k.Name()) != nil {
  83. found = true
  84. local = append(local, k)
  85. localNames = append(localNames, k.Name())
  86. }
  87. return nil
  88. })
  89. if !found {
  90. remote = append(remote, k)
  91. remoteNames = append(remoteNames, k.Name())
  92. }
  93. return nil
  94. }
  95. err = localDB.PkgCache().ForEach(f)
  96. return local, remote, localNames, remoteNames, err
  97. }
  98. func getSearchBy(value string) rpc.By {
  99. switch value {
  100. case "name":
  101. return rpc.Name
  102. case "maintainer":
  103. return rpc.Maintainer
  104. case "depends":
  105. return rpc.Depends
  106. case "makedepends":
  107. return rpc.MakeDepends
  108. case "optdepends":
  109. return rpc.OptDepends
  110. case "checkdepends":
  111. return rpc.CheckDepends
  112. default:
  113. return rpc.NameDesc
  114. }
  115. }
  116. // NarrowSearch searches AUR and narrows based on subarguments
  117. func narrowSearch(pkgS []string, sortS bool) (aurQuery, error) {
  118. var r []rpc.Pkg
  119. var err error
  120. var usedIndex int
  121. by := getSearchBy(config.SearchBy)
  122. if len(pkgS) == 0 {
  123. return nil, nil
  124. }
  125. for i, word := range pkgS {
  126. r, err = rpc.SearchBy(word, by)
  127. if err == nil {
  128. usedIndex = i
  129. break
  130. }
  131. }
  132. if err != nil {
  133. return nil, err
  134. }
  135. if len(pkgS) == 1 {
  136. if sortS {
  137. sort.Sort(aurQuery(r))
  138. }
  139. return r, err
  140. }
  141. var aq aurQuery
  142. var n int
  143. for i := range r {
  144. match := true
  145. for j, pkgN := range pkgS {
  146. if usedIndex == j {
  147. continue
  148. }
  149. if !(strings.Contains(r[i].Name, pkgN) || strings.Contains(strings.ToLower(r[i].Description), pkgN)) {
  150. match = false
  151. break
  152. }
  153. }
  154. if match {
  155. n++
  156. aq = append(aq, r[i])
  157. }
  158. }
  159. if sortS {
  160. sort.Sort(aq)
  161. }
  162. return aq, err
  163. }
  164. // SyncSearch presents a query to the local repos and to the AUR.
  165. func syncSearch(pkgS []string) (err error) {
  166. pkgS = removeInvalidTargets(pkgS)
  167. var aurErr error
  168. var repoErr error
  169. var aq aurQuery
  170. var pq repoQuery
  171. if mode == modeAUR || mode == modeAny {
  172. aq, aurErr = narrowSearch(pkgS, true)
  173. }
  174. if mode == modeRepo || mode == modeAny {
  175. pq, repoErr = queryRepo(pkgS)
  176. if repoErr != nil {
  177. return err
  178. }
  179. }
  180. switch config.SortMode {
  181. case topDown:
  182. if mode == modeRepo || mode == modeAny {
  183. pq.printSearch()
  184. }
  185. if mode == modeAUR || mode == modeAny {
  186. aq.printSearch(1)
  187. }
  188. case bottomUp:
  189. if mode == modeAUR || mode == modeAny {
  190. aq.printSearch(1)
  191. }
  192. if mode == modeRepo || mode == modeAny {
  193. pq.printSearch()
  194. }
  195. default:
  196. return errors.New(gotext.Get("invalid sort mode. Fix with yay -Y --bottomup --save"))
  197. }
  198. if aurErr != nil {
  199. text.Errorln(gotext.Get("error during AUR search: %s", aurErr))
  200. text.Warnln(gotext.Get("Showing repo packages only"))
  201. }
  202. return nil
  203. }
  204. // SyncInfo serves as a pacman -Si for repo packages and AUR packages.
  205. func syncInfo(pkgS []string) error {
  206. var info []*rpc.Pkg
  207. missing := false
  208. pkgS = removeInvalidTargets(pkgS)
  209. aurS, repoS, err := packageSlices(pkgS)
  210. if err != nil {
  211. return err
  212. }
  213. if len(aurS) != 0 {
  214. noDB := make([]string, 0, len(aurS))
  215. for _, pkg := range aurS {
  216. _, name := splitDBFromName(pkg)
  217. noDB = append(noDB, name)
  218. }
  219. info, err = aurInfoPrint(noDB)
  220. if err != nil {
  221. missing = true
  222. fmt.Fprintln(os.Stderr, err)
  223. }
  224. }
  225. // Repo always goes first
  226. if len(repoS) != 0 {
  227. arguments := cmdArgs.copy()
  228. arguments.clearTargets()
  229. arguments.addTarget(repoS...)
  230. err = show(passToPacman(arguments))
  231. if err != nil {
  232. return err
  233. }
  234. }
  235. if len(aurS) != len(info) {
  236. missing = true
  237. }
  238. if len(info) != 0 {
  239. for _, pkg := range info {
  240. PrintInfo(pkg)
  241. }
  242. }
  243. if missing {
  244. err = fmt.Errorf("")
  245. }
  246. return err
  247. }
  248. // Search handles repo searches. Creates a RepoSearch struct.
  249. func queryRepo(pkgInputN []string) (s repoQuery, err error) {
  250. dbList, err := alpmHandle.SyncDBs()
  251. if err != nil {
  252. return
  253. }
  254. _ = dbList.ForEach(func(db alpm.DB) error {
  255. if len(pkgInputN) == 0 {
  256. pkgs := db.PkgCache()
  257. s = append(s, pkgs.Slice()...)
  258. } else {
  259. pkgs := db.Search(pkgInputN)
  260. s = append(s, pkgs.Slice()...)
  261. }
  262. return nil
  263. })
  264. if config.SortMode == bottomUp {
  265. for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
  266. s[i], s[j] = s[j], s[i]
  267. }
  268. }
  269. return
  270. }
  271. // PackageSlices separates an input slice into aur and repo slices
  272. func packageSlices(toCheck []string) (aur, repo []string, err error) {
  273. dbList, err := alpmHandle.SyncDBs()
  274. if err != nil {
  275. return nil, nil, err
  276. }
  277. for _, _pkg := range toCheck {
  278. db, name := splitDBFromName(_pkg)
  279. found := false
  280. if db == "aur" || mode == modeAUR {
  281. aur = append(aur, _pkg)
  282. continue
  283. } else if db != "" || mode == modeRepo {
  284. repo = append(repo, _pkg)
  285. continue
  286. }
  287. _ = dbList.ForEach(func(db alpm.DB) error {
  288. if db.Pkg(name) != nil {
  289. found = true
  290. return fmt.Errorf("")
  291. }
  292. return nil
  293. })
  294. if !found {
  295. found = !dbList.FindGroupPkgs(name).Empty()
  296. }
  297. if found {
  298. repo = append(repo, _pkg)
  299. } else {
  300. aur = append(aur, _pkg)
  301. }
  302. }
  303. return aur, repo, nil
  304. }
  305. // HangingPackages returns a list of packages installed as deps
  306. // and unneeded by the system
  307. // removeOptional decides whether optional dependencies are counted or not
  308. func hangingPackages(removeOptional bool) (hanging []string, err error) {
  309. localDB, err := alpmHandle.LocalDB()
  310. if err != nil {
  311. return
  312. }
  313. // safePackages represents every package in the system in one of 3 states
  314. // State = 0 - Remove package from the system
  315. // State = 1 - Keep package in the system; need to iterate over dependencies
  316. // State = 2 - Keep package and have iterated over dependencies
  317. safePackages := make(map[string]uint8)
  318. // provides stores a mapping from the provides name back to the original package name
  319. provides := make(stringset.MapStringSet)
  320. packages := localDB.PkgCache()
  321. // Mark explicit dependencies and enumerate the provides list
  322. setupResources := func(pkg alpm.Package) error {
  323. if pkg.Reason() == alpm.PkgReasonExplicit {
  324. safePackages[pkg.Name()] = 1
  325. } else {
  326. safePackages[pkg.Name()] = 0
  327. }
  328. _ = pkg.Provides().ForEach(func(dep alpm.Depend) error {
  329. provides.Add(dep.Name, pkg.Name())
  330. return nil
  331. })
  332. return nil
  333. }
  334. _ = packages.ForEach(setupResources)
  335. iterateAgain := true
  336. processDependencies := func(pkg alpm.Package) error {
  337. if state := safePackages[pkg.Name()]; state == 0 || state == 2 {
  338. return nil
  339. }
  340. safePackages[pkg.Name()] = 2
  341. // Update state for dependencies
  342. markDependencies := func(dep alpm.Depend) error {
  343. // Don't assume a dependency is installed
  344. state, ok := safePackages[dep.Name]
  345. if !ok {
  346. // Check if dep is a provides rather than actual package name
  347. if pset, ok2 := provides[dep.Name]; ok2 {
  348. for p := range pset {
  349. if safePackages[p] == 0 {
  350. iterateAgain = true
  351. safePackages[p] = 1
  352. }
  353. }
  354. }
  355. return nil
  356. }
  357. if state == 0 {
  358. iterateAgain = true
  359. safePackages[dep.Name] = 1
  360. }
  361. return nil
  362. }
  363. _ = pkg.Depends().ForEach(markDependencies)
  364. if !removeOptional {
  365. _ = pkg.OptionalDepends().ForEach(markDependencies)
  366. }
  367. return nil
  368. }
  369. for iterateAgain {
  370. iterateAgain = false
  371. _ = packages.ForEach(processDependencies)
  372. }
  373. // Build list of packages to be removed
  374. _ = packages.ForEach(func(pkg alpm.Package) error {
  375. if safePackages[pkg.Name()] == 0 {
  376. hanging = append(hanging, pkg.Name())
  377. }
  378. return nil
  379. })
  380. return hanging, err
  381. }
  382. func lastBuildTime() (time.Time, error) {
  383. var lastTime time.Time
  384. pkgs, _, _, _, err := filterPackages()
  385. if err != nil {
  386. return lastTime, err
  387. }
  388. for _, pkg := range pkgs {
  389. thisTime := pkg.BuildDate()
  390. if thisTime.After(lastTime) {
  391. lastTime = thisTime
  392. }
  393. }
  394. return lastTime, nil
  395. }
  396. // Statistics returns statistics about packages installed in system
  397. func statistics() (*struct {
  398. Totaln int
  399. Expln int
  400. TotalSize int64
  401. }, error) {
  402. var tS int64 // TotalSize
  403. var nPkg int
  404. var ePkg int
  405. localDB, err := alpmHandle.LocalDB()
  406. if err != nil {
  407. return nil, err
  408. }
  409. for _, pkg := range localDB.PkgCache().Slice() {
  410. tS += pkg.ISize()
  411. nPkg++
  412. if pkg.Reason() == 0 {
  413. ePkg++
  414. }
  415. }
  416. info := &struct {
  417. Totaln int
  418. Expln int
  419. TotalSize int64
  420. }{
  421. nPkg, ePkg, tS,
  422. }
  423. return info, err
  424. }
  425. // Queries the aur for information about specified packages.
  426. // All packages should be queried in a single rpc request except when the number
  427. // of packages exceeds the number set in config.RequestSplitN.
  428. // If the number does exceed config.RequestSplitN multiple rpc requests will be
  429. // performed concurrently.
  430. func aurInfo(names []string, warnings *aurWarnings) ([]*rpc.Pkg, error) {
  431. info := make([]*rpc.Pkg, 0, len(names))
  432. seen := make(map[string]int)
  433. var mux sync.Mutex
  434. var wg sync.WaitGroup
  435. var errs multierror.MultiError
  436. makeRequest := func(n, max int) {
  437. defer wg.Done()
  438. tempInfo, requestErr := rpc.Info(names[n:max])
  439. errs.Add(requestErr)
  440. if requestErr != nil {
  441. return
  442. }
  443. mux.Lock()
  444. for i := range tempInfo {
  445. info = append(info, &tempInfo[i])
  446. }
  447. mux.Unlock()
  448. }
  449. for n := 0; n < len(names); n += config.RequestSplitN {
  450. max := intrange.Min(len(names), n+config.RequestSplitN)
  451. wg.Add(1)
  452. go makeRequest(n, max)
  453. }
  454. wg.Wait()
  455. if err := errs.Return(); err != nil {
  456. return info, err
  457. }
  458. for k, pkg := range info {
  459. seen[pkg.Name] = k
  460. }
  461. for _, name := range names {
  462. i, ok := seen[name]
  463. if !ok && !warnings.Ignore.Get(name) {
  464. warnings.Missing = append(warnings.Missing, name)
  465. continue
  466. }
  467. pkg := info[i]
  468. if pkg.Maintainer == "" && !warnings.Ignore.Get(name) {
  469. warnings.Orphans = append(warnings.Orphans, name)
  470. }
  471. if pkg.OutOfDate != 0 && !warnings.Ignore.Get(name) {
  472. warnings.OutOfDate = append(warnings.OutOfDate, name)
  473. }
  474. }
  475. return info, nil
  476. }
  477. func aurInfoPrint(names []string) ([]*rpc.Pkg, error) {
  478. text.OperationInfoln(gotext.Get("Querying AUR..."))
  479. warnings := &aurWarnings{}
  480. info, err := aurInfo(names, warnings)
  481. if err != nil {
  482. return info, err
  483. }
  484. warnings.print()
  485. return info, nil
  486. }