print.go 14 KB

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