print.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "strconv"
  10. "strings"
  11. "time"
  12. rpc "github.com/mikkeloscar/aur"
  13. )
  14. const arrow = "==>"
  15. const smallArrow = " ->"
  16. func (warnings *aurWarnings) Print() {
  17. if len(warnings.Missing) > 0 {
  18. fmt.Print(bold(yellow(smallArrow)) + " Missing AUR Packages:")
  19. for _, name := range warnings.Missing {
  20. fmt.Print(" " + cyan(name))
  21. }
  22. fmt.Println()
  23. }
  24. if len(warnings.Orphans) > 0 {
  25. fmt.Print(bold(yellow(smallArrow)) + " Orphaned AUR Packages:")
  26. for _, name := range warnings.Orphans {
  27. fmt.Print(" " + cyan(name))
  28. }
  29. fmt.Println()
  30. }
  31. if len(warnings.OutOfDate) > 0 {
  32. fmt.Print(bold(yellow(smallArrow)) + " Out Of Date AUR Packages:")
  33. for _, name := range warnings.OutOfDate {
  34. fmt.Print(" " + cyan(name))
  35. }
  36. fmt.Println()
  37. }
  38. }
  39. // human method returns results in human readable format.
  40. func human(size int64) string {
  41. floatsize := float32(size)
  42. units := [...]string{"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"}
  43. for _, unit := range units {
  44. if floatsize < 1024 {
  45. return fmt.Sprintf("%.1f %sB", floatsize, unit)
  46. }
  47. floatsize /= 1024
  48. }
  49. return fmt.Sprintf("%d%s", size, "B")
  50. }
  51. // PrintSearch handles printing search results in a given format
  52. func (q aurQuery) printSearch(start int) {
  53. localDb, _ := alpmHandle.LocalDb()
  54. for i, res := range q {
  55. var toprint string
  56. if config.SearchMode == NumberMenu {
  57. if config.SortMode == BottomUp {
  58. toprint += magenta(strconv.Itoa(len(q)+start-i-1) + " ")
  59. } else {
  60. toprint += magenta(strconv.Itoa(start+i) + " ")
  61. }
  62. } else if config.SearchMode == Minimal {
  63. fmt.Println(res.Name)
  64. continue
  65. }
  66. toprint += bold(colourHash("aur")) + "/" + bold(res.Name) +
  67. " " + cyan(res.Version) +
  68. bold(" (+"+strconv.Itoa(res.NumVotes)) +
  69. " " + bold(strconv.FormatFloat(res.Popularity, 'f', 2, 64)+"%) ")
  70. if res.Maintainer == "" {
  71. toprint += bold(red("(Orphaned)")) + " "
  72. }
  73. if res.OutOfDate != 0 {
  74. toprint += bold(red("(Out-of-date "+formatTime(res.OutOfDate)+")")) + " "
  75. }
  76. if pkg, err := localDb.PkgByName(res.Name); err == nil {
  77. if pkg.Version() != res.Version {
  78. toprint += bold(green("(Installed: " + pkg.Version() + ")"))
  79. } else {
  80. toprint += bold(green("(Installed)"))
  81. }
  82. }
  83. toprint += "\n " + res.Description
  84. fmt.Println(toprint)
  85. }
  86. }
  87. // PrintSearch receives a RepoSearch type and outputs pretty text.
  88. func (s repoQuery) printSearch() {
  89. for i, res := range s {
  90. var toprint string
  91. if config.SearchMode == NumberMenu {
  92. if config.SortMode == BottomUp {
  93. toprint += magenta(strconv.Itoa(len(s)-i) + " ")
  94. } else {
  95. toprint += magenta(strconv.Itoa(i+1) + " ")
  96. }
  97. } else if config.SearchMode == Minimal {
  98. fmt.Println(res.Name())
  99. continue
  100. }
  101. toprint += bold(colourHash(res.DB().Name())) + "/" + bold(res.Name()) +
  102. " " + cyan(res.Version()) +
  103. bold(" ("+human(res.Size())+
  104. " "+human(res.ISize())+") ")
  105. if len(res.Groups().Slice()) != 0 {
  106. toprint += fmt.Sprint(res.Groups().Slice(), " ")
  107. }
  108. localDb, err := alpmHandle.LocalDb()
  109. if err == nil {
  110. if pkg, err := localDb.PkgByName(res.Name()); err == nil {
  111. if pkg.Version() != res.Version() {
  112. toprint += bold(green("(Installed: " + pkg.Version() + ")"))
  113. } else {
  114. toprint += bold(green("(Installed)"))
  115. }
  116. }
  117. }
  118. toprint += "\n " + res.Description()
  119. fmt.Println(toprint)
  120. }
  121. }
  122. // Pretty print a set of packages from the same package base.
  123. // Packages foo and bar from a pkgbase named base would print like so:
  124. // base (foo bar)
  125. func formatPkgbase(pkg *rpc.Pkg, bases map[string][]*rpc.Pkg) string {
  126. str := pkg.PackageBase
  127. if len(bases[pkg.PackageBase]) > 1 || pkg.PackageBase != pkg.Name {
  128. str2 := " ("
  129. for _, split := range bases[pkg.PackageBase] {
  130. str2 += split.Name + " "
  131. }
  132. str2 = str2[:len(str2)-1] + ")"
  133. str += str2
  134. }
  135. return str
  136. }
  137. func (u upgrade) StylizedNameWithRepository() string {
  138. return bold(colourHash(u.Repository)) + "/" + bold(u.Name)
  139. }
  140. // Print prints the details of the packages to upgrade.
  141. func (u upSlice) Print() {
  142. longestName, longestVersion := 0, 0
  143. for _, pack := range u {
  144. packNameLen := len(pack.StylizedNameWithRepository())
  145. version, _ := getVersionDiff(pack.LocalVersion, pack.RemoteVersion)
  146. packVersionLen := len(version)
  147. longestName = max(packNameLen, longestName)
  148. longestVersion = max(packVersionLen, longestVersion)
  149. }
  150. namePadding := fmt.Sprintf("%%-%ds ", longestName)
  151. versionPadding := fmt.Sprintf("%%-%ds", longestVersion)
  152. numberPadding := fmt.Sprintf("%%%dd ", len(fmt.Sprintf("%v", len(u))))
  153. for k, i := range u {
  154. left, right := getVersionDiff(i.LocalVersion, i.RemoteVersion)
  155. fmt.Print(magenta(fmt.Sprintf(numberPadding, len(u)-k)))
  156. fmt.Printf(namePadding, i.StylizedNameWithRepository())
  157. fmt.Printf("%s -> %s\n", fmt.Sprintf(versionPadding, left), right)
  158. }
  159. }
  160. // printDownloadsFromRepo prints repository packages to be downloaded
  161. func printDepCatagories(dc *depCatagories) {
  162. repo := ""
  163. repoMake := ""
  164. aur := ""
  165. aurMake := ""
  166. repoLen := 0
  167. repoMakeLen := 0
  168. aurLen := 0
  169. aurMakeLen := 0
  170. for _, pkg := range dc.Repo {
  171. if dc.MakeOnly.get(pkg.Name()) {
  172. repoMake += " " + pkg.Name() + "-" + pkg.Version()
  173. repoMakeLen++
  174. } else {
  175. repo += " " + pkg.Name() + "-" + pkg.Version()
  176. repoLen++
  177. }
  178. }
  179. for _, pkg := range dc.Aur {
  180. pkgStr := " " + pkg.PackageBase + "-" + pkg.Version
  181. pkgStrMake := pkgStr
  182. push := false
  183. pushMake := false
  184. if len(dc.Bases[pkg.PackageBase]) > 1 || pkg.PackageBase != pkg.Name {
  185. pkgStr += " ("
  186. pkgStrMake += " ("
  187. for _, split := range dc.Bases[pkg.PackageBase] {
  188. if dc.MakeOnly.get(split.Name) {
  189. pkgStrMake += split.Name + " "
  190. aurMakeLen++
  191. pushMake = true
  192. } else {
  193. pkgStr += split.Name + " "
  194. aurLen++
  195. push = true
  196. }
  197. }
  198. pkgStr = pkgStr[:len(pkgStr)-1] + ")"
  199. pkgStrMake = pkgStrMake[:len(pkgStrMake)-1] + ")"
  200. } else if dc.MakeOnly.get(pkg.Name) {
  201. aurMakeLen++
  202. pushMake = true
  203. } else {
  204. aurLen++
  205. push = true
  206. }
  207. if push {
  208. aur += pkgStr
  209. }
  210. if pushMake {
  211. aurMake += pkgStrMake
  212. }
  213. }
  214. printDownloads("Repo", repoLen, repo)
  215. printDownloads("Repo Make", repoMakeLen, repoMake)
  216. printDownloads("Aur", aurLen, aur)
  217. printDownloads("Aur Make", aurMakeLen, aurMake)
  218. }
  219. func printDownloads(repoName string, length int, packages string) {
  220. if length < 1 {
  221. return
  222. }
  223. repoInfo := bold(blue(
  224. "[" + repoName + ": " + strconv.Itoa(length) + "]"))
  225. fmt.Println(repoInfo + cyan(packages))
  226. }
  227. // PrintInfo prints package info like pacman -Si.
  228. func PrintInfo(a *rpc.Pkg) {
  229. fmt.Println(bold("Repository :"), "aur")
  230. fmt.Println(bold("Name :"), a.Name)
  231. fmt.Println(bold("Version :"), a.Version)
  232. fmt.Println(bold("Description :"), a.Description)
  233. fmt.Println(bold("URL :"), a.URL)
  234. fmt.Println(bold("Licenses :"), strings.Join(a.License, " "))
  235. fmt.Println(bold("Provides :"), strings.Join(a.Provides, " "))
  236. fmt.Println(bold("Depends On :"), strings.Join(a.Depends, " "))
  237. fmt.Println(bold("Make Deps :"), strings.Join(a.MakeDepends, " "))
  238. fmt.Println(bold("Check Deps :"), strings.Join(a.CheckDepends, " "))
  239. fmt.Println(bold("Optional Deps :"), strings.Join(a.OptDepends, " "))
  240. fmt.Println(bold("Conflicts With :"), strings.Join(a.Conflicts, " "))
  241. fmt.Println(bold("Maintainer :"), a.Maintainer)
  242. fmt.Println(bold("Votes :"), a.NumVotes)
  243. fmt.Println(bold("Popularity :"), a.Popularity)
  244. if a.OutOfDate != 0 {
  245. fmt.Println(bold("Out-of-date :"), "Yes", "["+formatTime(a.OutOfDate)+"]")
  246. }
  247. fmt.Println()
  248. }
  249. // BiggestPackages prints the name of the ten biggest packages in the system.
  250. func biggestPackages() {
  251. localDb, err := alpmHandle.LocalDb()
  252. if err != nil {
  253. return
  254. }
  255. pkgCache := localDb.PkgCache()
  256. pkgS := pkgCache.SortBySize().Slice()
  257. if len(pkgS) < 10 {
  258. return
  259. }
  260. for i := 0; i < 10; i++ {
  261. fmt.Println(bold(pkgS[i].Name()) + ": " + cyan(human(pkgS[i].ISize())))
  262. }
  263. // Could implement size here as well, but we just want the general idea
  264. }
  265. // localStatistics prints installed packages statistics.
  266. func localStatistics() error {
  267. info, err := statistics()
  268. if err != nil {
  269. return err
  270. }
  271. _, _, _, remoteNames, err := filterPackages()
  272. if err != nil {
  273. return err
  274. }
  275. fmt.Printf(bold("Yay version v%s\n"), version)
  276. fmt.Println(bold(cyan("===========================================")))
  277. fmt.Println(bold(green("Total installed packages: ")) + cyan(strconv.Itoa(info.Totaln)))
  278. fmt.Println(bold(green("Total foreign installed packages: ")) + cyan(strconv.Itoa(len(remoteNames))))
  279. fmt.Println(bold(green("Explicitly installed packages: ")) + cyan(strconv.Itoa(info.Expln)))
  280. fmt.Println(bold(green("Total Size occupied by packages: ")) + cyan(human(info.TotalSize)))
  281. fmt.Println(bold(cyan("===========================================")))
  282. fmt.Println(bold(green("Ten biggest packages:")))
  283. biggestPackages()
  284. fmt.Println(bold(cyan("===========================================")))
  285. aurInfoPrint(remoteNames)
  286. return nil
  287. }
  288. //TODO: Make it less hacky
  289. func printNumberOfUpdates() error {
  290. //todo
  291. warnings := &aurWarnings{}
  292. old := os.Stdout // keep backup of the real stdout
  293. os.Stdout = nil
  294. aurUp, repoUp, err := upList(warnings)
  295. os.Stdout = old // restoring the real stdout
  296. if err != nil {
  297. return err
  298. }
  299. fmt.Println(len(aurUp) + len(repoUp))
  300. return nil
  301. }
  302. //TODO: Make it less hacky
  303. func printUpdateList(parser *arguments) error {
  304. warnings := &aurWarnings{}
  305. old := os.Stdout // keep backup of the real stdout
  306. os.Stdout = nil
  307. _, _, localNames, remoteNames, err := filterPackages()
  308. if err != nil {
  309. return err
  310. }
  311. aurUp, repoUp, err := upList(warnings)
  312. os.Stdout = old // restoring the real stdout
  313. if err != nil {
  314. return err
  315. }
  316. noTargets := len(parser.targets) == 0
  317. if !parser.existsArg("m", "foreign") {
  318. for _, pkg := range repoUp {
  319. if noTargets || parser.targets.get(pkg.Name) {
  320. fmt.Printf("%s %s -> %s\n", bold(pkg.Name), green(pkg.LocalVersion), green(pkg.RemoteVersion))
  321. delete(parser.targets, pkg.Name)
  322. }
  323. }
  324. }
  325. if !parser.existsArg("n", "native") {
  326. for _, pkg := range aurUp {
  327. if noTargets || parser.targets.get(pkg.Name) {
  328. fmt.Printf("%s %s -> %s\n", bold(pkg.Name), green(pkg.LocalVersion), green(pkg.RemoteVersion))
  329. delete(parser.targets, pkg.Name)
  330. }
  331. }
  332. }
  333. missing := false
  334. outer:
  335. for pkg := range parser.targets {
  336. for _, name := range localNames {
  337. if name == pkg {
  338. continue outer
  339. }
  340. }
  341. for _, name := range remoteNames {
  342. if name == pkg {
  343. continue outer
  344. }
  345. }
  346. fmt.Println(red(bold("error:")), "package '"+pkg+"' was not found")
  347. missing = true
  348. }
  349. if missing {
  350. return fmt.Errorf("")
  351. }
  352. return nil
  353. }
  354. type Item struct {
  355. Title string `xml:"title"`
  356. Link string `xml:"link"`
  357. Description string `xml:"description"`
  358. PubDate string `xml:"pubDate"`
  359. Creator string `xml:"dc:creator"`
  360. }
  361. func (item Item) Print() error {
  362. date, err := time.Parse(time.RFC1123Z, item.PubDate)
  363. if err != nil {
  364. return err
  365. }
  366. fd := formatTime(int(date.Unix()))
  367. fmt.Println(bold(magenta(fd)), bold(strings.TrimSpace(item.Title)))
  368. //fmt.Println(strings.TrimSpace(item.Link))
  369. if !cmdArgs.existsArg("q", "quiet") {
  370. desc := strings.TrimSpace(parseNews(item.Description))
  371. fmt.Println(desc)
  372. }
  373. return nil
  374. }
  375. type Channel struct {
  376. Title string `xml:"title"`
  377. Link string `xml:"link"`
  378. Description string `xml:"description"`
  379. Language string `xml:"language"`
  380. Lastbuilddate string `xml:"lastbuilddate"`
  381. Items []Item `xml:"item"`
  382. }
  383. type rss struct {
  384. Channel Channel `xml:"channel"`
  385. }
  386. func printNewsFeed() error {
  387. resp, err := http.Get("https://archlinux.org/feeds/news")
  388. if err != nil {
  389. return err
  390. }
  391. defer resp.Body.Close()
  392. body, err := ioutil.ReadAll(resp.Body)
  393. if err != nil {
  394. return err
  395. }
  396. rss := rss{}
  397. d := xml.NewDecoder(bytes.NewReader(body))
  398. err = d.Decode(&rss)
  399. if err != nil {
  400. return err
  401. }
  402. if config.SortMode == BottomUp {
  403. for i := len(rss.Channel.Items) - 1; i >= 0; i-- {
  404. err := rss.Channel.Items[i].Print()
  405. if err != nil {
  406. return err
  407. }
  408. }
  409. } else {
  410. for i := 0; i < len(rss.Channel.Items); i++ {
  411. err := rss.Channel.Items[i].Print()
  412. if err != nil {
  413. return err
  414. }
  415. }
  416. }
  417. return nil
  418. }
  419. // Formats a unix timestamp to ISO 8601 date (yyyy-mm-dd)
  420. func formatTime(i int) string {
  421. t := time.Unix(int64(i), 0)
  422. return t.Format("2006-01-02")
  423. }
  424. const (
  425. redCode = "\x1b[31m"
  426. greenCode = "\x1b[32m"
  427. yellowCode = "\x1b[33m"
  428. blueCode = "\x1b[34m"
  429. magentaCode = "\x1b[35m"
  430. cyanCode = "\x1b[36m"
  431. boldCode = "\x1b[1m"
  432. resetCode = "\x1b[0m"
  433. )
  434. func stylize(startCode, in string) string {
  435. if useColor {
  436. return startCode + in + resetCode
  437. }
  438. return in
  439. }
  440. func red(in string) string {
  441. return stylize(redCode, in)
  442. }
  443. func green(in string) string {
  444. return stylize(greenCode, in)
  445. }
  446. func yellow(in string) string {
  447. return stylize(yellowCode, in)
  448. }
  449. func blue(in string) string {
  450. return stylize(blueCode, in)
  451. }
  452. func cyan(in string) string {
  453. return stylize(cyanCode, in)
  454. }
  455. func magenta(in string) string {
  456. return stylize(magentaCode, in)
  457. }
  458. func bold(in string) string {
  459. return stylize(boldCode, in)
  460. }
  461. // Colours text using a hashing algorithm. The same text will always produce the
  462. // same colour while different text will produce a different colour.
  463. func colourHash(name string) (output string) {
  464. if !useColor {
  465. return name
  466. }
  467. var hash = 5381
  468. for i := 0; i < len(name); i++ {
  469. hash = int(name[i]) + ((hash << 5) + (hash))
  470. }
  471. return fmt.Sprintf("\x1b[%dm%s\x1b[0m", hash%6+31, name)
  472. }