print.go 15 KB

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