query.go 11 KB

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