print.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "strconv"
  10. "strings"
  11. "time"
  12. rpc "github.com/mikkeloscar/aur"
  13. )
  14. const arrow = "==>"
  15. const smallArrow = " ->"
  16. func (warnings *aurWarnings) Print() {
  17. if len(warnings.Missing) > 0 {
  18. fmt.Print(bold(yellow(smallArrow)) + " Missing AUR Packages:")
  19. for _, name := range warnings.Missing {
  20. fmt.Print(" " + cyan(name))
  21. }
  22. fmt.Println()
  23. }
  24. if len(warnings.Orphans) > 0 {
  25. fmt.Print(bold(yellow(smallArrow)) + " Orphaned AUR Packages:")
  26. for _, name := range warnings.Orphans {
  27. fmt.Print(" " + cyan(name))
  28. }
  29. fmt.Println()
  30. }
  31. if len(warnings.OutOfDate) > 0 {
  32. fmt.Print(bold(yellow(smallArrow)) + " Out Of Date AUR Packages:")
  33. for _, name := range warnings.OutOfDate {
  34. fmt.Print(" " + cyan(name))
  35. }
  36. fmt.Println()
  37. }
  38. }
  39. // human method returns results in human readable format.
  40. func human(size int64) string {
  41. floatsize := float32(size)
  42. units := [...]string{"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"}
  43. for _, unit := range units {
  44. if floatsize < 1024 {
  45. return fmt.Sprintf("%.1f %sB", floatsize, unit)
  46. }
  47. floatsize /= 1024
  48. }
  49. return fmt.Sprintf("%d%s", size, "B")
  50. }
  51. // PrintSearch handles printing search results in a given format
  52. func (q aurQuery) printSearch(start int) {
  53. localDb, _ := alpmHandle.LocalDb()
  54. for i, res := range q {
  55. var toprint string
  56. if config.SearchMode == NumberMenu {
  57. if config.SortMode == BottomUp {
  58. toprint += magenta(strconv.Itoa(len(q)+start-i-1) + " ")
  59. } else {
  60. toprint += magenta(strconv.Itoa(start+i) + " ")
  61. }
  62. } else if config.SearchMode == Minimal {
  63. fmt.Println(res.Name)
  64. continue
  65. }
  66. toprint += bold(colourHash("aur")) + "/" + bold(res.Name) +
  67. " " + cyan(res.Version) +
  68. bold(" (+"+strconv.Itoa(res.NumVotes)) +
  69. " " + bold(strconv.FormatFloat(res.Popularity, 'f', 2, 64)+"%) ")
  70. if res.Maintainer == "" {
  71. toprint += bold(red("(Orphaned)")) + " "
  72. }
  73. if res.OutOfDate != 0 {
  74. toprint += bold(red("(Out-of-date "+formatTime(res.OutOfDate)+")")) + " "
  75. }
  76. if pkg, err := localDb.PkgByName(res.Name); err == nil {
  77. if pkg.Version() != res.Version {
  78. toprint += bold(green("(Installed: " + pkg.Version() + ")"))
  79. } else {
  80. toprint += bold(green("(Installed)"))
  81. }
  82. }
  83. toprint += "\n " + res.Description
  84. fmt.Println(toprint)
  85. }
  86. }
  87. // PrintSearch receives a RepoSearch type and outputs pretty text.
  88. func (s repoQuery) printSearch() {
  89. for i, res := range s {
  90. var toprint string
  91. if config.SearchMode == NumberMenu {
  92. if config.SortMode == BottomUp {
  93. toprint += magenta(strconv.Itoa(len(s)-i) + " ")
  94. } else {
  95. toprint += magenta(strconv.Itoa(i+1) + " ")
  96. }
  97. } else if config.SearchMode == Minimal {
  98. fmt.Println(res.Name())
  99. continue
  100. }
  101. toprint += bold(colourHash(res.DB().Name())) + "/" + bold(res.Name()) +
  102. " " + cyan(res.Version()) +
  103. bold(" ("+human(res.Size())+
  104. " "+human(res.ISize())+") ")
  105. if len(res.Groups().Slice()) != 0 {
  106. toprint += fmt.Sprint(res.Groups().Slice(), " ")
  107. }
  108. localDb, err := alpmHandle.LocalDb()
  109. if err == nil {
  110. if pkg, err := localDb.PkgByName(res.Name()); err == nil {
  111. if pkg.Version() != res.Version() {
  112. toprint += bold(green("(Installed: " + pkg.Version() + ")"))
  113. } else {
  114. toprint += bold(green("(Installed)"))
  115. }
  116. }
  117. }
  118. toprint += "\n " + res.Description()
  119. fmt.Println(toprint)
  120. }
  121. }
  122. // Pretty print a set of packages from the same package base.
  123. // Packages foo and bar from a pkgbase named base would print like so:
  124. // base (foo bar)
  125. func formatPkgbase(pkg *rpc.Pkg, bases map[string][]*rpc.Pkg) string {
  126. str := pkg.PackageBase
  127. if len(bases[pkg.PackageBase]) > 1 || pkg.PackageBase != pkg.Name {
  128. str2 := " ("
  129. for _, split := range bases[pkg.PackageBase] {
  130. str2 += split.Name + " "
  131. }
  132. str2 = str2[:len(str2)-1] + ")"
  133. str += str2
  134. }
  135. return str
  136. }
  137. // Print prints the details of the packages to upgrade.
  138. func (u upSlice) Print(start int) {
  139. for k, i := range u {
  140. left, right := getVersionDiff(i.LocalVersion, i.RemoteVersion)
  141. fmt.Print(magenta(fmt.Sprintf("%3d ", len(u)+start-k-1)))
  142. fmt.Print(bold(colourHash(i.Repository)), "/", bold(i.Name))
  143. w := 70 - len(i.Repository) - len(i.Name)
  144. padding := fmt.Sprintf("%%%ds", w)
  145. fmt.Printf(padding, left)
  146. fmt.Printf(" -> %s\n", right)
  147. }
  148. }
  149. // printDownloadsFromRepo prints repository packages to be downloaded
  150. func printDepCatagories(dc *depCatagories) {
  151. repo := ""
  152. repoMake := ""
  153. aur := ""
  154. aurMake := ""
  155. repoLen := 0
  156. repoMakeLen := 0
  157. aurLen := 0
  158. aurMakeLen := 0
  159. for _, pkg := range dc.Repo {
  160. if dc.MakeOnly.get(pkg.Name()) {
  161. repoMake += " " + pkg.Name() + "-" + pkg.Version()
  162. repoMakeLen++
  163. } else {
  164. repo += " " + pkg.Name() + "-" + pkg.Version()
  165. repoLen++
  166. }
  167. }
  168. for _, pkg := range dc.Aur {
  169. pkgStr := " " + pkg.PackageBase + "-" + pkg.Version
  170. pkgStrMake := pkgStr
  171. push := false
  172. pushMake := false
  173. if len(dc.Bases[pkg.PackageBase]) > 1 || pkg.PackageBase != pkg.Name {
  174. pkgStr += " ("
  175. pkgStrMake += " ("
  176. for _, split := range dc.Bases[pkg.PackageBase] {
  177. if dc.MakeOnly.get(split.Name) {
  178. pkgStrMake += split.Name + " "
  179. aurMakeLen++
  180. pushMake = true
  181. } else {
  182. pkgStr += split.Name + " "
  183. aurLen++
  184. push = true
  185. }
  186. }
  187. pkgStr = pkgStr[:len(pkgStr)-1] + ")"
  188. pkgStrMake = pkgStrMake[:len(pkgStrMake)-1] + ")"
  189. } else if dc.MakeOnly.get(pkg.Name) {
  190. aurMakeLen++
  191. pushMake = true
  192. } else {
  193. aurLen++
  194. push = true
  195. }
  196. if push {
  197. aur += pkgStr
  198. }
  199. if pushMake {
  200. aurMake += pkgStrMake
  201. }
  202. }
  203. printDownloads("Repo", repoLen, repo)
  204. printDownloads("Repo Make", repoMakeLen, repoMake)
  205. printDownloads("Aur", aurLen, aur)
  206. printDownloads("Aur Make", aurMakeLen, aurMake)
  207. }
  208. func printDownloads(repoName string, length int, packages string) {
  209. if length < 1 {
  210. return
  211. }
  212. repoInfo := bold(blue(
  213. "[" + repoName + ": " + strconv.Itoa(length) + "]"))
  214. fmt.Println(repoInfo + cyan(packages))
  215. }
  216. // PrintInfo prints package info like pacman -Si.
  217. func PrintInfo(a *rpc.Pkg) {
  218. fmt.Println(bold("Repository :"), "aur")
  219. fmt.Println(bold("Name :"), a.Name)
  220. fmt.Println(bold("Version :"), a.Version)
  221. fmt.Println(bold("Description :"), a.Description)
  222. fmt.Println(bold("URL :"), a.URL)
  223. fmt.Println(bold("Licenses :"), strings.Join(a.License, " "))
  224. fmt.Println(bold("Provides :"), strings.Join(a.Provides, " "))
  225. fmt.Println(bold("Depends On :"), strings.Join(a.Depends, " "))
  226. fmt.Println(bold("Make Deps :"), strings.Join(a.MakeDepends, " "))
  227. fmt.Println(bold("Check Deps :"), strings.Join(a.CheckDepends, " "))
  228. fmt.Println(bold("Optional Deps :"), strings.Join(a.OptDepends, " "))
  229. fmt.Println(bold("Conflicts With :"), strings.Join(a.Conflicts, " "))
  230. fmt.Println(bold("Maintainer :"), a.Maintainer)
  231. fmt.Println(bold("Votes :"), a.NumVotes)
  232. fmt.Println(bold("Popularity :"), a.Popularity)
  233. if a.OutOfDate != 0 {
  234. fmt.Println(bold("Out-of-date :"), "Yes", "["+formatTime(a.OutOfDate)+"]")
  235. }
  236. fmt.Println()
  237. }
  238. // BiggestPackages prints the name of the ten biggest packages in the system.
  239. func biggestPackages() {
  240. localDb, err := alpmHandle.LocalDb()
  241. if err != nil {
  242. return
  243. }
  244. pkgCache := localDb.PkgCache()
  245. pkgS := pkgCache.SortBySize().Slice()
  246. if len(pkgS) < 10 {
  247. return
  248. }
  249. for i := 0; i < 10; i++ {
  250. fmt.Println(bold(pkgS[i].Name()) + ": " + cyan(human(pkgS[i].ISize())))
  251. }
  252. // Could implement size here as well, but we just want the general idea
  253. }
  254. // localStatistics prints installed packages statistics.
  255. func localStatistics() error {
  256. info, err := statistics()
  257. if err != nil {
  258. return err
  259. }
  260. _, _, _, remoteNames, err := filterPackages()
  261. if err != nil {
  262. return err
  263. }
  264. fmt.Printf(bold("Yay version v%s\n"), version)
  265. fmt.Println(bold(cyan("===========================================")))
  266. fmt.Println(bold(green("Total installed packages: ")) + cyan(strconv.Itoa(info.Totaln)))
  267. fmt.Println(bold(green("Total foreign installed packages: ")) + cyan(strconv.Itoa(len(remoteNames))))
  268. fmt.Println(bold(green("Explicitly installed packages: ")) + cyan(strconv.Itoa(info.Expln)))
  269. fmt.Println(bold(green("Total Size occupied by packages: ")) + cyan(human(info.TotalSize)))
  270. fmt.Println(bold(cyan("===========================================")))
  271. fmt.Println(bold(green("Ten biggest packages:")))
  272. biggestPackages()
  273. fmt.Println(bold(cyan("===========================================")))
  274. aurInfoPrint(remoteNames)
  275. return nil
  276. }
  277. //TODO: Make it less hacky
  278. func printNumberOfUpdates() error {
  279. //todo
  280. warnings := &aurWarnings{}
  281. old := os.Stdout // keep backup of the real stdout
  282. os.Stdout = nil
  283. aurUp, repoUp, err := upList(warnings)
  284. os.Stdout = old // restoring the real stdout
  285. if err != nil {
  286. return err
  287. }
  288. fmt.Println(len(aurUp) + len(repoUp))
  289. return nil
  290. }
  291. //TODO: Make it less hacky
  292. func printUpdateList(parser *arguments) error {
  293. warnings := &aurWarnings{}
  294. old := os.Stdout // keep backup of the real stdout
  295. os.Stdout = nil
  296. _, _, localNames, remoteNames, err := filterPackages()
  297. if err != nil {
  298. return err
  299. }
  300. aurUp, repoUp, err := upList(warnings)
  301. os.Stdout = old // restoring the real stdout
  302. if err != nil {
  303. return err
  304. }
  305. noTargets := len(parser.targets) == 0
  306. if !parser.existsArg("m", "foreigne") {
  307. for _, pkg := range repoUp {
  308. if noTargets || parser.targets.get(pkg.Name) {
  309. fmt.Printf("%s %s -> %s\n", bold(pkg.Name), green(pkg.LocalVersion), green(pkg.RemoteVersion))
  310. delete(parser.targets, pkg.Name)
  311. }
  312. }
  313. }
  314. if !parser.existsArg("n", "native") {
  315. for _, pkg := range aurUp {
  316. if noTargets || parser.targets.get(pkg.Name) {
  317. fmt.Printf("%s %s -> %s\n", bold(pkg.Name), green(pkg.LocalVersion), green(pkg.RemoteVersion))
  318. delete(parser.targets, pkg.Name)
  319. }
  320. }
  321. }
  322. missing := false
  323. outer:
  324. for pkg := range parser.targets {
  325. for _, name := range localNames {
  326. if name == pkg {
  327. continue outer
  328. }
  329. }
  330. for _, name := range remoteNames {
  331. if name == pkg {
  332. continue outer
  333. }
  334. }
  335. fmt.Println(red(bold("error:")), "package '"+pkg+"' was not found")
  336. missing = true
  337. }
  338. if missing {
  339. return fmt.Errorf("")
  340. }
  341. return nil
  342. }
  343. type Item struct {
  344. Title string `xml:"title"`
  345. Link string `xml:"link"`
  346. Description string `xml:"description"`
  347. PubDate string `xml:"pubDate"`
  348. Creator string `xml:"dc:creator"`
  349. }
  350. func (item Item) Print() error {
  351. date, err := time.Parse(time.RFC1123Z, item.PubDate)
  352. if err != nil {
  353. return err
  354. }
  355. fd := formatTime(int(date.Unix()))
  356. fmt.Println(bold(magenta(fd)), bold(strings.TrimSpace(item.Title)))
  357. //fmt.Println(strings.TrimSpace(item.Link))
  358. if !cmdArgs.existsArg("q", "quiet") {
  359. desc := strings.TrimSpace(parseNews(item.Description))
  360. fmt.Println(desc)
  361. }
  362. return nil
  363. }
  364. type Channel struct {
  365. Title string `xml:"title"`
  366. Link string `xml:"link"`
  367. Description string `xml:"description"`
  368. Language string `xml:"language"`
  369. Lastbuilddate string `xml:"lastbuilddate"`
  370. Items []Item `xml:"item"`
  371. }
  372. type rss struct {
  373. Channel Channel `xml:"channel"`
  374. }
  375. func printNewsFeed() error {
  376. resp, err := http.Get("https://archlinux.org/feeds/news")
  377. if err != nil {
  378. return err
  379. }
  380. defer resp.Body.Close()
  381. body, err := ioutil.ReadAll(resp.Body)
  382. if err != nil {
  383. return err
  384. }
  385. rss := rss{}
  386. d := xml.NewDecoder(bytes.NewReader(body))
  387. err = d.Decode(&rss)
  388. if err != nil {
  389. return err
  390. }
  391. if config.SortMode == BottomUp {
  392. for i := len(rss.Channel.Items) - 1; i >= 0; i-- {
  393. err := rss.Channel.Items[i].Print()
  394. if err != nil {
  395. return err
  396. }
  397. }
  398. } else {
  399. for i := 0; i < len(rss.Channel.Items); i++ {
  400. err := rss.Channel.Items[i].Print()
  401. if err != nil {
  402. return err
  403. }
  404. }
  405. }
  406. return nil
  407. }
  408. // Formats a unix timestamp to ISO 8601 date (yyyy-mm-dd)
  409. func formatTime(i int) string {
  410. t := time.Unix(int64(i), 0)
  411. return t.Format("2006-01-02")
  412. }
  413. const (
  414. redCode = "\x1b[31m"
  415. greenCode = "\x1b[32m"
  416. yellowCode = "\x1b[33m"
  417. blueCode = "\x1b[34m"
  418. magentaCode = "\x1b[35m"
  419. cyanCode = "\x1b[36m"
  420. boldCode = "\x1b[1m"
  421. resetCode = "\x1b[0m"
  422. )
  423. func stylize(startCode, in string) string {
  424. if useColor {
  425. return startCode + in + resetCode
  426. }
  427. return in
  428. }
  429. func red(in string) string {
  430. return stylize(redCode, in)
  431. }
  432. func green(in string) string {
  433. return stylize(greenCode, in)
  434. }
  435. func yellow(in string) string {
  436. return stylize(yellowCode, in)
  437. }
  438. func blue(in string) string {
  439. return stylize(blueCode, in)
  440. }
  441. func cyan(in string) string {
  442. return stylize(cyanCode, in)
  443. }
  444. func magenta(in string) string {
  445. return stylize(magentaCode, in)
  446. }
  447. func bold(in string) string {
  448. return stylize(boldCode, in)
  449. }
  450. // Colours text using a hashing algorithm. The same text will always produce the
  451. // same colour while different text will produce a different colour.
  452. func colourHash(name string) (output string) {
  453. if !useColor {
  454. return name
  455. }
  456. var hash = 5381
  457. for i := 0; i < len(name); i++ {
  458. hash = int(name[i]) + ((hash << 5) + (hash))
  459. }
  460. return fmt.Sprintf("\x1b[%dm%s\x1b[0m", hash%6+31, name)
  461. }