query.go 11 KB

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