query.go 11 KB

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