query.go 11 KB

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