print.go 15 KB

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