query.go 10 KB

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