query.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. aq, aurErr := narrowSearch(pkgS, true)
  136. pq, _, err := queryRepo(pkgS)
  137. if err != nil {
  138. return err
  139. }
  140. if config.SortMode == BottomUp {
  141. aq.printSearch(1)
  142. pq.printSearch()
  143. } else {
  144. pq.printSearch()
  145. aq.printSearch(1)
  146. }
  147. if aurErr != nil {
  148. fmt.Printf("Error during AUR search: %s\n", aurErr)
  149. fmt.Println("Showing Repo packags only")
  150. }
  151. return nil
  152. }
  153. // SyncInfo serves as a pacman -Si for repo packages and AUR packages.
  154. func syncInfo(pkgS []string) (err error) {
  155. var info []*rpc.Pkg
  156. missing := false
  157. pkgS = removeInvalidTargets(pkgS)
  158. aurS, repoS, err := packageSlices(pkgS)
  159. if err != nil {
  160. return
  161. }
  162. if len(aurS) != 0 {
  163. noDb := make([]string, 0, len(aurS))
  164. for _, pkg := range aurS {
  165. _, name := splitDbFromName(pkg)
  166. noDb = append(noDb, name)
  167. }
  168. info, err = aurInfoPrint(noDb)
  169. if err != nil {
  170. missing = true
  171. fmt.Println(err)
  172. }
  173. }
  174. // Repo always goes first
  175. if len(repoS) != 0 {
  176. arguments := cmdArgs.copy()
  177. arguments.clearTargets()
  178. arguments.addTarget(repoS...)
  179. err = passToPacman(arguments)
  180. if err != nil {
  181. return
  182. }
  183. }
  184. if len(aurS) != len(info) {
  185. missing = true
  186. }
  187. if len(info) != 0 {
  188. for _, pkg := range info {
  189. PrintInfo(pkg)
  190. }
  191. }
  192. if missing {
  193. err = fmt.Errorf("")
  194. }
  195. return
  196. }
  197. // Search handles repo searches. Creates a RepoSearch struct.
  198. func queryRepo(pkgInputN []string) (s repoQuery, n int, err error) {
  199. dbList, err := alpmHandle.SyncDbs()
  200. if err != nil {
  201. return
  202. }
  203. // BottomUp functions
  204. initL := func(len int) int {
  205. if config.SortMode == TopDown {
  206. return 0
  207. }
  208. return len - 1
  209. }
  210. compL := func(len int, i int) bool {
  211. if config.SortMode == TopDown {
  212. return i < len
  213. }
  214. return i > -1
  215. }
  216. finalL := func(i int) int {
  217. if config.SortMode == TopDown {
  218. return i + 1
  219. }
  220. return i - 1
  221. }
  222. dbS := dbList.Slice()
  223. lenDbs := len(dbS)
  224. for f := initL(lenDbs); compL(lenDbs, f); f = finalL(f) {
  225. pkgS := dbS[f].PkgCache().Slice()
  226. lenPkgs := len(pkgS)
  227. for i := initL(lenPkgs); compL(lenPkgs, i); i = finalL(i) {
  228. match := true
  229. for _, pkgN := range pkgInputN {
  230. if !(strings.Contains(pkgS[i].Name(), pkgN) || strings.Contains(strings.ToLower(pkgS[i].Description()), pkgN)) {
  231. match = false
  232. break
  233. }
  234. }
  235. if match {
  236. n++
  237. s = append(s, pkgS[i])
  238. }
  239. }
  240. }
  241. return
  242. }
  243. // PackageSlices separates an input slice into aur and repo slices
  244. func packageSlices(toCheck []string) (aur []string, repo []string, err error) {
  245. dbList, err := alpmHandle.SyncDbs()
  246. if err != nil {
  247. return
  248. }
  249. for _, _pkg := range toCheck {
  250. db, name := splitDbFromName(_pkg)
  251. found := false
  252. if db == "aur" || mode == ModeAUR {
  253. aur = append(aur, _pkg)
  254. continue
  255. } else if db != "" || mode == ModeRepo {
  256. repo = append(repo, _pkg)
  257. continue
  258. }
  259. _ = dbList.ForEach(func(db alpm.Db) error {
  260. _, err := db.PkgByName(name)
  261. if err == nil {
  262. found = true
  263. return fmt.Errorf("")
  264. }
  265. return nil
  266. })
  267. if !found {
  268. _, errdb := dbList.PkgCachebyGroup(name)
  269. found = errdb == nil
  270. }
  271. if found {
  272. repo = append(repo, _pkg)
  273. } else {
  274. aur = append(aur, _pkg)
  275. }
  276. }
  277. return
  278. }
  279. // HangingPackages returns a list of packages installed as deps
  280. // and unneeded by the system
  281. // removeOptional decides whether optional dependencies are counted or not
  282. func hangingPackages(removeOptional bool) (hanging []string, err error) {
  283. localDb, err := alpmHandle.LocalDb()
  284. if err != nil {
  285. return
  286. }
  287. // safePackages represents every package in the system in one of 3 states
  288. // State = 0 - Remove package from the system
  289. // State = 1 - Keep package in the system; need to iterate over dependencies
  290. // State = 2 - Keep package and have iterated over dependencies
  291. safePackages := make(map[string]uint8)
  292. // provides stores a mapping from the provides name back to the original package name
  293. provides := make(mapStringSet)
  294. packages := localDb.PkgCache()
  295. // Mark explicit dependencies and enumerate the provides list
  296. setupResources := func(pkg alpm.Package) error {
  297. if pkg.Reason() == alpm.PkgReasonExplicit {
  298. safePackages[pkg.Name()] = 1
  299. } else {
  300. safePackages[pkg.Name()] = 0
  301. }
  302. pkg.Provides().ForEach(func(dep alpm.Depend) error {
  303. provides.Add(dep.Name, pkg.Name())
  304. return nil
  305. })
  306. return nil
  307. }
  308. packages.ForEach(setupResources)
  309. iterateAgain := true
  310. processDependencies := func(pkg alpm.Package) error {
  311. if state := safePackages[pkg.Name()]; state == 0 || state == 2 {
  312. return nil
  313. }
  314. safePackages[pkg.Name()] = 2
  315. // Update state for dependencies
  316. markDependencies := func(dep alpm.Depend) error {
  317. // Don't assume a dependency is installed
  318. state, ok := safePackages[dep.Name]
  319. if !ok {
  320. // Check if dep is a provides rather than actual package name
  321. if pset, ok2 := provides[dep.Name]; ok2 {
  322. for p := range pset {
  323. if safePackages[p] == 0 {
  324. iterateAgain = true
  325. safePackages[p] = 1
  326. }
  327. }
  328. }
  329. return nil
  330. }
  331. if state == 0 {
  332. iterateAgain = true
  333. safePackages[dep.Name] = 1
  334. }
  335. return nil
  336. }
  337. pkg.Depends().ForEach(markDependencies)
  338. if !removeOptional {
  339. pkg.OptionalDepends().ForEach(markDependencies)
  340. }
  341. return nil
  342. }
  343. for iterateAgain {
  344. iterateAgain = false
  345. packages.ForEach(processDependencies)
  346. }
  347. // Build list of packages to be removed
  348. packages.ForEach(func(pkg alpm.Package) error {
  349. if safePackages[pkg.Name()] == 0 {
  350. hanging = append(hanging, pkg.Name())
  351. }
  352. return nil
  353. })
  354. return
  355. }
  356. func lastBuildTime() (time.Time, error) {
  357. var time time.Time
  358. pkgs, _, _, _, err := filterPackages()
  359. if err != nil {
  360. return time, err
  361. }
  362. for _, pkg := range pkgs {
  363. thisTime := pkg.BuildDate()
  364. if thisTime.After(time) {
  365. time = thisTime
  366. }
  367. }
  368. return time, nil
  369. }
  370. // Statistics returns statistics about packages installed in system
  371. func statistics() (info struct {
  372. Totaln int
  373. Expln int
  374. TotalSize int64
  375. }, err error) {
  376. var tS int64 // TotalSize
  377. var nPkg int
  378. var ePkg int
  379. localDb, err := alpmHandle.LocalDb()
  380. if err != nil {
  381. return
  382. }
  383. for _, pkg := range localDb.PkgCache().Slice() {
  384. tS += pkg.ISize()
  385. nPkg++
  386. if pkg.Reason() == 0 {
  387. ePkg++
  388. }
  389. }
  390. info = struct {
  391. Totaln int
  392. Expln int
  393. TotalSize int64
  394. }{
  395. nPkg, ePkg, tS,
  396. }
  397. return
  398. }
  399. // Queries the aur for information about specified packages.
  400. // All packages should be queried in a single rpc request except when the number
  401. // of packages exceeds the number set in config.RequestSplitN.
  402. // If the number does exceed config.RequestSplitN multiple rpc requests will be
  403. // performed concurrently.
  404. func aurInfo(names []string, warnings *aurWarnings) ([]*rpc.Pkg, error) {
  405. info := make([]*rpc.Pkg, 0, len(names))
  406. seen := make(map[string]int)
  407. var mux sync.Mutex
  408. var wg sync.WaitGroup
  409. var err error
  410. makeRequest := func(n, max int) {
  411. defer wg.Done()
  412. tempInfo, requestErr := rpc.Info(names[n:max])
  413. if err != nil {
  414. return
  415. }
  416. if requestErr != nil {
  417. err = requestErr
  418. return
  419. }
  420. mux.Lock()
  421. for _, _i := range tempInfo {
  422. i := _i
  423. info = append(info, &i)
  424. }
  425. mux.Unlock()
  426. }
  427. for n := 0; n < len(names); n += config.RequestSplitN {
  428. max := min(len(names), n+config.RequestSplitN)
  429. wg.Add(1)
  430. go makeRequest(n, max)
  431. }
  432. wg.Wait()
  433. if err != nil {
  434. return info, err
  435. }
  436. for k, pkg := range info {
  437. seen[pkg.Name] = k
  438. }
  439. for _, name := range names {
  440. i, ok := seen[name]
  441. if !ok {
  442. warnings.Missing = append(warnings.Missing, name)
  443. continue
  444. }
  445. pkg := info[i]
  446. if pkg.Maintainer == "" {
  447. warnings.Orphans = append(warnings.Orphans, name)
  448. }
  449. if pkg.OutOfDate != 0 {
  450. warnings.OutOfDate = append(warnings.OutOfDate, name)
  451. }
  452. }
  453. return info, nil
  454. }
  455. func aurInfoPrint(names []string) ([]*rpc.Pkg, error) {
  456. fmt.Println(bold(cyan("::") + bold(" Querying AUR...")))
  457. warnings := &aurWarnings{}
  458. info, err := aurInfo(names, warnings)
  459. if err != nil {
  460. return info, err
  461. }
  462. warnings.print()
  463. return info, nil
  464. }