print.go 16 KB

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