print.go 16 KB

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