query.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "sort"
  6. "strings"
  7. "sync"
  8. "time"
  9. alpm "github.com/jguer/go-alpm"
  10. rpc "github.com/mikkeloscar/aur"
  11. )
  12. type aurWarnings struct {
  13. Orphans []string
  14. OutOfDate []string
  15. Missing []string
  16. }
  17. // Query is a collection of Results
  18. type aurQuery []rpc.Pkg
  19. // Query holds the results of a repository search.
  20. type repoQuery []alpm.Package
  21. func (q aurQuery) Len() int {
  22. return len(q)
  23. }
  24. func (q aurQuery) Less(i, j int) bool {
  25. var result bool
  26. switch config.SortBy {
  27. case "votes":
  28. result = q[i].NumVotes > q[j].NumVotes
  29. case "popularity":
  30. result = q[i].Popularity > q[j].Popularity
  31. case "name":
  32. result = lessRunes([]rune(q[i].Name), []rune(q[j].Name))
  33. case "base":
  34. result = lessRunes([]rune(q[i].PackageBase), []rune(q[j].PackageBase))
  35. case "submitted":
  36. result = q[i].FirstSubmitted < q[j].FirstSubmitted
  37. case "modified":
  38. result = q[i].LastModified < q[j].LastModified
  39. case "id":
  40. result = q[i].ID < q[j].ID
  41. case "baseid":
  42. result = q[i].PackageBaseID < q[j].PackageBaseID
  43. }
  44. if config.SortMode == bottomUp {
  45. return !result
  46. }
  47. return result
  48. }
  49. func (q aurQuery) Swap(i, j int) {
  50. q[i], q[j] = q[j], q[i]
  51. }
  52. // FilterPackages filters packages based on source and type from local repository.
  53. func filterPackages() (local []alpm.Package, remote []alpm.Package,
  54. localNames []string, remoteNames []string, err error) {
  55. localDB, err := alpmHandle.LocalDB()
  56. if err != nil {
  57. return
  58. }
  59. dbList, err := alpmHandle.SyncDBs()
  60. if err != nil {
  61. return
  62. }
  63. f := func(k alpm.Package) error {
  64. found := false
  65. // For each DB search for our secret package.
  66. _ = dbList.ForEach(func(d alpm.DB) error {
  67. if found {
  68. return nil
  69. }
  70. _, err := d.Pkg(k.Name())
  71. if err == nil {
  72. found = true
  73. local = append(local, k)
  74. localNames = append(localNames, k.Name())
  75. }
  76. return nil
  77. })
  78. if !found {
  79. remote = append(remote, k)
  80. remoteNames = append(remoteNames, k.Name())
  81. }
  82. return nil
  83. }
  84. err = localDB.PkgCache().ForEach(f)
  85. return
  86. }
  87. // NarrowSearch searches AUR and narrows based on subarguments
  88. func narrowSearch(pkgS []string, sortS bool) (aurQuery, error) {
  89. var r []rpc.Pkg
  90. var err error
  91. var usedIndex int
  92. if len(pkgS) == 0 {
  93. return nil, nil
  94. }
  95. for i, word := range pkgS {
  96. r, err = rpc.Search(word)
  97. if err == nil {
  98. usedIndex = i
  99. break
  100. }
  101. }
  102. if err != nil {
  103. return nil, err
  104. }
  105. if len(pkgS) == 1 {
  106. if sortS {
  107. sort.Sort(aurQuery(r))
  108. }
  109. return r, err
  110. }
  111. var aq aurQuery
  112. var n int
  113. for _, res := range r {
  114. match := true
  115. for i, pkgN := range pkgS {
  116. if usedIndex == i {
  117. continue
  118. }
  119. if !(strings.Contains(res.Name, pkgN) || strings.Contains(strings.ToLower(res.Description), pkgN)) {
  120. match = false
  121. break
  122. }
  123. }
  124. if match {
  125. n++
  126. aq = append(aq, res)
  127. }
  128. }
  129. if sortS {
  130. sort.Sort(aq)
  131. }
  132. return aq, err
  133. }
  134. // SyncSearch presents a query to the local repos and to the AUR.
  135. func syncSearch(pkgS []string) (err error) {
  136. pkgS = removeInvalidTargets(pkgS)
  137. var aurErr error
  138. var repoErr error
  139. var aq aurQuery
  140. var pq repoQuery
  141. if mode == modeAUR || mode == modeAny {
  142. aq, aurErr = narrowSearch(pkgS, true)
  143. }
  144. if mode == modeRepo || mode == modeAny {
  145. pq, repoErr = queryRepo(pkgS)
  146. if repoErr != nil {
  147. return err
  148. }
  149. }
  150. if config.SortMode == bottomUp {
  151. if mode == modeAUR || mode == modeAny {
  152. aq.printSearch(1)
  153. }
  154. if mode == modeRepo || mode == modeAny {
  155. pq.printSearch()
  156. }
  157. } else {
  158. if mode == modeRepo || mode == modeAny {
  159. pq.printSearch()
  160. }
  161. if mode == modeAUR || mode == modeAny {
  162. aq.printSearch(1)
  163. }
  164. }
  165. if aurErr != nil {
  166. fmt.Fprintf(os.Stderr, "Error during AUR search: %s\n", aurErr)
  167. fmt.Fprintln(os.Stderr, "Showing Repo packages only")
  168. }
  169. return nil
  170. }
  171. // SyncInfo serves as a pacman -Si for repo packages and AUR packages.
  172. func syncInfo(pkgS []string) (err error) {
  173. var info []*rpc.Pkg
  174. missing := false
  175. pkgS = removeInvalidTargets(pkgS)
  176. aurS, repoS, err := packageSlices(pkgS)
  177. if err != nil {
  178. return
  179. }
  180. if len(aurS) != 0 {
  181. noDB := make([]string, 0, len(aurS))
  182. for _, pkg := range aurS {
  183. _, name := splitDBFromName(pkg)
  184. noDB = append(noDB, name)
  185. }
  186. info, err = aurInfoPrint(noDB)
  187. if err != nil {
  188. missing = true
  189. fmt.Fprintln(os.Stderr, err)
  190. }
  191. }
  192. // Repo always goes first
  193. if len(repoS) != 0 {
  194. arguments := cmdArgs.copy()
  195. arguments.clearTargets()
  196. arguments.addTarget(repoS...)
  197. err = show(passToPacman(arguments))
  198. if err != nil {
  199. return
  200. }
  201. }
  202. if len(aurS) != len(info) {
  203. missing = true
  204. }
  205. if len(info) != 0 {
  206. for _, pkg := range info {
  207. PrintInfo(pkg)
  208. }
  209. }
  210. if missing {
  211. err = fmt.Errorf("")
  212. }
  213. return
  214. }
  215. // Search handles repo searches. Creates a RepoSearch struct.
  216. func queryRepo(pkgInputN []string) (s repoQuery, err error) {
  217. dbList, err := alpmHandle.SyncDBs()
  218. if err != nil {
  219. return
  220. }
  221. dbList.ForEach(func(db alpm.DB) error {
  222. if len(pkgInputN) == 0 {
  223. pkgs := db.PkgCache()
  224. s = append(s, pkgs.Slice()...)
  225. } else {
  226. pkgs := db.Search(pkgInputN)
  227. s = append(s, pkgs.Slice()...)
  228. }
  229. return nil
  230. })
  231. if config.SortMode == bottomUp {
  232. for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
  233. s[i], s[j] = s[j], s[i]
  234. }
  235. }
  236. return
  237. }
  238. // PackageSlices separates an input slice into aur and repo slices
  239. func packageSlices(toCheck []string) (aur []string, repo []string, err error) {
  240. dbList, err := alpmHandle.SyncDBs()
  241. if err != nil {
  242. return
  243. }
  244. for _, _pkg := range toCheck {
  245. db, name := splitDBFromName(_pkg)
  246. found := false
  247. if db == "aur" || mode == modeAUR {
  248. aur = append(aur, _pkg)
  249. continue
  250. } else if db != "" || mode == modeRepo {
  251. repo = append(repo, _pkg)
  252. continue
  253. }
  254. _ = dbList.ForEach(func(db alpm.DB) error {
  255. _, err := db.Pkg(name)
  256. if err == nil {
  257. found = true
  258. return fmt.Errorf("")
  259. }
  260. return nil
  261. })
  262. if !found {
  263. _, errdb := dbList.FindGroupPkgs(name)
  264. found = errdb == nil
  265. }
  266. if found {
  267. repo = append(repo, _pkg)
  268. } else {
  269. aur = append(aur, _pkg)
  270. }
  271. }
  272. return
  273. }
  274. // HangingPackages returns a list of packages installed as deps
  275. // and unneeded by the system
  276. // removeOptional decides whether optional dependencies are counted or not
  277. func hangingPackages(removeOptional bool) (hanging []string, err error) {
  278. localDB, err := alpmHandle.LocalDB()
  279. if err != nil {
  280. return
  281. }
  282. // safePackages represents every package in the system in one of 3 states
  283. // State = 0 - Remove package from the system
  284. // State = 1 - Keep package in the system; need to iterate over dependencies
  285. // State = 2 - Keep package and have iterated over dependencies
  286. safePackages := make(map[string]uint8)
  287. // provides stores a mapping from the provides name back to the original package name
  288. provides := make(mapStringSet)
  289. packages := localDB.PkgCache()
  290. // Mark explicit dependencies and enumerate the provides list
  291. setupResources := func(pkg alpm.Package) error {
  292. if pkg.Reason() == alpm.PkgReasonExplicit {
  293. safePackages[pkg.Name()] = 1
  294. } else {
  295. safePackages[pkg.Name()] = 0
  296. }
  297. pkg.Provides().ForEach(func(dep alpm.Depend) error {
  298. provides.Add(dep.Name, pkg.Name())
  299. return nil
  300. })
  301. return nil
  302. }
  303. packages.ForEach(setupResources)
  304. iterateAgain := true
  305. processDependencies := func(pkg alpm.Package) error {
  306. if state := safePackages[pkg.Name()]; state == 0 || state == 2 {
  307. return nil
  308. }
  309. safePackages[pkg.Name()] = 2
  310. // Update state for dependencies
  311. markDependencies := func(dep alpm.Depend) error {
  312. // Don't assume a dependency is installed
  313. state, ok := safePackages[dep.Name]
  314. if !ok {
  315. // Check if dep is a provides rather than actual package name
  316. if pset, ok2 := provides[dep.Name]; ok2 {
  317. for p := range pset {
  318. if safePackages[p] == 0 {
  319. iterateAgain = true
  320. safePackages[p] = 1
  321. }
  322. }
  323. }
  324. return nil
  325. }
  326. if state == 0 {
  327. iterateAgain = true
  328. safePackages[dep.Name] = 1
  329. }
  330. return nil
  331. }
  332. pkg.Depends().ForEach(markDependencies)
  333. if !removeOptional {
  334. pkg.OptionalDepends().ForEach(markDependencies)
  335. }
  336. return nil
  337. }
  338. for iterateAgain {
  339. iterateAgain = false
  340. packages.ForEach(processDependencies)
  341. }
  342. // Build list of packages to be removed
  343. packages.ForEach(func(pkg alpm.Package) error {
  344. if safePackages[pkg.Name()] == 0 {
  345. hanging = append(hanging, pkg.Name())
  346. }
  347. return nil
  348. })
  349. return
  350. }
  351. func lastBuildTime() (time.Time, error) {
  352. var time time.Time
  353. pkgs, _, _, _, err := filterPackages()
  354. if err != nil {
  355. return time, err
  356. }
  357. for _, pkg := range pkgs {
  358. thisTime := pkg.BuildDate()
  359. if thisTime.After(time) {
  360. time = thisTime
  361. }
  362. }
  363. return time, nil
  364. }
  365. // Statistics returns statistics about packages installed in system
  366. func statistics() (info struct {
  367. Totaln int
  368. Expln int
  369. TotalSize int64
  370. }, err error) {
  371. var tS int64 // TotalSize
  372. var nPkg int
  373. var ePkg int
  374. localDB, err := alpmHandle.LocalDB()
  375. if err != nil {
  376. return
  377. }
  378. for _, pkg := range localDB.PkgCache().Slice() {
  379. tS += pkg.ISize()
  380. nPkg++
  381. if pkg.Reason() == 0 {
  382. ePkg++
  383. }
  384. }
  385. info = struct {
  386. Totaln int
  387. Expln int
  388. TotalSize int64
  389. }{
  390. nPkg, ePkg, tS,
  391. }
  392. return
  393. }
  394. // Queries the aur for information about specified packages.
  395. // All packages should be queried in a single rpc request except when the number
  396. // of packages exceeds the number set in config.RequestSplitN.
  397. // If the number does exceed config.RequestSplitN multiple rpc requests will be
  398. // performed concurrently.
  399. func aurInfo(names []string, warnings *aurWarnings) ([]*rpc.Pkg, error) {
  400. info := make([]*rpc.Pkg, 0, len(names))
  401. seen := make(map[string]int)
  402. var mux sync.Mutex
  403. var wg sync.WaitGroup
  404. var errs MultiError
  405. makeRequest := func(n, max int) {
  406. defer wg.Done()
  407. tempInfo, requestErr := rpc.Info(names[n:max])
  408. errs.Add(requestErr)
  409. if requestErr != nil {
  410. return
  411. }
  412. mux.Lock()
  413. for _, _i := range tempInfo {
  414. i := _i
  415. info = append(info, &i)
  416. }
  417. mux.Unlock()
  418. }
  419. for n := 0; n < len(names); n += config.RequestSplitN {
  420. max := min(len(names), n+config.RequestSplitN)
  421. wg.Add(1)
  422. go makeRequest(n, max)
  423. }
  424. wg.Wait()
  425. if err := errs.Return(); err != nil {
  426. return info, err
  427. }
  428. for k, pkg := range info {
  429. seen[pkg.Name] = k
  430. }
  431. for _, name := range names {
  432. i, ok := seen[name]
  433. if !ok {
  434. warnings.Missing = append(warnings.Missing, name)
  435. continue
  436. }
  437. pkg := info[i]
  438. if pkg.Maintainer == "" {
  439. warnings.Orphans = append(warnings.Orphans, name)
  440. }
  441. if pkg.OutOfDate != 0 {
  442. warnings.OutOfDate = append(warnings.OutOfDate, name)
  443. }
  444. }
  445. return info, nil
  446. }
  447. func aurInfoPrint(names []string) ([]*rpc.Pkg, error) {
  448. fmt.Println(bold(cyan("::") + bold(" Querying AUR...")))
  449. warnings := &aurWarnings{}
  450. info, err := aurInfo(names, warnings)
  451. if err != nil {
  452. return info, err
  453. }
  454. warnings.print()
  455. return info, nil
  456. }