yay/print.go

566 lines
13 KiB
Go
Raw Normal View History

package main
import (
2018-05-06 02:26:03 +02:00
"bytes"
"encoding/xml"
"fmt"
2018-05-06 02:26:03 +02:00
"io/ioutil"
"net/http"
2018-02-19 18:36:33 +01:00
"os"
"strconv"
"strings"
"time"
rpc "github.com/mikkeloscar/aur"
)
const arrow = "==>"
const smallArrow = " ->"
func (warnings *aurWarnings) Print() {
if len(warnings.Missing) > 0 {
fmt.Print(bold(yellow(smallArrow)) + " Missing AUR Packages:")
for _, name := range warnings.Missing {
fmt.Print(" " + cyan(name))
}
fmt.Println()
}
if len(warnings.Orphans) > 0 {
fmt.Print(bold(yellow(smallArrow)) + " Orphaned AUR Packages:")
for _, name := range warnings.Orphans {
fmt.Print(" " + cyan(name))
}
fmt.Println()
}
if len(warnings.OutOfDate) > 0 {
fmt.Print(bold(yellow(smallArrow)) + " Out Of Date AUR Packages:")
for _, name := range warnings.OutOfDate {
fmt.Print(" " + cyan(name))
}
fmt.Println()
}
}
// human method returns results in human readable format.
func human(size int64) string {
floatsize := float32(size)
units := [...]string{"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"}
for _, unit := range units {
if floatsize < 1024 {
return fmt.Sprintf("%.1f %sB", floatsize, unit)
}
floatsize /= 1024
}
return fmt.Sprintf("%d%s", size, "B")
}
// PrintSearch handles printing search results in a given format
func (q aurQuery) printSearch(start int) {
localDb, _ := alpmHandle.LocalDb()
for i, res := range q {
var toprint string
2017-08-04 11:26:53 +02:00
if config.SearchMode == NumberMenu {
if config.SortMode == BottomUp {
toprint += magenta(strconv.Itoa(len(q)+start-i-1) + " ")
} else {
toprint += magenta(strconv.Itoa(start+i) + " ")
}
2017-08-04 11:26:53 +02:00
} else if config.SearchMode == Minimal {
fmt.Println(res.Name)
continue
}
toprint += bold(colourHash("aur")) + "/" + bold(res.Name) +
" " + cyan(res.Version) +
bold(" (+"+strconv.Itoa(res.NumVotes)) +
" " + bold(strconv.FormatFloat(res.Popularity, 'f', 2, 64)+"%) ")
if res.Maintainer == "" {
toprint += bold(red("(Orphaned)")) + " "
}
if res.OutOfDate != 0 {
toprint += bold(red("(Out-of-date "+formatTime(res.OutOfDate)+")")) + " "
}
if pkg, err := localDb.PkgByName(res.Name); err == nil {
if pkg.Version() != res.Version {
toprint += bold(green("(Installed: " + pkg.Version() + ")"))
} else {
toprint += bold(green("(Installed)"))
}
}
toprint += "\n " + res.Description
fmt.Println(toprint)
}
}
// PrintSearch receives a RepoSearch type and outputs pretty text.
func (s repoQuery) printSearch() {
for i, res := range s {
var toprint string
if config.SearchMode == NumberMenu {
if config.SortMode == BottomUp {
toprint += magenta(strconv.Itoa(len(s)-i) + " ")
} else {
toprint += magenta(strconv.Itoa(i+1) + " ")
}
} else if config.SearchMode == Minimal {
fmt.Println(res.Name())
continue
}
toprint += bold(colourHash(res.DB().Name())) + "/" + bold(res.Name()) +
" " + cyan(res.Version()) +
bold(" ("+human(res.Size())+
" "+human(res.ISize())+") ")
if len(res.Groups().Slice()) != 0 {
toprint += fmt.Sprint(res.Groups().Slice(), " ")
}
localDb, err := alpmHandle.LocalDb()
if err == nil {
if pkg, err := localDb.PkgByName(res.Name()); err == nil {
if pkg.Version() != res.Version() {
toprint += bold(green("(Installed: " + pkg.Version() + ")"))
} else {
toprint += bold(green("(Installed)"))
}
}
}
toprint += "\n " + res.Description()
fmt.Println(toprint)
}
}
// Pretty print a set of packages from the same package base.
// Packages foo and bar from a pkgbase named base would print like so:
// base (foo bar)
func formatPkgbase(pkg *rpc.Pkg, bases map[string][]*rpc.Pkg) string {
str := pkg.PackageBase
if len(bases[pkg.PackageBase]) > 1 || pkg.PackageBase != pkg.Name {
str2 := " ("
for _, split := range bases[pkg.PackageBase] {
str2 += split.Name + " "
}
str2 = str2[:len(str2)-1] + ")"
str += str2
}
return str
}
2018-05-02 17:46:21 +02:00
func (u upgrade) StylizedNameWithRepository() string {
return bold(colourHash(u.Repository)) + "/" + bold(u.Name)
}
// Print prints the details of the packages to upgrade.
2018-05-02 17:46:21 +02:00
func (u upSlice) Print() {
longestName, longestVersion := 0, 0
for _, pack := range u {
packNameLen := len(pack.StylizedNameWithRepository())
version, _ := getVersionDiff(pack.LocalVersion, pack.RemoteVersion)
packVersionLen := len(version)
longestName = max(packNameLen, longestName)
longestVersion = max(packVersionLen, longestVersion)
}
namePadding := fmt.Sprintf("%%-%ds ", longestName)
versionPadding := fmt.Sprintf("%%-%ds", longestVersion)
numberPadding := fmt.Sprintf("%%%dd ", len(fmt.Sprintf("%v", len(u))))
for k, i := range u {
left, right := getVersionDiff(i.LocalVersion, i.RemoteVersion)
2018-05-02 17:46:21 +02:00
fmt.Print(magenta(fmt.Sprintf(numberPadding, len(u)-k)))
fmt.Printf(namePadding, i.StylizedNameWithRepository())
2018-05-02 17:46:21 +02:00
fmt.Printf("%s -> %s\n", fmt.Sprintf(versionPadding, left), right)
}
}
2018-02-05 21:05:58 +01:00
// printDownloadsFromRepo prints repository packages to be downloaded
func printDepCatagories(dc *depCatagories) {
repo := ""
repoMake := ""
aur := ""
aurMake := ""
repoLen := 0
repoMakeLen := 0
aurLen := 0
aurMakeLen := 0
for _, pkg := range dc.Repo {
if dc.MakeOnly.get(pkg.Name()) {
repoMake += " " + pkg.Name() + "-" + pkg.Version()
repoMakeLen++
} else {
repo += " " + pkg.Name() + "-" + pkg.Version()
repoLen++
}
2018-02-05 21:05:58 +01:00
}
for _, pkg := range dc.Aur {
pkgStr := " " + pkg.PackageBase + "-" + pkg.Version
pkgStrMake := pkgStr
push := false
pushMake := false
if len(dc.Bases[pkg.PackageBase]) > 1 || pkg.PackageBase != pkg.Name {
pkgStr += " ("
pkgStrMake += " ("
for _, split := range dc.Bases[pkg.PackageBase] {
if dc.MakeOnly.get(split.Name) {
pkgStrMake += split.Name + " "
aurMakeLen++
pushMake = true
} else {
pkgStr += split.Name + " "
aurLen++
push = true
}
}
pkgStr = pkgStr[:len(pkgStr)-1] + ")"
pkgStrMake = pkgStrMake[:len(pkgStrMake)-1] + ")"
} else if dc.MakeOnly.get(pkg.Name) {
aurMakeLen++
pushMake = true
} else {
aurLen++
push = true
}
if push {
aur += pkgStr
}
if pushMake {
aurMake += pkgStrMake
}
2018-02-05 21:05:58 +01:00
}
2018-02-16 18:18:59 +01:00
printDownloads("Repo", repoLen, repo)
printDownloads("Repo Make", repoMakeLen, repoMake)
printDownloads("Aur", aurLen, aur)
printDownloads("Aur Make", aurMakeLen, aurMake)
2018-02-05 21:05:58 +01:00
}
func printDownloads(repoName string, length int, packages string) {
if length < 1 {
return
2018-02-05 21:05:58 +01:00
}
repoInfo := bold(blue(
"[" + repoName + ": " + strconv.Itoa(length) + "]"))
fmt.Println(repoInfo + cyan(packages))
2018-02-05 21:05:58 +01:00
}
// PrintInfo prints package info like pacman -Si.
func PrintInfo(a *rpc.Pkg) {
fmt.Println(bold("Repository :"), "aur")
fmt.Println(bold("Name :"), a.Name)
fmt.Println(bold("Version :"), a.Version)
fmt.Println(bold("Description :"), a.Description)
fmt.Println(bold("URL :"), a.URL)
fmt.Println(bold("Licenses :"), strings.Join(a.License, " "))
2018-03-23 08:11:57 +01:00
fmt.Println(bold("Provides :"), strings.Join(a.Provides, " "))
fmt.Println(bold("Depends On :"), strings.Join(a.Depends, " "))
fmt.Println(bold("Make Deps :"), strings.Join(a.MakeDepends, " "))
fmt.Println(bold("Check Deps :"), strings.Join(a.CheckDepends, " "))
fmt.Println(bold("Optional Deps :"), strings.Join(a.OptDepends, " "))
fmt.Println(bold("Conflicts With :"), strings.Join(a.Conflicts, " "))
fmt.Println(bold("Maintainer :"), a.Maintainer)
fmt.Println(bold("Votes :"), a.NumVotes)
fmt.Println(bold("Popularity :"), a.Popularity)
if a.OutOfDate != 0 {
fmt.Println(bold("Out-of-date :"), "Yes", "["+formatTime(a.OutOfDate)+"]")
}
fmt.Println()
}
// BiggestPackages prints the name of the ten biggest packages in the system.
func biggestPackages() {
localDb, err := alpmHandle.LocalDb()
if err != nil {
return
}
pkgCache := localDb.PkgCache()
pkgS := pkgCache.SortBySize().Slice()
if len(pkgS) < 10 {
return
}
for i := 0; i < 10; i++ {
fmt.Println(bold(pkgS[i].Name()) + ": " + cyan(human(pkgS[i].ISize())))
}
// Could implement size here as well, but we just want the general idea
}
2017-10-19 07:59:26 +02:00
// localStatistics prints installed packages statistics.
func localStatistics() error {
info, err := statistics()
if err != nil {
return err
}
_, _, _, remoteNames, err := filterPackages()
if err != nil {
return err
}
fmt.Printf(bold("Yay version v%s\n"), version)
fmt.Println(bold(cyan("===========================================")))
fmt.Println(bold(green("Total installed packages: ")) + cyan(strconv.Itoa(info.Totaln)))
fmt.Println(bold(green("Total foreign installed packages: ")) + cyan(strconv.Itoa(len(remoteNames))))
fmt.Println(bold(green("Explicitly installed packages: ")) + cyan(strconv.Itoa(info.Expln)))
fmt.Println(bold(green("Total Size occupied by packages: ")) + cyan(human(info.TotalSize)))
fmt.Println(bold(cyan("===========================================")))
fmt.Println(bold(green("Ten biggest packages:")))
2017-10-19 07:59:26 +02:00
biggestPackages()
fmt.Println(bold(cyan("===========================================")))
2017-10-19 07:59:26 +02:00
aurInfoPrint(remoteNames)
2017-10-19 07:59:26 +02:00
return nil
}
New install algorithm I have replaced the old install and dependancy algorithms with a new design that attemps to be more pacaur like. Mostly in minimizing user input. Ask every thing first then do everything with no need for more user input. It is not yet fully complete but is finished enough so that it works, should not fail in most cases and provides a base for more contributors to help address the existing problems. The new install chain is as follows: Source info about the provided targets Fetch a list of all dependancies needed to install targets I put alot of effort into fetching the dependancy tree while making the least amount of aur requests as possible. I'm actually very happy with how it turned out and yay wil now resolve dependancies noticably faster than pacaur when there are many aur dependancies. Install repo targets by passing to pacman Print dependancy tree and ask to confirm Ask to clean build if directory already exists Download all pkgbuilds Ask to edit all pkgbuilds Ask to continue with the install Download the sources for each packagebuild Build and install every package using -s to get repo deps and -i to install Ask to remove make dependancies There are still a lot of things that need to be done for a fully working system. Here are the problems I found with this system, either new or existing: Formating I am not so good at formatting myself, I thought best to leave it until last so I could get feedback on how it should look and help implementing it. Dependancy tree The dependancy tree is usually correct although I have noticed times where it doesnt detect all the dependancies that it should. I have only noticed this when there are circular dependancies so i think this might be the cause. It's not a big deal currently because makepkg -i installed repo deps for us which handles the repo deps for us and will get the correct ones. So yay might not list all the dependancies. but they will get installed so I consider this a visual bug. I have yet to see any circular dependancies in the AUR so I can not say what will happend but I#m guessing that it will break. Versioned packages/dependencies Targets and dependancies with version constriants such as 'linux>=4.1' will not be checked on the aur side of things but will be checked on the repo side. Ignorepkg/Ignoregroup Currently I do not handle this in any way but it shouldn't be too hard to implement. Conflict checking This is not currently implemented either Split Paclages Split packages are not Handles properly. If we only specify one package so install from a split package makepkg -i ends up installing them all anyway. If we specify more than one (n) package it will actually build the package base n times and reinstall every split package n times. Makepkg To get things working I decided to keep using the makepkg -i method. I plan to eventually replace this with a pacman -U based method. This should allow passing args such as --dbpath and --config to aur packages aswell as help solve some problems such as the split packages. Clean build I plan to improve the clean build choice to be a little more smart and instead of check if the directory exists, check if the package is already build and if so skip the build all together.
2018-01-17 22:48:23 +01:00
//TODO: Make it less hacky
func printNumberOfUpdates() error {
//todo
warnings := &aurWarnings{}
2018-02-19 18:36:33 +01:00
old := os.Stdout // keep backup of the real stdout
os.Stdout = nil
aurUp, repoUp, err := upList(warnings)
os.Stdout = old // restoring the real stdout
if err != nil {
return err
}
fmt.Println(len(aurUp) + len(repoUp))
2018-02-21 09:41:25 +01:00
return nil
}
//TODO: Make it less hacky
func printUpdateList(parser *arguments) error {
warnings := &aurWarnings{}
old := os.Stdout // keep backup of the real stdout
os.Stdout = nil
2018-02-19 18:36:33 +01:00
_, _, localNames, remoteNames, err := filterPackages()
if err != nil {
return err
}
aurUp, repoUp, err := upList(warnings)
os.Stdout = old // restoring the real stdout
if err != nil {
return err
}
noTargets := len(parser.targets) == 0
if !parser.existsArg("m", "foreigne") {
for _, pkg := range repoUp {
if noTargets || parser.targets.get(pkg.Name) {
fmt.Printf("%s %s -> %s\n", bold(pkg.Name), green(pkg.LocalVersion), green(pkg.RemoteVersion))
delete(parser.targets, pkg.Name)
}
}
}
if !parser.existsArg("n", "native") {
for _, pkg := range aurUp {
if noTargets || parser.targets.get(pkg.Name) {
fmt.Printf("%s %s -> %s\n", bold(pkg.Name), green(pkg.LocalVersion), green(pkg.RemoteVersion))
delete(parser.targets, pkg.Name)
}
}
}
missing := false
outer:
for pkg := range parser.targets {
for _, name := range localNames {
if name == pkg {
continue outer
}
}
for _, name := range remoteNames {
if name == pkg {
continue outer
}
}
2018-03-22 17:39:27 +01:00
fmt.Println(red(bold("error:")), "package '"+pkg+"' was not found")
missing = true
}
if missing {
return fmt.Errorf("")
}
2018-02-19 18:36:33 +01:00
return nil
}
type Item struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
PubDate string `xml:"pubDate"`
Creator string `xml:"dc:creator"`
}
func (item Item) Print() error {
date, err := time.Parse(time.RFC1123Z, item.PubDate)
if err != nil {
return err
}
fd := formatTime(int(date.Unix()))
fmt.Println(bold(magenta(fd)), bold(strings.TrimSpace(item.Title)))
//fmt.Println(strings.TrimSpace(item.Link))
if !cmdArgs.existsArg("q", "quiet") {
desc := strings.TrimSpace(parseNews(item.Description))
fmt.Println(desc)
}
return nil
}
type Channel struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
Language string `xml:"language"`
Lastbuilddate string `xml:"lastbuilddate"`
Items []Item `xml:"item"`
}
2018-05-06 02:26:03 +02:00
type rss struct {
Channel Channel `xml:"channel"`
2018-05-06 02:26:03 +02:00
}
func printNewsFeed() error {
resp, err := http.Get("https://archlinux.org/feeds/news")
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
rss := rss{}
2018-05-06 04:25:23 +02:00
d := xml.NewDecoder(bytes.NewReader(body))
err = d.Decode(&rss)
2018-05-06 02:26:03 +02:00
if err != nil {
return err
}
if config.SortMode == BottomUp {
for i := len(rss.Channel.Items) - 1; i >= 0; i-- {
err := rss.Channel.Items[i].Print()
if err != nil {
return err
}
}
} else {
for i := 0; i < len(rss.Channel.Items); i++ {
err := rss.Channel.Items[i].Print()
if err != nil {
return err
}
2018-05-06 04:25:23 +02:00
}
2018-05-06 02:26:03 +02:00
}
return nil
}
2018-05-04 12:36:14 +02:00
// Formats a unix timestamp to ISO 8601 date (yyyy-mm-dd)
func formatTime(i int) string {
t := time.Unix(int64(i), 0)
2018-05-04 12:36:14 +02:00
return t.Format("2006-01-02")
}
const (
redCode = "\x1b[31m"
greenCode = "\x1b[32m"
yellowCode = "\x1b[33m"
blueCode = "\x1b[34m"
magentaCode = "\x1b[35m"
cyanCode = "\x1b[36m"
boldCode = "\x1b[1m"
resetCode = "\x1b[0m"
)
func stylize(startCode, in string) string {
if useColor {
return startCode + in + resetCode
}
return in
}
func red(in string) string {
return stylize(redCode, in)
}
func green(in string) string {
return stylize(greenCode, in)
}
func yellow(in string) string {
return stylize(yellowCode, in)
2018-01-26 12:30:33 +01:00
}
func blue(in string) string {
return stylize(blueCode, in)
}
func cyan(in string) string {
return stylize(cyanCode, in)
}
func magenta(in string) string {
return stylize(magentaCode, in)
}
func bold(in string) string {
return stylize(boldCode, in)
}
// Colours text using a hashing algorithm. The same text will always produce the
// same colour while different text will produce a different colour.
func colourHash(name string) (output string) {
if !useColor {
return name
}
var hash = 5381
for i := 0; i < len(name); i++ {
hash = int(name[i]) + ((hash << 5) + (hash))
}
return fmt.Sprintf("\x1b[%dm%s\x1b[0m", hash%6+31, name)
}