print.go 16 KB

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