query.go 11 KB

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