print.go 16 KB

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