query.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. "strings"
  6. "sync"
  7. "time"
  8. alpm "github.com/jguer/go-alpm"
  9. rpc "github.com/mikkeloscar/aur"
  10. )
  11. type aurWarnings struct {
  12. Orphans []string
  13. OutOfDate []string
  14. Missing []string
  15. }
  16. // Query is a collection of Results
  17. type aurQuery []rpc.Pkg
  18. // Query holds the results of a repository search.
  19. type repoQuery []alpm.Package
  20. func (q aurQuery) Len() int {
  21. return len(q)
  22. }
  23. func (q aurQuery) Less(i, j int) bool {
  24. var result bool
  25. switch config.SortBy {
  26. case "votes":
  27. result = q[i].NumVotes > q[j].NumVotes
  28. case "popularity":
  29. result = q[i].Popularity > q[j].Popularity
  30. case "name":
  31. result = lessRunes([]rune(q[i].Name), []rune(q[j].Name))
  32. case "base":
  33. result = lessRunes([]rune(q[i].PackageBase), []rune(q[j].PackageBase))
  34. case "submitted":
  35. result = q[i].FirstSubmitted < q[j].FirstSubmitted
  36. case "modified":
  37. result = q[i].LastModified < q[j].LastModified
  38. case "id":
  39. result = q[i].ID < q[j].ID
  40. case "baseid":
  41. result = q[i].PackageBaseID < q[j].PackageBaseID
  42. }
  43. if config.SortMode == BottomUp {
  44. return !result
  45. }
  46. return result
  47. }
  48. func (q aurQuery) Swap(i, j int) {
  49. q[i], q[j] = q[j], q[i]
  50. }
  51. // FilterPackages filters packages based on source and type from local repository.
  52. func filterPackages() (local []alpm.Package, remote []alpm.Package,
  53. localNames []string, remoteNames []string, err error) {
  54. localDb, err := alpmHandle.LocalDb()
  55. if err != nil {
  56. return
  57. }
  58. dbList, err := alpmHandle.SyncDbs()
  59. if err != nil {
  60. return
  61. }
  62. f := func(k alpm.Package) error {
  63. found := false
  64. // For each DB search for our secret package.
  65. _ = dbList.ForEach(func(d alpm.Db) error {
  66. if found {
  67. return nil
  68. }
  69. _, err := d.PkgByName(k.Name())
  70. if err == 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. if config.SortMode == BottomUp {
  150. if mode == ModeAUR || mode == ModeAny {
  151. aq.printSearch(1)
  152. }
  153. if mode == ModeRepo || mode == ModeAny {
  154. pq.printSearch()
  155. }
  156. } else {
  157. if mode == ModeRepo || mode == ModeAny {
  158. pq.printSearch()
  159. }
  160. if mode == ModeAUR || mode == ModeAny {
  161. aq.printSearch(1)
  162. }
  163. }
  164. if aurErr != nil {
  165. fmt.Printf("Error during AUR search: %s\n", aurErr)
  166. fmt.Println("Showing Repo packages only")
  167. }
  168. return nil
  169. }
  170. // SyncInfo serves as a pacman -Si for repo packages and AUR packages.
  171. func syncInfo(pkgS []string) (err error) {
  172. var info []*rpc.Pkg
  173. missing := false
  174. pkgS = removeInvalidTargets(pkgS)
  175. aurS, repoS, err := packageSlices(pkgS)
  176. if err != nil {
  177. return
  178. }
  179. if len(aurS) != 0 {
  180. noDb := make([]string, 0, len(aurS))
  181. for _, pkg := range aurS {
  182. _, name := splitDbFromName(pkg)
  183. noDb = append(noDb, name)
  184. }
  185. info, err = aurInfoPrint(noDb)
  186. if err != nil {
  187. missing = true
  188. fmt.Println(err)
  189. }
  190. }
  191. // Repo always goes first
  192. if len(repoS) != 0 {
  193. arguments := cmdArgs.copy()
  194. arguments.clearTargets()
  195. arguments.addTarget(repoS...)
  196. err = show(passToPacman(arguments))
  197. if err != nil {
  198. return
  199. }
  200. }
  201. if len(aurS) != len(info) {
  202. missing = true
  203. }
  204. if len(info) != 0 {
  205. for _, pkg := range info {
  206. PrintInfo(pkg)
  207. }
  208. }
  209. if missing {
  210. err = fmt.Errorf("")
  211. }
  212. return
  213. }
  214. // Search handles repo searches. Creates a RepoSearch struct.
  215. func queryRepo(pkgInputN []string) (s repoQuery, n int, err error) {
  216. dbList, err := alpmHandle.SyncDbs()
  217. if err != nil {
  218. return
  219. }
  220. // BottomUp functions
  221. initL := func(len int) int {
  222. if config.SortMode == TopDown {
  223. return 0
  224. }
  225. return len - 1
  226. }
  227. compL := func(len int, i int) bool {
  228. if config.SortMode == TopDown {
  229. return i < len
  230. }
  231. return i > -1
  232. }
  233. finalL := func(i int) int {
  234. if config.SortMode == TopDown {
  235. return i + 1
  236. }
  237. return i - 1
  238. }
  239. dbS := dbList.Slice()
  240. lenDbs := len(dbS)
  241. for f := initL(lenDbs); compL(lenDbs, f); f = finalL(f) {
  242. pkgS := dbS[f].PkgCache().Slice()
  243. lenPkgs := len(pkgS)
  244. for i := initL(lenPkgs); compL(lenPkgs, i); i = finalL(i) {
  245. match := true
  246. for _, pkgN := range pkgInputN {
  247. if !(strings.Contains(pkgS[i].Name(), pkgN) || strings.Contains(strings.ToLower(pkgS[i].Description()), pkgN)) {
  248. match = false
  249. break
  250. }
  251. }
  252. if match {
  253. n++
  254. s = append(s, pkgS[i])
  255. }
  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. _, err := db.PkgByName(name)
  278. if err == nil {
  279. found = true
  280. return fmt.Errorf("")
  281. }
  282. return nil
  283. })
  284. if !found {
  285. _, errdb := dbList.PkgCachebyGroup(name)
  286. found = errdb == nil
  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(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 time time.Time
  375. pkgs, _, _, _, err := filterPackages()
  376. if err != nil {
  377. return time, err
  378. }
  379. for _, pkg := range pkgs {
  380. thisTime := pkg.BuildDate()
  381. if thisTime.After(time) {
  382. time = thisTime
  383. }
  384. }
  385. return time, 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 err error
  427. makeRequest := func(n, max int) {
  428. defer wg.Done()
  429. tempInfo, requestErr := rpc.Info(names[n:max])
  430. if err != nil {
  431. return
  432. }
  433. if requestErr != nil {
  434. err = requestErr
  435. return
  436. }
  437. mux.Lock()
  438. for _, _i := range tempInfo {
  439. i := _i
  440. info = append(info, &i)
  441. }
  442. mux.Unlock()
  443. }
  444. for n := 0; n < len(names); n += config.RequestSplitN {
  445. max := min(len(names), n+config.RequestSplitN)
  446. wg.Add(1)
  447. go makeRequest(n, max)
  448. }
  449. wg.Wait()
  450. if err != nil {
  451. return info, err
  452. }
  453. for k, pkg := range info {
  454. seen[pkg.Name] = k
  455. }
  456. for _, name := range names {
  457. i, ok := seen[name]
  458. if !ok {
  459. warnings.Missing = append(warnings.Missing, name)
  460. continue
  461. }
  462. pkg := info[i]
  463. if pkg.Maintainer == "" {
  464. warnings.Orphans = append(warnings.Orphans, name)
  465. }
  466. if pkg.OutOfDate != 0 {
  467. warnings.OutOfDate = append(warnings.OutOfDate, name)
  468. }
  469. }
  470. return info, nil
  471. }
  472. func aurInfoPrint(names []string) ([]*rpc.Pkg, error) {
  473. fmt.Println(bold(cyan("::") + bold(" Querying AUR...")))
  474. warnings := &aurWarnings{}
  475. info, err := aurInfo(names, warnings)
  476. if err != nil {
  477. return info, err
  478. }
  479. warnings.print()
  480. return info, nil
  481. }