query.go 11 KB

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