print.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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(base []*rpc.Pkg) string {
  127. pkg := base[0]
  128. str := pkg.PackageBase
  129. if len(base) > 1 || pkg.PackageBase != pkg.Name {
  130. str2 := " ("
  131. for _, split := range base {
  132. str2 += split.Name + " "
  133. }
  134. str2 = str2[:len(str2)-1] + ")"
  135. str += str2
  136. }
  137. return str
  138. }
  139. func (u upgrade) StylizedNameWithRepository() string {
  140. return bold(colourHash(u.Repository)) + "/" + bold(u.Name)
  141. }
  142. // Print prints the details of the packages to upgrade.
  143. func (u upSlice) print() {
  144. longestName, longestVersion := 0, 0
  145. for _, pack := range u {
  146. packNameLen := len(pack.StylizedNameWithRepository())
  147. version, _ := getVersionDiff(pack.LocalVersion, pack.RemoteVersion)
  148. packVersionLen := len(version)
  149. longestName = max(packNameLen, longestName)
  150. longestVersion = max(packVersionLen, longestVersion)
  151. }
  152. namePadding := fmt.Sprintf("%%-%ds ", longestName)
  153. versionPadding := fmt.Sprintf("%%-%ds", longestVersion)
  154. numberPadding := fmt.Sprintf("%%%dd ", len(fmt.Sprintf("%v", len(u))))
  155. for k, i := range u {
  156. left, right := getVersionDiff(i.LocalVersion, i.RemoteVersion)
  157. fmt.Print(magenta(fmt.Sprintf(numberPadding, len(u)-k)))
  158. fmt.Printf(namePadding, i.StylizedNameWithRepository())
  159. fmt.Printf("%s -> %s\n", fmt.Sprintf(versionPadding, left), right)
  160. }
  161. }
  162. // printDownloadsFromRepo prints repository packages to be downloaded
  163. func (do *depOrder) Print() {
  164. repo := ""
  165. repoMake := ""
  166. aur := ""
  167. aurMake := ""
  168. repoLen := 0
  169. repoMakeLen := 0
  170. aurLen := 0
  171. aurMakeLen := 0
  172. for _, pkg := range do.Repo {
  173. if do.Runtime.get(pkg.Name()) {
  174. repo += " " + pkg.Name() + "-" + pkg.Version()
  175. repoLen++
  176. } else {
  177. repoMake += " " + pkg.Name() + "-" + pkg.Version()
  178. repoMakeLen++
  179. }
  180. }
  181. for _, pkg := range do.Aur {
  182. pkgStr := " " + pkg.PackageBase + "-" + pkg.Version
  183. pkgStrMake := pkgStr
  184. push := false
  185. pushMake := false
  186. if len(do.Bases[pkg.PackageBase]) > 1 || pkg.PackageBase != pkg.Name {
  187. pkgStr += " ("
  188. pkgStrMake += " ("
  189. for _, split := range do.Bases[pkg.PackageBase] {
  190. if do.Runtime.get(split.Name) {
  191. pkgStr += split.Name + " "
  192. aurLen++
  193. push = true
  194. } else {
  195. pkgStrMake += split.Name + " "
  196. aurMakeLen++
  197. pushMake = true
  198. }
  199. }
  200. pkgStr = pkgStr[:len(pkgStr)-1] + ")"
  201. pkgStrMake = pkgStrMake[:len(pkgStrMake)-1] + ")"
  202. } else if do.Runtime.get(pkg.Name) {
  203. aurLen++
  204. push = true
  205. } else {
  206. aurMakeLen++
  207. pushMake = true
  208. }
  209. if push {
  210. aur += pkgStr
  211. }
  212. if pushMake {
  213. aurMake += pkgStrMake
  214. }
  215. }
  216. printDownloads("Repo", repoLen, repo)
  217. printDownloads("Repo Make", repoMakeLen, repoMake)
  218. printDownloads("Aur", aurLen, aur)
  219. printDownloads("Aur Make", aurMakeLen, aurMake)
  220. }
  221. func printDownloads(repoName string, length int, packages string) {
  222. if length < 1 {
  223. return
  224. }
  225. repoInfo := bold(blue(
  226. "[" + repoName + ": " + strconv.Itoa(length) + "]"))
  227. fmt.Println(repoInfo + cyan(packages))
  228. }
  229. func printInfoValue(str, value string) {
  230. if value == "" {
  231. value = "None"
  232. }
  233. fmt.Printf(bold("%-16s%s")+" %s\n", str, ":", value)
  234. }
  235. // PrintInfo prints package info like pacman -Si.
  236. func PrintInfo(a *rpc.Pkg) {
  237. printInfoValue("Repository", "aur")
  238. printInfoValue("Name", a.Name)
  239. printInfoValue("Keywords", strings.Join(a.Keywords, " "))
  240. printInfoValue("Version", a.Version)
  241. printInfoValue("Description", a.Description)
  242. printInfoValue("URL", a.URL)
  243. printInfoValue("AUR URL", baseURL+"/packages/"+a.Name)
  244. printInfoValue("Groups", strings.Join(a.Groups, " "))
  245. printInfoValue("Licenses", strings.Join(a.License, " "))
  246. printInfoValue("Provides", strings.Join(a.Provides, " "))
  247. printInfoValue("Depends On", strings.Join(a.Depends, " "))
  248. printInfoValue("Make Deps", strings.Join(a.MakeDepends, " "))
  249. printInfoValue("Check Deps", strings.Join(a.CheckDepends, " "))
  250. printInfoValue("Optional Deps", strings.Join(a.OptDepends, " "))
  251. printInfoValue("Conflicts With", strings.Join(a.Conflicts, " "))
  252. printInfoValue("Maintainer", a.Maintainer)
  253. printInfoValue("Votes", fmt.Sprintf("%d", a.NumVotes))
  254. printInfoValue("Popularity", fmt.Sprintf("%f", a.Popularity))
  255. printInfoValue("First Submitted", formatTime(a.FirstSubmitted))
  256. printInfoValue("Last Modified", formatTime(a.LastModified))
  257. if a.OutOfDate != 0 {
  258. printInfoValue("Out-of-date", "Yes ["+formatTime(a.OutOfDate)+"]")
  259. } else {
  260. printInfoValue("Out-of-date", "No")
  261. }
  262. if cmdArgs.existsDouble("i") {
  263. printInfoValue("ID", fmt.Sprintf("%d", a.ID))
  264. printInfoValue("Package Base ID", fmt.Sprintf("%d", a.PackageBaseID))
  265. printInfoValue("Package Base", a.PackageBase)
  266. printInfoValue("Snapshot URL", baseURL+a.URLPath)
  267. }
  268. fmt.Println()
  269. }
  270. // BiggestPackages prints the name of the ten biggest packages in the system.
  271. func biggestPackages() {
  272. localDb, err := alpmHandle.LocalDb()
  273. if err != nil {
  274. return
  275. }
  276. pkgCache := localDb.PkgCache()
  277. pkgS := pkgCache.SortBySize().Slice()
  278. if len(pkgS) < 10 {
  279. return
  280. }
  281. for i := 0; i < 10; i++ {
  282. fmt.Println(bold(pkgS[i].Name()) + ": " + cyan(human(pkgS[i].ISize())))
  283. }
  284. // Could implement size here as well, but we just want the general idea
  285. }
  286. // localStatistics prints installed packages statistics.
  287. func localStatistics() error {
  288. info, err := statistics()
  289. if err != nil {
  290. return err
  291. }
  292. _, _, _, remoteNames, err := filterPackages()
  293. if err != nil {
  294. return err
  295. }
  296. fmt.Printf(bold("Yay version v%s\n"), version)
  297. fmt.Println(bold(cyan("===========================================")))
  298. fmt.Println(bold(green("Total installed packages: ")) + cyan(strconv.Itoa(info.Totaln)))
  299. fmt.Println(bold(green("Total foreign installed packages: ")) + cyan(strconv.Itoa(len(remoteNames))))
  300. fmt.Println(bold(green("Explicitly installed packages: ")) + cyan(strconv.Itoa(info.Expln)))
  301. fmt.Println(bold(green("Total Size occupied by packages: ")) + cyan(human(info.TotalSize)))
  302. fmt.Println(bold(cyan("===========================================")))
  303. fmt.Println(bold(green("Ten biggest packages:")))
  304. biggestPackages()
  305. fmt.Println(bold(cyan("===========================================")))
  306. aurInfoPrint(remoteNames)
  307. return nil
  308. }
  309. //TODO: Make it less hacky
  310. func printNumberOfUpdates() error {
  311. //todo
  312. warnings := &aurWarnings{}
  313. old := os.Stdout // keep backup of the real stdout
  314. os.Stdout = nil
  315. aurUp, repoUp, err := upList(warnings)
  316. os.Stdout = old // restoring the real stdout
  317. if err != nil {
  318. return err
  319. }
  320. fmt.Println(len(aurUp) + len(repoUp))
  321. return nil
  322. }
  323. //TODO: Make it less hacky
  324. func printUpdateList(parser *arguments) error {
  325. targets := sliceToStringSet(parser.targets)
  326. warnings := &aurWarnings{}
  327. old := os.Stdout // keep backup of the real stdout
  328. os.Stdout = nil
  329. _, _, localNames, remoteNames, err := filterPackages()
  330. if err != nil {
  331. return err
  332. }
  333. aurUp, repoUp, err := upList(warnings)
  334. os.Stdout = old // restoring the real stdout
  335. if err != nil {
  336. return err
  337. }
  338. noTargets := len(targets) == 0
  339. if !parser.existsArg("m", "foreign") {
  340. for _, pkg := range repoUp {
  341. if noTargets || targets.get(pkg.Name) {
  342. fmt.Printf("%s %s -> %s\n", bold(pkg.Name), green(pkg.LocalVersion), green(pkg.RemoteVersion))
  343. delete(targets, pkg.Name)
  344. }
  345. }
  346. }
  347. if !parser.existsArg("n", "native") {
  348. for _, pkg := range aurUp {
  349. if noTargets || targets.get(pkg.Name) {
  350. fmt.Printf("%s %s -> %s\n", bold(pkg.Name), green(pkg.LocalVersion), green(pkg.RemoteVersion))
  351. delete(targets, pkg.Name)
  352. }
  353. }
  354. }
  355. missing := false
  356. outer:
  357. for pkg := range targets {
  358. for _, name := range localNames {
  359. if name == pkg {
  360. continue outer
  361. }
  362. }
  363. for _, name := range remoteNames {
  364. if name == pkg {
  365. continue outer
  366. }
  367. }
  368. fmt.Println(red(bold("error:")), "package '"+pkg+"' was not found")
  369. missing = true
  370. }
  371. if missing {
  372. return fmt.Errorf("")
  373. }
  374. return nil
  375. }
  376. type item struct {
  377. Title string `xml:"title"`
  378. Link string `xml:"link"`
  379. Description string `xml:"description"`
  380. PubDate string `xml:"pubDate"`
  381. Creator string `xml:"dc:creator"`
  382. }
  383. func (item item) print(buildTime time.Time) {
  384. var fd string
  385. date, err := time.Parse(time.RFC1123Z, item.PubDate)
  386. if err != nil {
  387. fmt.Println(err)
  388. } else {
  389. fd = formatTime(int(date.Unix()))
  390. if _, double, _ := cmdArgs.getArg("news", "w"); !double && !buildTime.IsZero() {
  391. if buildTime.After(date) {
  392. return
  393. }
  394. }
  395. }
  396. fmt.Println(bold(magenta(fd)), bold(strings.TrimSpace(item.Title)))
  397. //fmt.Println(strings.TrimSpace(item.Link))
  398. if !cmdArgs.existsArg("q", "quiet") {
  399. desc := strings.TrimSpace(parseNews(item.Description))
  400. fmt.Println(desc)
  401. }
  402. }
  403. type channel struct {
  404. Title string `xml:"title"`
  405. Link string `xml:"link"`
  406. Description string `xml:"description"`
  407. Language string `xml:"language"`
  408. Lastbuilddate string `xml:"lastbuilddate"`
  409. Items []item `xml:"item"`
  410. }
  411. type rss struct {
  412. Channel channel `xml:"channel"`
  413. }
  414. func printNewsFeed() error {
  415. resp, err := http.Get("https://archlinux.org/feeds/news")
  416. if err != nil {
  417. return err
  418. }
  419. defer resp.Body.Close()
  420. body, err := ioutil.ReadAll(resp.Body)
  421. if err != nil {
  422. return err
  423. }
  424. rss := rss{}
  425. d := xml.NewDecoder(bytes.NewReader(body))
  426. err = d.Decode(&rss)
  427. if err != nil {
  428. return err
  429. }
  430. buildTime, err := lastBuildTime()
  431. if err != nil {
  432. return err
  433. }
  434. if config.SortMode == BottomUp {
  435. for i := len(rss.Channel.Items) - 1; i >= 0; i-- {
  436. rss.Channel.Items[i].print(buildTime)
  437. }
  438. } else {
  439. for i := 0; i < len(rss.Channel.Items); i++ {
  440. rss.Channel.Items[i].print(buildTime)
  441. }
  442. }
  443. return nil
  444. }
  445. // Formats a unix timestamp to ISO 8601 date (yyyy-mm-dd)
  446. func formatTime(i int) string {
  447. t := time.Unix(int64(i), 0)
  448. return t.Format("2006-01-02")
  449. }
  450. const (
  451. redCode = "\x1b[31m"
  452. greenCode = "\x1b[32m"
  453. yellowCode = "\x1b[33m"
  454. blueCode = "\x1b[34m"
  455. magentaCode = "\x1b[35m"
  456. cyanCode = "\x1b[36m"
  457. boldCode = "\x1b[1m"
  458. resetCode = "\x1b[0m"
  459. )
  460. func stylize(startCode, in string) string {
  461. if useColor {
  462. return startCode + in + resetCode
  463. }
  464. return in
  465. }
  466. func red(in string) string {
  467. return stylize(redCode, in)
  468. }
  469. func green(in string) string {
  470. return stylize(greenCode, in)
  471. }
  472. func yellow(in string) string {
  473. return stylize(yellowCode, in)
  474. }
  475. func blue(in string) string {
  476. return stylize(blueCode, in)
  477. }
  478. func cyan(in string) string {
  479. return stylize(cyanCode, in)
  480. }
  481. func magenta(in string) string {
  482. return stylize(magentaCode, in)
  483. }
  484. func bold(in string) string {
  485. return stylize(boldCode, in)
  486. }
  487. // Colours text using a hashing algorithm. The same text will always produce the
  488. // same colour while different text will produce a different colour.
  489. func colourHash(name string) (output string) {
  490. if !useColor {
  491. return name
  492. }
  493. var hash = 5381
  494. for i := 0; i < len(name); i++ {
  495. hash = int(name[i]) + ((hash << 5) + (hash))
  496. }
  497. return fmt.Sprintf("\x1b[%dm%s\x1b[0m", hash%6+31, name)
  498. }
  499. func providerMenu(dep string, providers providers) *rpc.Pkg {
  500. size := providers.Len()
  501. fmt.Print(bold(cyan(":: ")))
  502. str := bold(fmt.Sprintf(bold("There are %d providers available for %s:"), size, dep))
  503. size = 1
  504. str += bold(cyan("\n:: ")) + bold("Repository AUR\n ")
  505. for _, pkg := range providers.Pkgs {
  506. str += fmt.Sprintf("%d) %s ", size, pkg.Name)
  507. size++
  508. }
  509. fmt.Println(str)
  510. for {
  511. fmt.Print("\nEnter a number (default=1): ")
  512. if config.NoConfirm {
  513. fmt.Println("1")
  514. return providers.Pkgs[0]
  515. }
  516. reader := bufio.NewReader(os.Stdin)
  517. numberBuf, overflow, err := reader.ReadLine()
  518. if err != nil {
  519. fmt.Println(err)
  520. break
  521. }
  522. if overflow {
  523. fmt.Println("Input too long")
  524. continue
  525. }
  526. if string(numberBuf) == "" {
  527. return providers.Pkgs[0]
  528. }
  529. num, err := strconv.Atoi(string(numberBuf))
  530. if err != nil {
  531. fmt.Printf("%s invalid number: %s\n", red("error:"), string(numberBuf))
  532. continue
  533. }
  534. if num < 1 || num > size {
  535. fmt.Printf("%s invalid value: %d is not between %d and %d\n", red("error:"), num, 1, size)
  536. continue
  537. }
  538. return providers.Pkgs[num-1]
  539. }
  540. return nil
  541. }