query.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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, err error) {
  216. dbList, err := alpmHandle.SyncDbs()
  217. if err != nil {
  218. return
  219. }
  220. dbList.ForEach(func(db alpm.Db) error {
  221. if len(pkgInputN) == 0 {
  222. pkgs := db.PkgCache()
  223. s = append(s, pkgs.Slice()...)
  224. } else {
  225. pkgs := db.Search(pkgInputN)
  226. s = append(s, pkgs.Slice()...)
  227. }
  228. return nil
  229. })
  230. if config.SortMode == BottomUp {
  231. for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
  232. s[i], s[j] = s[j], s[i]
  233. }
  234. }
  235. return
  236. }
  237. // PackageSlices separates an input slice into aur and repo slices
  238. func packageSlices(toCheck []string) (aur []string, repo []string, err error) {
  239. dbList, err := alpmHandle.SyncDbs()
  240. if err != nil {
  241. return
  242. }
  243. for _, _pkg := range toCheck {
  244. db, name := splitDbFromName(_pkg)
  245. found := false
  246. if db == "aur" || mode == ModeAUR {
  247. aur = append(aur, _pkg)
  248. continue
  249. } else if db != "" || mode == ModeRepo {
  250. repo = append(repo, _pkg)
  251. continue
  252. }
  253. _ = dbList.ForEach(func(db alpm.Db) error {
  254. _, err := db.PkgByName(name)
  255. if err == nil {
  256. found = true
  257. return fmt.Errorf("")
  258. }
  259. return nil
  260. })
  261. if !found {
  262. _, errdb := dbList.PkgCachebyGroup(name)
  263. found = errdb == nil
  264. }
  265. if found {
  266. repo = append(repo, _pkg)
  267. } else {
  268. aur = append(aur, _pkg)
  269. }
  270. }
  271. return
  272. }
  273. // HangingPackages returns a list of packages installed as deps
  274. // and unneeded by the system
  275. // removeOptional decides whether optional dependencies are counted or not
  276. func hangingPackages(removeOptional bool) (hanging []string, err error) {
  277. localDb, err := alpmHandle.LocalDb()
  278. if err != nil {
  279. return
  280. }
  281. // safePackages represents every package in the system in one of 3 states
  282. // State = 0 - Remove package from the system
  283. // State = 1 - Keep package in the system; need to iterate over dependencies
  284. // State = 2 - Keep package and have iterated over dependencies
  285. safePackages := make(map[string]uint8)
  286. // provides stores a mapping from the provides name back to the original package name
  287. provides := make(mapStringSet)
  288. packages := localDb.PkgCache()
  289. // Mark explicit dependencies and enumerate the provides list
  290. setupResources := func(pkg alpm.Package) error {
  291. if pkg.Reason() == alpm.PkgReasonExplicit {
  292. safePackages[pkg.Name()] = 1
  293. } else {
  294. safePackages[pkg.Name()] = 0
  295. }
  296. pkg.Provides().ForEach(func(dep alpm.Depend) error {
  297. provides.Add(dep.Name, pkg.Name())
  298. return nil
  299. })
  300. return nil
  301. }
  302. packages.ForEach(setupResources)
  303. iterateAgain := true
  304. processDependencies := func(pkg alpm.Package) error {
  305. if state := safePackages[pkg.Name()]; state == 0 || state == 2 {
  306. return nil
  307. }
  308. safePackages[pkg.Name()] = 2
  309. // Update state for dependencies
  310. markDependencies := func(dep alpm.Depend) error {
  311. // Don't assume a dependency is installed
  312. state, ok := safePackages[dep.Name]
  313. if !ok {
  314. // Check if dep is a provides rather than actual package name
  315. if pset, ok2 := provides[dep.Name]; ok2 {
  316. for p := range pset {
  317. if safePackages[p] == 0 {
  318. iterateAgain = true
  319. safePackages[p] = 1
  320. }
  321. }
  322. }
  323. return nil
  324. }
  325. if state == 0 {
  326. iterateAgain = true
  327. safePackages[dep.Name] = 1
  328. }
  329. return nil
  330. }
  331. pkg.Depends().ForEach(markDependencies)
  332. if !removeOptional {
  333. pkg.OptionalDepends().ForEach(markDependencies)
  334. }
  335. return nil
  336. }
  337. for iterateAgain {
  338. iterateAgain = false
  339. packages.ForEach(processDependencies)
  340. }
  341. // Build list of packages to be removed
  342. packages.ForEach(func(pkg alpm.Package) error {
  343. if safePackages[pkg.Name()] == 0 {
  344. hanging = append(hanging, pkg.Name())
  345. }
  346. return nil
  347. })
  348. return
  349. }
  350. func lastBuildTime() (time.Time, error) {
  351. var time time.Time
  352. pkgs, _, _, _, err := filterPackages()
  353. if err != nil {
  354. return time, err
  355. }
  356. for _, pkg := range pkgs {
  357. thisTime := pkg.BuildDate()
  358. if thisTime.After(time) {
  359. time = thisTime
  360. }
  361. }
  362. return time, nil
  363. }
  364. // Statistics returns statistics about packages installed in system
  365. func statistics() (info struct {
  366. Totaln int
  367. Expln int
  368. TotalSize int64
  369. }, err error) {
  370. var tS int64 // TotalSize
  371. var nPkg int
  372. var ePkg int
  373. localDb, err := alpmHandle.LocalDb()
  374. if err != nil {
  375. return
  376. }
  377. for _, pkg := range localDb.PkgCache().Slice() {
  378. tS += pkg.ISize()
  379. nPkg++
  380. if pkg.Reason() == 0 {
  381. ePkg++
  382. }
  383. }
  384. info = struct {
  385. Totaln int
  386. Expln int
  387. TotalSize int64
  388. }{
  389. nPkg, ePkg, tS,
  390. }
  391. return
  392. }
  393. // Queries the aur for information about specified packages.
  394. // All packages should be queried in a single rpc request except when the number
  395. // of packages exceeds the number set in config.RequestSplitN.
  396. // If the number does exceed config.RequestSplitN multiple rpc requests will be
  397. // performed concurrently.
  398. func aurInfo(names []string, warnings *aurWarnings) ([]*rpc.Pkg, error) {
  399. info := make([]*rpc.Pkg, 0, len(names))
  400. seen := make(map[string]int)
  401. var mux sync.Mutex
  402. var wg sync.WaitGroup
  403. var errs MultiError
  404. makeRequest := func(n, max int) {
  405. defer wg.Done()
  406. tempInfo, requestErr := rpc.Info(names[n:max])
  407. errs.Add(requestErr)
  408. if requestErr != nil {
  409. return
  410. }
  411. mux.Lock()
  412. for _, _i := range tempInfo {
  413. i := _i
  414. info = append(info, &i)
  415. }
  416. mux.Unlock()
  417. }
  418. for n := 0; n < len(names); n += config.RequestSplitN {
  419. max := min(len(names), n+config.RequestSplitN)
  420. wg.Add(1)
  421. go makeRequest(n, max)
  422. }
  423. wg.Wait()
  424. if err := errs.Return(); err != nil {
  425. return info, err
  426. }
  427. for k, pkg := range info {
  428. seen[pkg.Name] = k
  429. }
  430. for _, name := range names {
  431. i, ok := seen[name]
  432. if !ok {
  433. warnings.Missing = append(warnings.Missing, name)
  434. continue
  435. }
  436. pkg := info[i]
  437. if pkg.Maintainer == "" {
  438. warnings.Orphans = append(warnings.Orphans, name)
  439. }
  440. if pkg.OutOfDate != 0 {
  441. warnings.OutOfDate = append(warnings.OutOfDate, name)
  442. }
  443. }
  444. return info, nil
  445. }
  446. func aurInfoPrint(names []string) ([]*rpc.Pkg, error) {
  447. fmt.Println(bold(cyan("::") + bold(" Querying AUR...")))
  448. warnings := &aurWarnings{}
  449. info, err := aurInfo(names, warnings)
  450. if err != nil {
  451. return info, err
  452. }
  453. warnings.print()
  454. return info, nil
  455. }