print.go 15 KB

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