query.go 11 KB

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