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