1
0
mirror of https://github.com/Jguer/yay.git synced 2025-08-16 03:27:16 +02:00

fix(ci): implement stricter linting settings

This commit is contained in:
jguer 2020-05-02 16:17:20 +02:00
parent e7b1fe4d53
commit 9fccdcb30f
No known key found for this signature in database
GPG Key ID: 6D6CC9BEA8556B35
29 changed files with 443 additions and 415 deletions

View File

@ -13,13 +13,20 @@ jobs:
name: Lint and test yay name: Lint and test yay
# This job runs on Linux # This job runs on Linux
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: samip537/archlinux:devel container:
image: samip537/archlinux:devel
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v2 uses: actions/checkout@v2
- uses: actions/cache@v1
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go-
- name: Run Build and tests - name: Run Build and tests
run: | run: |
pacman -Sy --noconfirm go pacman -Sy --noconfirm go
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s v1.25.1 curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s v1.26.0
./bin/golangci-lint run ./... ./bin/golangci-lint run ./...
make test make test

View File

@ -5,8 +5,8 @@ linters-settings:
lines: 100 lines: 100
statements: 50 statements: 50
goconst: goconst:
min-len: 2 min-len: 3
min-occurrences: 2 min-occurrences: 4
gocritic: gocritic:
enabled-tags: enabled-tags:
- diagnostic - diagnostic
@ -48,18 +48,13 @@ linters:
- bodyclose - bodyclose
- deadcode - deadcode
- depguard - depguard
- dogsled
- dupl - dupl
- errcheck - errcheck
- funlen
- gochecknoinits - gochecknoinits
- goconst
- gocritic - gocritic
- gocyclo
- gofmt - gofmt
- goimports - goimports
- golint - golint
- gomnd
- goprintffuncname - goprintffuncname
- gosec - gosec
- gosimple - gosimple
@ -70,7 +65,6 @@ linters:
- misspell - misspell
- nakedret - nakedret
- rowserrcheck - rowserrcheck
- scopelint
- staticcheck - staticcheck
- structcheck - structcheck
- stylecheck - stylecheck
@ -80,10 +74,18 @@ linters:
- unused - unused
- varcheck - varcheck
- whitespace - whitespace
- godox
- maligned
- prealloc - prealloc
- maligned
# disabled want to fix
#- scopelint
#- gomnd
#- goconst
#- gocyclo
#- funlen
#- dogsled
# disabled for now
# - godox
issues: issues:
# Excluding configuration per-path, per-linter, per-text and per-source # Excluding configuration per-path, per-linter, per-text and per-source
@ -92,9 +94,9 @@ issues:
linters: linters:
- gomnd - gomnd
exclude:
- G204
- commentedOutCode
run: run:
skip-dirs: tests: false
- test/testdata_etc
- internal/cache
- internal/renameio
- internal/robustio

View File

@ -17,7 +17,7 @@ VERSION ?= ${MAJORVERSION}.${MINORVERSION}.${PATCHVERSION}
GOFLAGS := -v -mod=mod GOFLAGS := -v -mod=mod
EXTRA_GOFLAGS ?= EXTRA_GOFLAGS ?=
LDFLAGS := $(LDFLAGS) -X "main.version=${VERSION}" LDFLAGS := $(LDFLAGS) -X "main.yayVersion=${VERSION}"
RELEASE_DIR := ${PKGNAME}_${VERSION}_${ARCH} RELEASE_DIR := ${PKGNAME}_${VERSION}_${ARCH}
PACKAGE := $(RELEASE_DIR).tar.gz PACKAGE := $(RELEASE_DIR).tar.gz

View File

@ -58,7 +58,6 @@ func cleanRemove(pkgNames []string) error {
} }
func syncClean(parser *arguments) error { func syncClean(parser *arguments) error {
var err error
keepInstalled := false keepInstalled := false
keepCurrent := false keepCurrent := false
@ -92,11 +91,13 @@ func syncClean(parser *arguments) error {
fmt.Printf("\nBuild directory: %s\n", config.BuildDir) fmt.Printf("\nBuild directory: %s\n", config.BuildDir)
if continueTask(question, true) { if continueTask(question, true) {
err = cleanAUR(keepInstalled, keepCurrent, removeAll) if err := cleanAUR(keepInstalled, keepCurrent, removeAll); err != nil {
return err
}
} }
if err != nil || removeAll { if removeAll {
return err return nil
} }
if continueTask("Do you want to remove ALL untracked AUR files?", true) { if continueTask("Do you want to remove ALL untracked AUR files?", true) {
@ -136,9 +137,9 @@ func cleanAUR(keepInstalled, keepCurrent, removeAll bool) error {
// Querying the AUR is slow and needs internet so don't do it if we // Querying the AUR is slow and needs internet so don't do it if we
// don't need to. // don't need to.
if keepCurrent { if keepCurrent {
info, err := aurInfo(cachedPackages, &aurWarnings{}) info, errInfo := aurInfo(cachedPackages, &aurWarnings{})
if err != nil { if errInfo != nil {
return err return errInfo
} }
for _, pkg := range info { for _, pkg := range info {

50
cmd.go
View File

@ -7,6 +7,7 @@ import (
"os" "os"
alpm "github.com/Jguer/go-alpm" alpm "github.com/Jguer/go-alpm"
"github.com/Jguer/yay/v9/pkg/completion" "github.com/Jguer/yay/v9/pkg/completion"
"github.com/Jguer/yay/v9/pkg/intrange" "github.com/Jguer/yay/v9/pkg/intrange"
) )
@ -134,10 +135,9 @@ getpkgbuild specific options:
-f --force Force download for existing ABS packages`) -f --force Force download for existing ABS packages`)
} }
func handleCmd() (err error) { func handleCmd() error {
if cmdArgs.existsArg("h", "help") { if cmdArgs.existsArg("h", "help") {
err = handleHelp() return handleHelp()
return
} }
if config.SudoLoop && cmdArgs.needRoot() { if config.SudoLoop && cmdArgs.needRoot() {
@ -147,33 +147,30 @@ func handleCmd() (err error) {
switch cmdArgs.op { switch cmdArgs.op {
case "V", "version": case "V", "version":
handleVersion() handleVersion()
return nil
case "D", "database": case "D", "database":
err = show(passToPacman(cmdArgs)) return show(passToPacman(cmdArgs))
case "F", "files": case "F", "files":
err = show(passToPacman(cmdArgs)) return show(passToPacman(cmdArgs))
case "Q", "query": case "Q", "query":
err = handleQuery() return handleQuery()
case "R", "remove": case "R", "remove":
err = handleRemove() return handleRemove()
case "S", "sync": case "S", "sync":
err = handleSync() return handleSync()
case "T", "deptest": case "T", "deptest":
err = show(passToPacman(cmdArgs)) return show(passToPacman(cmdArgs))
case "U", "upgrade": case "U", "upgrade":
err = show(passToPacman(cmdArgs)) return show(passToPacman(cmdArgs))
case "G", "getpkgbuild": case "G", "getpkgbuild":
err = handleGetpkgbuild() return handleGetpkgbuild()
case "P", "show": case "P", "show":
err = handlePrint() return handlePrint()
case "Y", "--yay": case "Y", "--yay":
err = handleYay() return handleYay()
default:
//this means we allowed an op but not implement it
//if this happens it an error in the code and not the usage
err = fmt.Errorf("unhandled operation")
} }
return return fmt.Errorf("unhandled operation")
} }
func handleQuery() error { func handleQuery() error {
@ -192,7 +189,7 @@ func handleHelp() error {
} }
func handleVersion() { func handleVersion() {
fmt.Printf("yay v%s - libalpm v%s\n", version, alpm.Version()) fmt.Printf("yay v%s - libalpm v%s\n", yayVersion, alpm.Version())
} }
func handlePrint() (err error) { func handlePrint() (err error) {
@ -222,7 +219,6 @@ func handlePrint() (err error) {
} }
func handleYay() error { func handleYay() error {
//_, options, targets := cmdArgs.formatArgs()
if cmdArgs.existsArg("gendb") { if cmdArgs.existsArg("gendb") {
return createDevelDB() return createDevelDB()
} }
@ -318,7 +314,7 @@ func displayNumberMenu(pkgS []string) (err error) {
} }
if lenpq == 0 && lenaq == 0 { if lenpq == 0 && lenaq == 0 {
return fmt.Errorf("No packages match search") return fmt.Errorf("no packages match search")
} }
switch config.SortMode { switch config.SortMode {
@ -337,7 +333,7 @@ func displayNumberMenu(pkgS []string) (err error) {
pq.printSearch() pq.printSearch()
} }
default: default:
return fmt.Errorf("Invalid Sort Mode. Fix with yay -Y --bottomup --save") return fmt.Errorf("invalid sort mode. Fix with yay -Y --bottomup --save")
} }
if aurErr != nil { if aurErr != nil {
@ -355,7 +351,7 @@ func displayNumberMenu(pkgS []string) (err error) {
return err return err
} }
if overflow { if overflow {
return fmt.Errorf("Input too long") return fmt.Errorf("input too long")
} }
include, exclude, _, otherExclude := intrange.ParseNumberMenu(string(numberBuf)) include, exclude, _, otherExclude := intrange.ParseNumberMenu(string(numberBuf))
@ -371,7 +367,7 @@ func displayNumberMenu(pkgS []string) (err error) {
case bottomUp: case bottomUp:
target = len(pq) - i target = len(pq) - i
default: default:
return fmt.Errorf("Invalid Sort Mode. Fix with yay -Y --bottomup --save") return fmt.Errorf("invalid sort mode. Fix with yay -Y --bottomup --save")
} }
if (isInclude && include.Get(target)) || (!isInclude && !exclude.Get(target)) { if (isInclude && include.Get(target)) || (!isInclude && !exclude.Get(target)) {
@ -379,7 +375,7 @@ func displayNumberMenu(pkgS []string) (err error) {
} }
} }
for i, pkg := range aq { for i := range aq {
var target int var target int
switch config.SortMode { switch config.SortMode {
@ -388,11 +384,11 @@ func displayNumberMenu(pkgS []string) (err error) {
case bottomUp: case bottomUp:
target = len(aq) - i + len(pq) target = len(aq) - i + len(pq)
default: default:
return fmt.Errorf("Invalid Sort Mode. Fix with yay -Y --bottomup --save") return fmt.Errorf("invalid sort mode. Fix with yay -Y --bottomup --save")
} }
if (isInclude && include.Get(target)) || (!isInclude && !exclude.Get(target)) { if (isInclude && include.Get(target)) || (!isInclude && !exclude.Get(target)) {
arguments.addTarget("aur/" + pkg.Name) arguments.addTarget("aur/" + aq[i].Name)
} }
} }

View File

@ -47,7 +47,6 @@ type Configuration struct {
PacmanConf string `json:"pacmanconf"` PacmanConf string `json:"pacmanconf"`
ReDownload string `json:"redownload"` ReDownload string `json:"redownload"`
ReBuild string `json:"rebuild"` ReBuild string `json:"rebuild"`
BatchInstall bool `json:"batchinstall"`
AnswerClean string `json:"answerclean"` AnswerClean string `json:"answerclean"`
AnswerDiff string `json:"answerdiff"` AnswerDiff string `json:"answerdiff"`
AnswerEdit string `json:"answeredit"` AnswerEdit string `json:"answeredit"`
@ -79,9 +78,10 @@ type Configuration struct {
EditMenu bool `json:"editmenu"` EditMenu bool `json:"editmenu"`
CombinedUpgrade bool `json:"combinedupgrade"` CombinedUpgrade bool `json:"combinedupgrade"`
UseAsk bool `json:"useask"` UseAsk bool `json:"useask"`
BatchInstall bool `json:"batchinstall"`
} }
var version = "9.4.3" var yayVersion = "9.4.3"
// configFileName holds the name of the config file. // configFileName holds the name of the config file.
const configFileName string = "config.json" const configFileName string = "config.json"
@ -142,7 +142,7 @@ func (config *Configuration) saveConfig() error {
} }
func defaultSettings() *Configuration { func defaultSettings() *Configuration {
config := &Configuration{ newConfig := &Configuration{
AURURL: "https://aur.archlinux.org", AURURL: "https://aur.archlinux.org",
BuildDir: "$HOME/.cache/yay", BuildDir: "$HOME/.cache/yay",
ABSDir: "$HOME/.cache/yay/abs", ABSDir: "$HOME/.cache/yay/abs",
@ -191,7 +191,7 @@ func defaultSettings() *Configuration {
config.BuildDir = "$XDG_CACHE_HOME/yay" config.BuildDir = "$XDG_CACHE_HOME/yay"
} }
return config return newConfig
} }
func (config *Configuration) expandEnv() { func (config *Configuration) expandEnv() {
@ -223,7 +223,7 @@ func (config *Configuration) expandEnv() {
} }
// Editor returns the preferred system editor. // Editor returns the preferred system editor.
func editor() (string, []string) { func editor() (editor string, args []string) {
switch { switch {
case config.Editor != "": case config.Editor != "":
editor, err := exec.LookPath(config.Editor) editor, err := exec.LookPath(config.Editor)
@ -256,7 +256,13 @@ func editor() (string, []string) {
default: default:
fmt.Fprintln(os.Stderr) fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, bold(red(arrow)), bold(cyan("$EDITOR")), bold("is not set")) fmt.Fprintln(os.Stderr, bold(red(arrow)), bold(cyan("$EDITOR")), bold("is not set"))
fmt.Fprintln(os.Stderr, bold(red(arrow))+bold(" Please add ")+bold(cyan("$EDITOR"))+bold(" or ")+bold(cyan("$VISUAL"))+bold(" to your environment variables.")) fmt.Fprintln(os.Stderr,
bold(red(arrow))+
bold(" Please add ")+
bold(cyan("$EDITOR"))+
bold(" or ")+
bold(cyan("$VISUAL"))+
bold(" to your environment variables."))
for { for {
fmt.Print(green(bold(arrow + " Edit PKGBUILD with: "))) fmt.Print(green(bold(arrow + " Edit PKGBUILD with: ")))
@ -325,13 +331,13 @@ func getInput(defaultValue string) (string, error) {
} }
if overflow { if overflow {
return "", fmt.Errorf("Input too long") return "", fmt.Errorf("input too long")
} }
return string(buf), nil return string(buf), nil
} }
func (config Configuration) String() string { func (config *Configuration) String() string {
var buf bytes.Buffer var buf bytes.Buffer
enc := json.NewEncoder(&buf) enc := json.NewEncoder(&buf)
enc.SetIndent("", "\t") enc.SetIndent("", "\t")
@ -365,8 +371,7 @@ func toUsage(usages []string) alpm.Usage {
return ret return ret
} }
func configureAlpm(conf *pacmanconf.Config) error { func configureAlpm() error {
// TODO: set SigLevel // TODO: set SigLevel
// sigLevel := alpm.SigPackage | alpm.SigPackageOptional | alpm.SigDatabase | alpm.SigDatabaseOptional // sigLevel := alpm.SigPackage | alpm.SigPackageOptional | alpm.SigDatabase | alpm.SigDatabaseOptional
// localFileSigLevel := alpm.SigUseDefault // localFileSigLevel := alpm.SigUseDefault
@ -381,7 +386,6 @@ func configureAlpm(conf *pacmanconf.Config) error {
db.SetServers(repo.Servers) db.SetServers(repo.Servers)
db.SetUsage(toUsage(repo.Usage)) db.SetUsage(toUsage(repo.Usage))
} }
if err := alpmHandle.SetCacheDirs(pacmanConf.CacheDir); err != nil { if err := alpmHandle.SetCacheDirs(pacmanConf.CacheDir); err != nil {

6
dep.go
View File

@ -40,9 +40,7 @@ func (q providers) Swap(i, j int) {
q.Pkgs[i], q.Pkgs[j] = q.Pkgs[j], q.Pkgs[i] q.Pkgs[i], q.Pkgs[j] = q.Pkgs[j], q.Pkgs[i]
} }
func splitDep(dep string) (string, string, string) { func splitDep(dep string) (pkg, mod, ver string) {
mod := ""
split := strings.FieldsFunc(dep, func(c rune) bool { split := strings.FieldsFunc(dep, func(c rune) bool {
match := c == '>' || c == '<' || c == '=' match := c == '>' || c == '<' || c == '='
@ -140,7 +138,7 @@ func satisfiesRepo(dep string, pkg *alpm.Package) bool {
} }
// split apart db/package to db and package // split apart db/package to db and package
func splitDBFromName(pkg string) (string, string) { func splitDBFromName(pkg string) (db, name string) {
split := strings.SplitN(pkg, "/", 2) split := strings.SplitN(pkg, "/", 2)
if len(split) == 2 { if len(split) == 2 {

View File

@ -7,10 +7,11 @@ import (
"sync" "sync"
alpm "github.com/Jguer/go-alpm" alpm "github.com/Jguer/go-alpm"
"github.com/Jguer/yay/v9/pkg/stringset" "github.com/Jguer/yay/v9/pkg/stringset"
) )
func (dp *depPool) checkInnerConflict(name string, conflict string, conflicts stringset.MapStringSet) { func (dp *depPool) checkInnerConflict(name, conflict string, conflicts stringset.MapStringSet) {
for _, pkg := range dp.Aur { for _, pkg := range dp.Aur {
if pkg.Name == name { if pkg.Name == name {
continue continue
@ -32,7 +33,7 @@ func (dp *depPool) checkInnerConflict(name string, conflict string, conflicts st
} }
} }
func (dp *depPool) checkForwardConflict(name string, conflict string, conflicts stringset.MapStringSet) { func (dp *depPool) checkForwardConflict(name, conflict string, conflicts stringset.MapStringSet) {
_ = dp.LocalDB.PkgCache().ForEach(func(pkg alpm.Package) error { _ = dp.LocalDB.PkgCache().ForEach(func(pkg alpm.Package) error {
if pkg.Name() == name || dp.hasPackage(pkg.Name()) { if pkg.Name() == name || dp.hasPackage(pkg.Name()) {
return nil return nil
@ -50,7 +51,7 @@ func (dp *depPool) checkForwardConflict(name string, conflict string, conflicts
}) })
} }
func (dp *depPool) checkReverseConflict(name string, conflict string, conflicts stringset.MapStringSet) { func (dp *depPool) checkReverseConflict(name, conflict string, conflicts stringset.MapStringSet) {
for _, pkg := range dp.Aur { for _, pkg := range dp.Aur {
if pkg.Name == name { if pkg.Name == name {
continue continue
@ -159,7 +160,6 @@ func (dp *depPool) CheckConflicts() (stringset.MapStringSet, error) {
fmt.Println(str) fmt.Println(str)
} }
} }
if len(conflicts) != 0 { if len(conflicts) != 0 {
@ -175,7 +175,6 @@ func (dp *depPool) CheckConflicts() (stringset.MapStringSet, error) {
fmt.Println(str) fmt.Println(str)
} }
} }
// Add the inner conflicts to the conflicts // Add the inner conflicts to the conflicts
@ -191,7 +190,7 @@ func (dp *depPool) CheckConflicts() (stringset.MapStringSet, error) {
if len(conflicts) > 0 { if len(conflicts) > 0 {
if !config.UseAsk { if !config.UseAsk {
if config.NoConfirm { if config.NoConfirm {
return nil, fmt.Errorf("Package conflicts can not be resolved with noconfirm, aborting") return nil, fmt.Errorf("package conflicts can not be resolved with noconfirm, aborting")
} }
fmt.Fprintln(os.Stderr) fmt.Fprintln(os.Stderr)
@ -276,7 +275,6 @@ func (dp *depPool) CheckMissing() error {
fmt.Println(bold(red(arrow+" Error: ")) + "Could not find all required packages:") fmt.Println(bold(red(arrow+" Error: ")) + "Could not find all required packages:")
for dep, trees := range missing.Missing { for dep, trees := range missing.Missing {
for _, tree := range trees { for _, tree := range trees {
fmt.Print(" ", cyan(dep)) fmt.Print(" ", cyan(dep))
if len(tree) == 0 { if len(tree) == 0 {

View File

@ -2,8 +2,9 @@ package main
import ( import (
alpm "github.com/Jguer/go-alpm" alpm "github.com/Jguer/go-alpm"
"github.com/Jguer/yay/v9/pkg/stringset"
rpc "github.com/mikkeloscar/aur" rpc "github.com/mikkeloscar/aur"
"github.com/Jguer/yay/v9/pkg/stringset"
) )
// Base is an AUR base package // Base is an AUR base package

View File

@ -6,8 +6,9 @@ import (
"sync" "sync"
alpm "github.com/Jguer/go-alpm" alpm "github.com/Jguer/go-alpm"
"github.com/Jguer/yay/v9/pkg/stringset"
rpc "github.com/mikkeloscar/aur" rpc "github.com/mikkeloscar/aur"
"github.com/Jguer/yay/v9/pkg/stringset"
) )
type target struct { type target struct {
@ -19,13 +20,13 @@ type target struct {
func toTarget(pkg string) target { func toTarget(pkg string) target {
db, dep := splitDBFromName(pkg) db, dep := splitDBFromName(pkg)
name, mod, version := splitDep(dep) name, mod, depVersion := splitDep(dep)
return target{ return target{
db, DB: db,
name, Name: name,
mod, Mod: mod,
version, Version: depVersion,
} }
} }
@ -198,10 +199,10 @@ func (dp *depPool) findProvides(pkgs stringset.StringSet) error {
return return
} }
for _, result := range results { for iR := range results {
mux.Lock() mux.Lock()
if _, ok := dp.AurCache[result.Name]; !ok { if _, ok := dp.AurCache[results[iR].Name]; !ok {
pkgs.Set(result.Name) pkgs.Set(results[iR].Name)
} }
mux.Unlock() mux.Unlock()
} }
@ -319,7 +320,6 @@ func (dp *depPool) resolveAURPackages(pkgs stringset.StringSet, explicit bool) e
// assume it's in the aur // assume it's in the aur
// ditch the versioning because the RPC can't handle it // ditch the versioning because the RPC can't handle it
newAURPackages.Set(dep) newAURPackages.Set(dep)
} }
err = dp.resolveAURPackages(newAURPackages, false) err = dp.resolveAURPackages(newAURPackages, false)
@ -388,13 +388,12 @@ func (dp *depPool) findSatisfierAur(dep string) *rpc.Pkg {
func (dp *depPool) findSatisfierAurCache(dep string) *rpc.Pkg { func (dp *depPool) findSatisfierAurCache(dep string) *rpc.Pkg {
depName, _, _ := splitDep(dep) depName, _, _ := splitDep(dep)
seen := make(stringset.StringSet) seen := make(stringset.StringSet)
providers := makeProviders(depName) providerSlice := makeProviders(depName)
if dp.LocalDB.Pkg(depName) != nil { if dp.LocalDB.Pkg(depName) != nil {
if pkg, ok := dp.AurCache[dep]; ok && pkgSatisfies(pkg.Name, pkg.Version, dep) { if pkg, ok := dp.AurCache[dep]; ok && pkgSatisfies(pkg.Name, pkg.Version, dep) {
return pkg return pkg
} }
} }
if cmdArgs.op == "Y" || cmdArgs.op == "yay" { if cmdArgs.op == "Y" || cmdArgs.op == "yay" {
@ -415,31 +414,31 @@ func (dp *depPool) findSatisfierAurCache(dep string) *rpc.Pkg {
} }
if pkgSatisfies(pkg.Name, pkg.Version, dep) { if pkgSatisfies(pkg.Name, pkg.Version, dep) {
providers.Pkgs = append(providers.Pkgs, pkg) providerSlice.Pkgs = append(providerSlice.Pkgs, pkg)
seen.Set(pkg.Name) seen.Set(pkg.Name)
continue continue
} }
for _, provide := range pkg.Provides { for _, provide := range pkg.Provides {
if provideSatisfies(provide, dep) { if provideSatisfies(provide, dep) {
providers.Pkgs = append(providers.Pkgs, pkg) providerSlice.Pkgs = append(providerSlice.Pkgs, pkg)
seen.Set(pkg.Name) seen.Set(pkg.Name)
continue continue
} }
} }
} }
if !config.Provides && providers.Len() >= 1 { if !config.Provides && providerSlice.Len() >= 1 {
return providers.Pkgs[0] return providerSlice.Pkgs[0]
} }
if providers.Len() == 1 { if providerSlice.Len() == 1 {
return providers.Pkgs[0] return providerSlice.Pkgs[0]
} }
if providers.Len() > 1 { if providerSlice.Len() > 1 {
sort.Sort(providers) sort.Sort(providerSlice)
return providerMenu(dep, providers) return providerMenu(dep, providerSlice)
} }
return nil return nil

View File

@ -9,6 +9,7 @@ import (
"sync" "sync"
alpm "github.com/Jguer/go-alpm" alpm "github.com/Jguer/go-alpm"
"github.com/Jguer/yay/v9/pkg/multierror" "github.com/Jguer/yay/v9/pkg/multierror"
) )
@ -16,7 +17,7 @@ const gitDiffRefName = "AUR_SEEN"
// Update the YAY_DIFF_REVIEW ref to HEAD. We use this ref to determine which diff were // Update the YAY_DIFF_REVIEW ref to HEAD. We use this ref to determine which diff were
// reviewed by the user // reviewed by the user
func gitUpdateSeenRef(path string, name string) error { func gitUpdateSeenRef(path, name string) error {
_, stderr, err := capture(passToGit(filepath.Join(path, name), "update-ref", gitDiffRefName, "HEAD")) _, stderr, err := capture(passToGit(filepath.Join(path, name), "update-ref", gitDiffRefName, "HEAD"))
if err != nil { if err != nil {
return fmt.Errorf("%s%s", stderr, err) return fmt.Errorf("%s%s", stderr, err)
@ -26,14 +27,14 @@ func gitUpdateSeenRef(path string, name string) error {
// Return wether or not we have reviewed a diff yet. It checks for the existence of // Return wether or not we have reviewed a diff yet. It checks for the existence of
// YAY_DIFF_REVIEW in the git ref-list // YAY_DIFF_REVIEW in the git ref-list
func gitHasLastSeenRef(path string, name string) bool { func gitHasLastSeenRef(path, name string) bool {
_, _, err := capture(passToGit(filepath.Join(path, name), "rev-parse", "--quiet", "--verify", gitDiffRefName)) _, _, err := capture(passToGit(filepath.Join(path, name), "rev-parse", "--quiet", "--verify", gitDiffRefName))
return err == nil return err == nil
} }
// Returns the last reviewed hash. If YAY_DIFF_REVIEW exists it will return this hash. // Returns the last reviewed hash. If YAY_DIFF_REVIEW exists it will return this hash.
// If it does not it will return empty tree as no diff have been reviewed yet. // If it does not it will return empty tree as no diff have been reviewed yet.
func getLastSeenHash(path string, name string) (string, error) { func getLastSeenHash(path, name string) (string, error) {
if gitHasLastSeenRef(path, name) { if gitHasLastSeenRef(path, name) {
stdout, stderr, err := capture(passToGit(filepath.Join(path, name), "rev-parse", gitDiffRefName)) stdout, stderr, err := capture(passToGit(filepath.Join(path, name), "rev-parse", gitDiffRefName))
if err != nil { if err != nil {
@ -48,7 +49,7 @@ func getLastSeenHash(path string, name string) (string, error) {
// Check whether or not a diff exists between the last reviewed diff and // Check whether or not a diff exists between the last reviewed diff and
// HEAD@{upstream} // HEAD@{upstream}
func gitHasDiff(path string, name string) (bool, error) { func gitHasDiff(path, name string) (bool, error) {
if gitHasLastSeenRef(path, name) { if gitHasLastSeenRef(path, name) {
stdout, stderr, err := capture(passToGit(filepath.Join(path, name), "rev-parse", gitDiffRefName, "HEAD@{upstream}")) stdout, stderr, err := capture(passToGit(filepath.Join(path, name), "rev-parse", gitDiffRefName, "HEAD@{upstream}"))
if err != nil { if err != nil {
@ -66,14 +67,12 @@ func gitHasDiff(path string, name string) (bool, error) {
} }
// TODO: yay-next passes args through the header, use that to unify ABS and AUR // TODO: yay-next passes args through the header, use that to unify ABS and AUR
func gitDownloadABS(url string, path string, name string) (bool, error) { func gitDownloadABS(url, path, name string) (bool, error) {
err := os.MkdirAll(path, 0755) if err := os.MkdirAll(path, 0755); err != nil {
if err != nil {
return false, err return false, err
} }
_, err = os.Stat(filepath.Join(path, name)) if _, errExist := os.Stat(filepath.Join(path, name)); os.IsNotExist(errExist) {
if os.IsNotExist(err) {
cmd := passToGit(path, "clone", "--no-progress", "--single-branch", cmd := passToGit(path, "clone", "--no-progress", "--single-branch",
"-b", "packages/"+name, url, name) "-b", "packages/"+name, url, name)
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0") cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
@ -83,7 +82,7 @@ func gitDownloadABS(url string, path string, name string) (bool, error) {
} }
return true, nil return true, nil
} else if err != nil { } else if errExist != nil {
return false, fmt.Errorf("error reading %s", filepath.Join(path, name, ".git")) return false, fmt.Errorf("error reading %s", filepath.Join(path, name, ".git"))
} }
@ -97,13 +96,13 @@ func gitDownloadABS(url string, path string, name string) (bool, error) {
return true, nil return true, nil
} }
func gitDownload(url string, path string, name string) (bool, error) { func gitDownload(url, path, name string) (bool, error) {
_, err := os.Stat(filepath.Join(path, name, ".git")) _, err := os.Stat(filepath.Join(path, name, ".git"))
if os.IsNotExist(err) { if os.IsNotExist(err) {
cmd := passToGit(path, "clone", "--no-progress", url, name) cmd := passToGit(path, "clone", "--no-progress", url, name)
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0") cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
_, stderr, err := capture(cmd) _, stderr, errCapture := capture(cmd)
if err != nil { if errCapture != nil {
return false, fmt.Errorf("error cloning %s: %s", name, stderr) return false, fmt.Errorf("error cloning %s: %s", name, stderr)
} }
@ -122,7 +121,7 @@ func gitDownload(url string, path string, name string) (bool, error) {
return false, nil return false, nil
} }
func gitMerge(path string, name string) error { func gitMerge(path, name string) error {
_, stderr, err := capture(passToGit(filepath.Join(path, name), "reset", "--hard", "HEAD")) _, stderr, err := capture(passToGit(filepath.Join(path, name), "reset", "--hard", "HEAD"))
if err != nil { if err != nil {
return fmt.Errorf("error resetting %s: %s", name, stderr) return fmt.Errorf("error resetting %s: %s", name, stderr)
@ -223,7 +222,7 @@ func getPkgbuildsfromABS(pkgs []string, path string) (bool, error) {
pkgDB, name := splitDBFromName(pkgN) pkgDB, name := splitDBFromName(pkgN)
if pkgDB != "" { if pkgDB != "" {
if db, err := alpmHandle.SyncDBByName(pkgDB); err == nil { if db, errSync := alpmHandle.SyncDBByName(pkgDB); errSync == nil {
pkg = db.Pkg(name) pkg = db.Pkg(name)
} }
} else { } else {

14
exec.go
View File

@ -3,12 +3,13 @@ package main
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"golang.org/x/crypto/ssh/terminal"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
"golang.org/x/crypto/ssh/terminal"
) )
func show(cmd *exec.Cmd) error { func show(cmd *exec.Cmd) error {
@ -20,14 +21,14 @@ func show(cmd *exec.Cmd) error {
return nil return nil
} }
func capture(cmd *exec.Cmd) (string, string, error) { func capture(cmd *exec.Cmd) (stdout, stderr string, err error) {
var outbuf, errbuf bytes.Buffer var outbuf, errbuf bytes.Buffer
cmd.Stdout = &outbuf cmd.Stdout = &outbuf
cmd.Stderr = &errbuf cmd.Stderr = &errbuf
err := cmd.Run() err = cmd.Run()
stdout := strings.TrimSpace(outbuf.String()) stdout = strings.TrimSpace(outbuf.String())
stderr := strings.TrimSpace(errbuf.String()) stderr = strings.TrimSpace(errbuf.String())
return stdout, stderr, err return stdout, stderr, err
} }
@ -93,8 +94,7 @@ func passToPacman(args *arguments) *exec.Cmd {
argArr = append(argArr, "--noconfirm") argArr = append(argArr, "--noconfirm")
} }
argArr = append(argArr, "--config", config.PacmanConf) argArr = append(argArr, "--config", config.PacmanConf, "--")
argArr = append(argArr, "--")
argArr = append(argArr, args.targets...) argArr = append(argArr, args.targets...)
if args.needRoot() { if args.needRoot() {

5
go.mod
View File

@ -1,11 +1,12 @@
module github.com/Jguer/yay/v9 module github.com/Jguer/yay/v9
require ( require (
github.com/Jguer/go-alpm v0.0.0-20191122171459-5cffc6e8fc69 github.com/Jguer/go-alpm v0.0.0-20200405152916-a3feea4322e9
github.com/Morganamilo/go-pacmanconf v0.0.0-20180910220353-9c5265e1b14f github.com/Morganamilo/go-pacmanconf v0.0.0-20180910220353-9c5265e1b14f
github.com/Morganamilo/go-srcinfo v1.0.0 github.com/Morganamilo/go-srcinfo v1.0.0
github.com/mikkeloscar/aur v0.0.0-20200113170522-1cb4e2949656 github.com/mikkeloscar/aur v0.0.0-20200113170522-1cb4e2949656
golang.org/x/crypto v0.0.0-20200317142112-1b76d66859c6 golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79
golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3 // indirect
) )
go 1.13 go 1.13

10
go.sum
View File

@ -1,5 +1,5 @@
github.com/Jguer/go-alpm v0.0.0-20191122171459-5cffc6e8fc69 h1:eNGutt8eUr37crjH7Wpvg5rTNk71hoBEXUpyJA0oheU= github.com/Jguer/go-alpm v0.0.0-20200405152916-a3feea4322e9 h1:lLQSUe6iRdtFrP0zkDV7n8I8XKSxRHQTEU1KRh4IOLg=
github.com/Jguer/go-alpm v0.0.0-20191122171459-5cffc6e8fc69/go.mod h1:D5SUcIS9Yiz/L8cjRzq/992eERnx6ugYmGlc4e7xdus= github.com/Jguer/go-alpm v0.0.0-20200405152916-a3feea4322e9/go.mod h1:D5SUcIS9Yiz/L8cjRzq/992eERnx6ugYmGlc4e7xdus=
github.com/Morganamilo/go-pacmanconf v0.0.0-20180910220353-9c5265e1b14f h1:ptFKynTV1p8JCzqk81NcMj0DV0Xle+PdKxfHjPbdIOU= github.com/Morganamilo/go-pacmanconf v0.0.0-20180910220353-9c5265e1b14f h1:ptFKynTV1p8JCzqk81NcMj0DV0Xle+PdKxfHjPbdIOU=
github.com/Morganamilo/go-pacmanconf v0.0.0-20180910220353-9c5265e1b14f/go.mod h1:Hk55m330jNiwxRodIlMCvw5iEyoRUCIY64W1p9D+tHc= github.com/Morganamilo/go-pacmanconf v0.0.0-20180910220353-9c5265e1b14f/go.mod h1:Hk55m330jNiwxRodIlMCvw5iEyoRUCIY64W1p9D+tHc=
github.com/Morganamilo/go-srcinfo v1.0.0 h1:Wh4nEF+HJWo+29hnxM18Q2hi+DUf0GejS13+Wg+dzmI= github.com/Morganamilo/go-srcinfo v1.0.0 h1:Wh4nEF+HJWo+29hnxM18Q2hi+DUf0GejS13+Wg+dzmI=
@ -7,10 +7,12 @@ github.com/Morganamilo/go-srcinfo v1.0.0/go.mod h1:MP6VGY1NNpVUmYIEgoM9acix95KQq
github.com/mikkeloscar/aur v0.0.0-20200113170522-1cb4e2949656 h1:j679+jxcDkCFblYk+I+G71HQTFxM3PacYbVCiYmhRhU= github.com/mikkeloscar/aur v0.0.0-20200113170522-1cb4e2949656 h1:j679+jxcDkCFblYk+I+G71HQTFxM3PacYbVCiYmhRhU=
github.com/mikkeloscar/aur v0.0.0-20200113170522-1cb4e2949656/go.mod h1:nYOKcK8tIj69ZZ8uDOWoiT+L25NvlOQaraDqTec/idA= github.com/mikkeloscar/aur v0.0.0-20200113170522-1cb4e2949656/go.mod h1:nYOKcK8tIj69ZZ8uDOWoiT+L25NvlOQaraDqTec/idA=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200317142112-1b76d66859c6 h1:TjszyFsQsyZNHwdVdZ5m7bjmreu0znc2kRYsEml9/Ww= golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79 h1:IaQbIIB2X/Mp/DKctl6ROxz1KyMlKp4uyvL6+kQ7C88=
golang.org/x/crypto v0.0.0-20200317142112-1b76d66859c6/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI= golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3 h1:5B6i6EAiSYyejWfvc5Rc9BbI3rzIsrrXfAQBWnYfn+w=
golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=

View File

@ -10,11 +10,12 @@ import (
"sync" "sync"
alpm "github.com/Jguer/go-alpm" alpm "github.com/Jguer/go-alpm"
gosrc "github.com/Morganamilo/go-srcinfo"
"github.com/Jguer/yay/v9/pkg/completion" "github.com/Jguer/yay/v9/pkg/completion"
"github.com/Jguer/yay/v9/pkg/intrange" "github.com/Jguer/yay/v9/pkg/intrange"
"github.com/Jguer/yay/v9/pkg/multierror" "github.com/Jguer/yay/v9/pkg/multierror"
"github.com/Jguer/yay/v9/pkg/stringset" "github.com/Jguer/yay/v9/pkg/stringset"
gosrc "github.com/Morganamilo/go-srcinfo"
) )
func asdeps(parser *arguments, pkgs []string) error { func asdeps(parser *arguments, pkgs []string) error {
@ -66,7 +67,7 @@ func install(parser *arguments) (err error) {
if parser.existsArg("y", "refresh") { if parser.existsArg("y", "refresh") {
err = earlyRefresh(parser) err = earlyRefresh(parser)
if err != nil { if err != nil {
return fmt.Errorf("Error refreshing databases") return fmt.Errorf("error refreshing databases")
} }
} }
} else if parser.existsArg("y", "refresh") || parser.existsArg("u", "sysupgrade") || len(parser.targets) > 0 { } else if parser.existsArg("y", "refresh") || parser.existsArg("u", "sysupgrade") || len(parser.targets) > 0 {
@ -114,9 +115,9 @@ func install(parser *arguments) (err error) {
warnings.print() warnings.print()
ignore, aurUp, err := upgradePkgs(aurUp, repoUp) ignore, aurUp, errUp := upgradePkgs(aurUp, repoUp)
if err != nil { if errUp != nil {
return err return errUp
} }
for _, up := range repoUp { for _, up := range repoUp {
@ -223,9 +224,9 @@ func install(parser *arguments) (err error) {
if config.CleanMenu { if config.CleanMenu {
if anyExistInCache(do.Aur) { if anyExistInCache(do.Aur) {
askClean := pkgbuildNumberMenu(do.Aur, remoteNamesCache) askClean := pkgbuildNumberMenu(do.Aur, remoteNamesCache)
toClean, err := cleanNumberMenu(do.Aur, remoteNamesCache, askClean) toClean, errClean := cleanNumberMenu(do.Aur, remoteNamesCache, askClean)
if err != nil { if errClean != nil {
return err return errClean
} }
cleanBuilds(toClean) cleanBuilds(toClean)
@ -261,9 +262,9 @@ func install(parser *arguments) (err error) {
config.NoConfirm = false config.NoConfirm = false
fmt.Println() fmt.Println()
if !continueTask(bold(green("Proceed with install?")), true) { if !continueTask(bold(green("Proceed with install?")), true) {
return fmt.Errorf("Aborting due to user") return fmt.Errorf("aborting due to user")
} }
err = updatePkgbuildSeenRef(toDiff, cloned) err = updatePkgbuildSeenRef(toDiff)
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, err.Error()) fmt.Fprintln(os.Stderr, err.Error())
} }
@ -301,7 +302,7 @@ func install(parser *arguments) (err error) {
config.NoConfirm = false config.NoConfirm = false
fmt.Println() fmt.Println()
if !continueTask(bold(green("Proceed with install?")), true) { if !continueTask(bold(green("Proceed with install?")), true) {
return fmt.Errorf("Aborting due to user") return fmt.Errorf("aborting due to user")
} }
config.NoConfirm = oldValue config.NoConfirm = oldValue
} }
@ -323,9 +324,8 @@ func install(parser *arguments) (err error) {
} }
if len(arguments.targets) > 0 || arguments.existsArg("u") { if len(arguments.targets) > 0 || arguments.existsArg("u") {
err := show(passToPacman(arguments)) if errShow := show(passToPacman(arguments)); errShow != nil {
if err != nil { return fmt.Errorf("error installing repo packages")
return fmt.Errorf("Error installing repo packages")
} }
deps := make([]string, 0) deps := make([]string, 0)
@ -344,11 +344,11 @@ func install(parser *arguments) (err error) {
} }
} }
if err = asdeps(parser, deps); err != nil { if errDeps := asdeps(parser, deps); errDeps != nil {
return err return errDeps
} }
if err = asexp(parser, exp); err != nil { if errExp := asexp(parser, exp); errExp != nil {
return err return errExp
} }
} }
@ -434,7 +434,7 @@ func earlyPacmanCall(parser *arguments) error {
if parser.existsArg("y", "refresh") || parser.existsArg("u", "sysupgrade") || len(arguments.targets) > 0 { if parser.existsArg("y", "refresh") || parser.existsArg("u", "sysupgrade") || len(arguments.targets) > 0 {
err = show(passToPacman(arguments)) err = show(passToPacman(arguments))
if err != nil { if err != nil {
return fmt.Errorf("Error installing repo packages") return fmt.Errorf("error installing repo packages")
} }
} }
@ -482,23 +482,22 @@ nextpkg:
fmt.Println() fmt.Println()
if !continueTask("Try to build them anyway?", true) { if !continueTask("Try to build them anyway?", true) {
return nil, fmt.Errorf("Aborting due to user") return nil, fmt.Errorf("aborting due to user")
} }
} }
return incompatible, nil return incompatible, nil
} }
func parsePackageList(dir string) (map[string]string, string, error) { func parsePackageList(dir string) (pkgdests map[string]string, pkgVersion string, err error) {
stdout, stderr, err := capture(passToMakepkg(dir, "--packagelist")) stdout, stderr, err := capture(passToMakepkg(dir, "--packagelist"))
if err != nil { if err != nil {
return nil, "", fmt.Errorf("%s%s", stderr, err) return nil, "", fmt.Errorf("%s%s", stderr, err)
} }
var version string
lines := strings.Split(stdout, "\n") lines := strings.Split(stdout, "\n")
pkgdests := make(map[string]string) pkgdests = make(map[string]string)
for _, line := range lines { for _, line := range lines {
if line == "" { if line == "" {
@ -509,18 +508,18 @@ func parsePackageList(dir string) (map[string]string, string, error) {
split := strings.Split(fileName, "-") split := strings.Split(fileName, "-")
if len(split) < 4 { if len(split) < 4 {
return nil, "", fmt.Errorf("Can not find package name : %s", split) return nil, "", fmt.Errorf("cannot find package name : %s", split)
} }
// pkgname-pkgver-pkgrel-arch.pkgext // pkgname-pkgver-pkgrel-arch.pkgext
// This assumes 3 dashes after the pkgname, Will cause an error // This assumes 3 dashes after the pkgname, Will cause an error
// if the PKGEXT contains a dash. Please no one do that. // if the PKGEXT contains a dash. Please no one do that.
pkgname := strings.Join(split[:len(split)-3], "-") pkgName := strings.Join(split[:len(split)-3], "-")
version = strings.Join(split[len(split)-3:len(split)-1], "-") pkgVersion = strings.Join(split[len(split)-3:len(split)-1], "-")
pkgdests[pkgname] = line pkgdests[pkgName] = line
} }
return pkgdests, version, nil return pkgdests, pkgVersion, nil
} }
func anyExistInCache(bases []Base) bool { func anyExistInCache(bases []Base) bool {
@ -588,7 +587,7 @@ func cleanNumberMenu(bases []Base, installed stringset.StringSet, hasClean bool)
cIsInclude := len(cExclude) == 0 && len(cOtherExclude) == 0 cIsInclude := len(cExclude) == 0 && len(cOtherExclude) == 0
if cOtherInclude.Get("abort") || cOtherInclude.Get("ab") { if cOtherInclude.Get("abort") || cOtherInclude.Get("ab") {
return nil, fmt.Errorf("Aborting due to user") return nil, fmt.Errorf("aborting due to user")
} }
if !cOtherInclude.Get("n") && !cOtherInclude.Get("none") { if !cOtherInclude.Get("n") && !cOtherInclude.Get("none") {
@ -673,7 +672,7 @@ func editDiffNumberMenu(bases []Base, installed stringset.StringSet, diff bool)
eIsInclude := len(eExclude) == 0 && len(eOtherExclude) == 0 eIsInclude := len(eExclude) == 0 && len(eOtherExclude) == 0
if eOtherInclude.Get("abort") || eOtherInclude.Get("ab") { if eOtherInclude.Get("abort") || eOtherInclude.Get("ab") {
return nil, fmt.Errorf("Aborting due to user") return nil, fmt.Errorf("aborting due to user")
} }
if !eOtherInclude.Get("n") && !eOtherInclude.Get("none") { if !eOtherInclude.Get("n") && !eOtherInclude.Get("none") {
@ -716,7 +715,7 @@ func editDiffNumberMenu(bases []Base, installed stringset.StringSet, diff bool)
return toEdit, nil return toEdit, nil
} }
func updatePkgbuildSeenRef(bases []Base, cloned stringset.StringSet) error { func updatePkgbuildSeenRef(bases []Base) error {
var errMulti multierror.MultiError var errMulti multierror.MultiError
for _, base := range bases { for _, base := range bases {
pkg := base.Pkgbase() pkg := base.Pkgbase()
@ -754,7 +753,9 @@ func showPkgbuildDiffs(bases []Base, cloned stringset.StringSet) error {
} }
} }
args := []string{"diff", start + "..HEAD@{upstream}", "--src-prefix", dir + "/", "--dst-prefix", dir + "/", "--", ".", ":(exclude).SRCINFO"} args := []string{"diff",
start + "..HEAD@{upstream}", "--src-prefix",
dir + "/", "--dst-prefix", dir + "/", "--", ".", ":(exclude).SRCINFO"}
if useColor { if useColor {
args = append(args, "--color=always") args = append(args, "--color=always")
} else { } else {
@ -787,7 +788,7 @@ func editPkgbuilds(bases []Base, srcinfos map[string]*gosrc.Srcinfo) error {
editcmd.Stdin, editcmd.Stdout, editcmd.Stderr = os.Stdin, os.Stdout, os.Stderr editcmd.Stdin, editcmd.Stdout, editcmd.Stderr = os.Stdin, os.Stdout, os.Stderr
err := editcmd.Run() err := editcmd.Run()
if err != nil { if err != nil {
return fmt.Errorf("Editor did not exit successfully, Aborting: %s", err) return fmt.Errorf("editor did not exit successfully, Aborting: %s", err)
} }
} }
@ -862,7 +863,7 @@ func downloadPkgbuilds(bases []Base, toSkip stringset.StringSet, buildDir string
var mux sync.Mutex var mux sync.Mutex
var errs multierror.MultiError var errs multierror.MultiError
download := func(k int, base Base) { download := func(base Base) {
defer wg.Done() defer wg.Done()
pkg := base.Pkgbase() pkg := base.Pkgbase()
@ -894,9 +895,9 @@ func downloadPkgbuilds(bases []Base, toSkip stringset.StringSet, buildDir string
} }
count := 0 count := 0
for k, base := range bases { for _, base := range bases {
wg.Add(1) wg.Add(1)
go download(k, base) go download(base)
count++ count++
if count%25 == 0 { if count%25 == 0 {
wg.Wait() wg.Wait()
@ -920,14 +921,20 @@ func downloadPkgbuildsSources(bases []Base, incompatible stringset.StringSet) (e
err = show(passToMakepkg(dir, args...)) err = show(passToMakepkg(dir, args...))
if err != nil { if err != nil {
return fmt.Errorf("Error downloading sources: %s", cyan(base.String())) return fmt.Errorf("error downloading sources: %s", cyan(base.String()))
} }
} }
return return
} }
func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc.Srcinfo, parser *arguments, incompatible stringset.StringSet, conflicts stringset.MapStringSet) error { func buildInstallPkgbuilds(
dp *depPool,
do *depOrder,
srcinfos map[string]*gosrc.Srcinfo,
parser *arguments,
incompatible stringset.StringSet,
conflicts stringset.MapStringSet) error {
arguments := parser.copy() arguments := parser.copy()
arguments.clearTargets() arguments.clearTargets()
arguments.op = "U" arguments.op = "U"
@ -961,9 +968,8 @@ func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc
return nil return nil
} }
err := show(passToPacman(arguments)) if errShow := show(passToPacman(arguments)); errShow != nil {
if err != nil { return errShow
return err
} }
err = saveVCSInfo() err = saveVCSInfo()
@ -971,11 +977,11 @@ func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)
} }
if err = asdeps(parser, deps); err != nil { if errDeps := asdeps(parser, deps); err != nil {
return err return errDeps
} }
if err = asexp(parser, exp); err != nil { if errExps := asexp(parser, exp); err != nil {
return err return errExps
} }
config.NoConfirm = oldConfirm config.NoConfirm = oldConfirm
@ -988,7 +994,6 @@ func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc
} }
for _, base := range do.Aur { for _, base := range do.Aur {
var err error
pkg := base.Pkgbase() pkg := base.Pkgbase()
dir := filepath.Join(config.BuildDir, pkg) dir := filepath.Join(config.BuildDir, pkg)
built := true built := true
@ -998,7 +1003,7 @@ func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc
for _, pkg := range base { for _, pkg := range base {
for _, deps := range [3][]string{pkg.Depends, pkg.MakeDepends, pkg.CheckDepends} { for _, deps := range [3][]string{pkg.Depends, pkg.MakeDepends, pkg.CheckDepends} {
for _, dep := range deps { for _, dep := range deps {
if _, err := dp.LocalDB.PkgCache().FindSatisfier(dep); err != nil { if _, errSatisfier := dp.LocalDB.PkgCache().FindSatisfier(dep); errSatisfier != nil {
satisfied = false satisfied = false
fmt.Printf("%s not satisfied, flushing install queue\n", dep) fmt.Printf("%s not satisfied, flushing install queue\n", dep)
break all break all
@ -1023,14 +1028,13 @@ func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc
} }
// pkgver bump // pkgver bump
err = show(passToMakepkg(dir, args...)) if err = show(passToMakepkg(dir, args...)); err != nil {
if err != nil { return fmt.Errorf("error making: %s", base.String())
return fmt.Errorf("Error making: %s", base.String())
} }
pkgdests, version, err := parsePackageList(dir) pkgdests, pkgVersion, errList := parsePackageList(dir)
if err != nil { if errList != nil {
return err return errList
} }
isExplicit := false isExplicit := false
@ -1041,14 +1045,13 @@ func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc
for _, split := range base { for _, split := range base {
pkgdest, ok := pkgdests[split.Name] pkgdest, ok := pkgdests[split.Name]
if !ok { if !ok {
return fmt.Errorf("Could not find PKGDEST for: %s", split.Name) return fmt.Errorf("could not find PKGDEST for: %s", split.Name)
} }
_, err := os.Stat(pkgdest) if _, errStat := os.Stat(pkgdest); os.IsNotExist(errStat) {
if os.IsNotExist(err) {
built = false built = false
} else if err != nil { } else if errStat != nil {
return err return errStat
} }
} }
} else { } else {
@ -1058,7 +1061,7 @@ func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc
if cmdArgs.existsArg("needed") { if cmdArgs.existsArg("needed") {
installed := true installed := true
for _, split := range base { for _, split := range base {
if alpmpkg := dp.LocalDB.Pkg(split.Name); alpmpkg == nil || alpmpkg.Version() != version { if alpmpkg := dp.LocalDB.Pkg(split.Name); alpmpkg == nil || alpmpkg.Version() != pkgVersion {
installed = false installed = false
} }
} }
@ -1066,10 +1069,10 @@ func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc
if installed { if installed {
err = show(passToMakepkg(dir, "-c", "--nobuild", "--noextract", "--ignorearch")) err = show(passToMakepkg(dir, "-c", "--nobuild", "--noextract", "--ignorearch"))
if err != nil { if err != nil {
return fmt.Errorf("Error making: %s", err) return fmt.Errorf("error making: %s", err)
} }
fmt.Println(cyan(pkg+"-"+version) + bold(" is up to date -- skipping")) fmt.Println(cyan(pkg+"-"+pkgVersion) + bold(" is up to date -- skipping"))
continue continue
} }
} }
@ -1077,11 +1080,11 @@ func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc
if built { if built {
err = show(passToMakepkg(dir, "-c", "--nobuild", "--noextract", "--ignorearch")) err = show(passToMakepkg(dir, "-c", "--nobuild", "--noextract", "--ignorearch"))
if err != nil { if err != nil {
return fmt.Errorf("Error making: %s", err) return fmt.Errorf("error making: %s", err)
} }
fmt.Println(bold(yellow(arrow)), fmt.Println(bold(yellow(arrow)),
cyan(pkg+"-"+version)+bold(" already made -- skipping build")) cyan(pkg+"-"+pkgVersion)+bold(" already made -- skipping build"))
} else { } else {
args := []string{"-cf", "--noconfirm", "--noextract", "--noprepare", "--holdver"} args := []string{"-cf", "--noconfirm", "--noextract", "--noprepare", "--holdver"}
@ -1089,9 +1092,8 @@ func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc
args = append(args, "--ignorearch") args = append(args, "--ignorearch")
} }
err := show(passToMakepkg(dir, args...)) if errMake := show(passToMakepkg(dir, args...)); errMake != nil {
if err != nil { return fmt.Errorf("error making: %s", base.String())
return fmt.Errorf("Error making: %s", base.String())
} }
} }
@ -1116,15 +1118,15 @@ func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc
return nil return nil
} }
return fmt.Errorf("Could not find PKGDEST for: %s", name) return fmt.Errorf("could not find PKGDEST for: %s", name)
} }
if _, err := os.Stat(pkgdest); os.IsNotExist(err) { if _, errStat := os.Stat(pkgdest); os.IsNotExist(errStat) {
if optional { if optional {
return nil return nil
} }
return fmt.Errorf("PKGDEST for %s listed by makepkg, but does not exist: %s", name, pkgdest) return fmt.Errorf("the PKGDEST for %s listed by makepkg, but does not exist: %s", name, pkgdest)
} }
arguments.addTarget(pkgdest) arguments.addTarget(pkgdest)
@ -1140,16 +1142,12 @@ func buildInstallPkgbuilds(dp *depPool, do *depOrder, srcinfos map[string]*gosrc
} }
for _, split := range base { for _, split := range base {
var err error if errAdd := doAddTarget(split.Name, false); errAdd != nil {
return errAdd
err = doAddTarget(split.Name, false)
if err != nil {
return err
} }
err = doAddTarget(split.Name+"-debug", true) if errAddDebug := doAddTarget(split.Name+"-debug", true); errAddDebug != nil {
if err != nil { return errAddDebug
return err
} }
} }

View File

@ -26,7 +26,7 @@ func (set pgpKeySet) set(key string, p Base) {
// Using ToUpper to make sure keys with a different case will be // Using ToUpper to make sure keys with a different case will be
// considered the same. // considered the same.
upperKey := strings.ToUpper(key) upperKey := strings.ToUpper(key)
set[key] = append(set[upperKey], p) set[upperKey] = append(set[upperKey], p)
} }
func (set pgpKeySet) get(key string) bool { func (set pgpKeySet) get(key string) bool {

View File

@ -178,14 +178,18 @@ func TestCheckPgpKeys(t *testing.T) {
// B6C8F98282B944E3B0D5C2530FC3042E345AD05D: Hans Wennborg. // B6C8F98282B944E3B0D5C2530FC3042E345AD05D: Hans Wennborg.
{ {
pkgs: Base{newPkg("libc++")}, pkgs: Base{newPkg("libc++")},
srcinfos: map[string]*gosrc.Srcinfo{"libc++": makeSrcinfo("libc++", "11E521D646982372EB577A1F8F0871F202119294", "B6C8F98282B944E3B0D5C2530FC3042E345AD05D")}, srcinfos: map[string]*gosrc.Srcinfo{
"libc++": makeSrcinfo("libc++", "11E521D646982372EB577A1F8F0871F202119294", "B6C8F98282B944E3B0D5C2530FC3042E345AD05D")},
wantError: false, wantError: false,
}, },
// Two dummy packages requiring the same key. // Two dummy packages requiring the same key.
// ABAF11C65A2970B130ABE3C479BE3E4300411886: Linus Torvalds. // ABAF11C65A2970B130ABE3C479BE3E4300411886: Linus Torvalds.
{ {
pkgs: Base{newPkg("dummy-1"), newPkg("dummy-2")}, pkgs: Base{newPkg("dummy-1"), newPkg("dummy-2")},
srcinfos: map[string]*gosrc.Srcinfo{"dummy-1": makeSrcinfo("dummy-1", "ABAF11C65A2970B130ABE3C479BE3E4300411886"), "dummy-2": makeSrcinfo("dummy-2", "ABAF11C65A2970B130ABE3C479BE3E4300411886")}, srcinfos: map[string]*gosrc.Srcinfo{
"dummy-1": makeSrcinfo("dummy-1",
"ABAF11C65A2970B130ABE3C479BE3E4300411886"),
"dummy-2": makeSrcinfo("dummy-2", "ABAF11C65A2970B130ABE3C479BE3E4300411886")},
wantError: false, wantError: false,
}, },
// dummy package: single package, two valid keys, one of them already // dummy package: single package, two valid keys, one of them already
@ -194,13 +198,16 @@ func TestCheckPgpKeys(t *testing.T) {
// C52048C0C0748FEE227D47A2702353E0F7E48EDB: Thomas Dickey. // C52048C0C0748FEE227D47A2702353E0F7E48EDB: Thomas Dickey.
{ {
pkgs: Base{newPkg("dummy-3")}, pkgs: Base{newPkg("dummy-3")},
srcinfos: map[string]*gosrc.Srcinfo{"dummy-3": makeSrcinfo("dummy-3", "11E521D646982372EB577A1F8F0871F202119294", "C52048C0C0748FEE227D47A2702353E0F7E48EDB")}, srcinfos: map[string]*gosrc.Srcinfo{
"dummy-3": makeSrcinfo("dummy-3", "11E521D646982372EB577A1F8F0871F202119294", "C52048C0C0748FEE227D47A2702353E0F7E48EDB")},
wantError: false, wantError: false,
}, },
// Two dummy packages with existing keys. // Two dummy packages with existing keys.
{ {
pkgs: Base{newPkg("dummy-4"), newPkg("dummy-5")}, pkgs: Base{newPkg("dummy-4"), newPkg("dummy-5")},
srcinfos: map[string]*gosrc.Srcinfo{"dummy-4": makeSrcinfo("dummy-4", "11E521D646982372EB577A1F8F0871F202119294"), "dummy-5": makeSrcinfo("dummy-5", "C52048C0C0748FEE227D47A2702353E0F7E48EDB")}, srcinfos: map[string]*gosrc.Srcinfo{
"dummy-4": makeSrcinfo("dummy-4", "11E521D646982372EB577A1F8F0871F202119294"),
"dummy-5": makeSrcinfo("dummy-5", "C52048C0C0748FEE227D47A2702353E0F7E48EDB")},
wantError: false, wantError: false,
}, },
// Dummy package with invalid key, should fail. // Dummy package with invalid key, should fail.

25
main.go
View File

@ -37,14 +37,14 @@ func setPaths() error {
func initConfig() error { func initConfig() error {
cfile, err := os.Open(configFile) cfile, err := os.Open(configFile)
if !os.IsNotExist(err) && err != nil { if !os.IsNotExist(err) && err != nil {
return fmt.Errorf("Failed to open config file '%s': %s", configFile, err) return fmt.Errorf("failed to open config file '%s': %s", configFile, err)
} }
defer cfile.Close() defer cfile.Close()
if !os.IsNotExist(err) { if !os.IsNotExist(err) {
decoder := json.NewDecoder(cfile) decoder := json.NewDecoder(cfile)
if err = decoder.Decode(&config); err != nil { if err = decoder.Decode(&config); err != nil {
return fmt.Errorf("Failed to read config '%s': %s", configFile, err) return fmt.Errorf("failed to read config '%s': %s", configFile, err)
} }
} }
@ -59,14 +59,14 @@ func initConfig() error {
func initVCS() error { func initVCS() error {
vfile, err := os.Open(vcsFile) vfile, err := os.Open(vcsFile)
if !os.IsNotExist(err) && err != nil { if !os.IsNotExist(err) && err != nil {
return fmt.Errorf("Failed to open vcs file '%s': %s", vcsFile, err) return fmt.Errorf("failed to open vcs file '%s': %s", vcsFile, err)
} }
defer vfile.Close() defer vfile.Close()
if !os.IsNotExist(err) { if !os.IsNotExist(err) {
decoder := json.NewDecoder(vfile) decoder := json.NewDecoder(vfile)
if err = decoder.Decode(&savedInfo); err != nil { if err = decoder.Decode(&savedInfo); err != nil {
return fmt.Errorf("Failed to read vcs '%s': %s", vcsFile, err) return fmt.Errorf("failed to read vcs '%s': %s", vcsFile, err)
} }
} }
@ -76,7 +76,7 @@ func initVCS() error {
func initHomeDirs() error { func initHomeDirs() error {
if _, err := os.Stat(configHome); os.IsNotExist(err) { if _, err := os.Stat(configHome); os.IsNotExist(err) {
if err = os.MkdirAll(configHome, 0755); err != nil { if err = os.MkdirAll(configHome, 0755); err != nil {
return fmt.Errorf("Failed to create config directory '%s': %s", configHome, err) return fmt.Errorf("failed to create config directory '%s': %s", configHome, err)
} }
} else if err != nil { } else if err != nil {
return err return err
@ -84,7 +84,7 @@ func initHomeDirs() error {
if _, err := os.Stat(cacheHome); os.IsNotExist(err) { if _, err := os.Stat(cacheHome); os.IsNotExist(err) {
if err = os.MkdirAll(cacheHome, 0755); err != nil { if err = os.MkdirAll(cacheHome, 0755); err != nil {
return fmt.Errorf("Failed to create cache directory '%s': %s", cacheHome, err) return fmt.Errorf("failed to create cache directory '%s': %s", cacheHome, err)
} }
} else if err != nil { } else if err != nil {
return err return err
@ -96,7 +96,7 @@ func initHomeDirs() error {
func initBuildDir() error { func initBuildDir() error {
if _, err := os.Stat(config.BuildDir); os.IsNotExist(err) { if _, err := os.Stat(config.BuildDir); os.IsNotExist(err) {
if err = os.MkdirAll(config.BuildDir, 0755); err != nil { if err = os.MkdirAll(config.BuildDir, 0755); err != nil {
return fmt.Errorf("Failed to create BuildDir directory '%s': %s", config.BuildDir, err) return fmt.Errorf("failed to create BuildDir directory '%s': %s", config.BuildDir, err)
} }
} else if err != nil { } else if err != nil {
return err return err
@ -166,19 +166,18 @@ func initAlpm() error {
} }
func initAlpmHandle() error { func initAlpmHandle() error {
var err error
if alpmHandle != nil { if alpmHandle != nil {
if err := alpmHandle.Release(); err != nil { if errRelease := alpmHandle.Release(); errRelease != nil {
return err return errRelease
} }
} }
var err error
if alpmHandle, err = alpm.Initialize(pacmanConf.RootDir, pacmanConf.DBPath); err != nil { if alpmHandle, err = alpm.Initialize(pacmanConf.RootDir, pacmanConf.DBPath); err != nil {
return fmt.Errorf("Unable to CreateHandle: %s", err) return fmt.Errorf("unable to CreateHandle: %s", err)
} }
if err := configureAlpm(pacmanConf); err != nil { if err := configureAlpm(); err != nil {
return err return err
} }

View File

@ -9,8 +9,9 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/Jguer/yay/v9/pkg/stringset"
rpc "github.com/mikkeloscar/aur" rpc "github.com/mikkeloscar/aur"
"github.com/Jguer/yay/v9/pkg/stringset"
) )
// Parses command line arguments in a way we can interact with programmatically but // Parses command line arguments in a way we can interact with programmatically but
@ -139,7 +140,7 @@ func (parser *arguments) addOP(op string) (err error) {
return return
} }
func (parser *arguments) addParam(option string, arg string) (err error) { func (parser *arguments) addParam(option, arg string) (err error) {
if !isArg(option) { if !isArg(option) {
return fmt.Errorf("invalid option '%s'", option) return fmt.Errorf("invalid option '%s'", option)
} }
@ -188,7 +189,7 @@ func (parser *arguments) existsArg(options ...string) bool {
return false return false
} }
func (parser *arguments) getArg(options ...string) (arg string, double bool, exists bool) { func (parser *arguments) getArg(options ...string) (arg string, double, exists bool) {
existCount := 0 existCount := 0
for _, option := range options { for _, option := range options {
@ -204,7 +205,6 @@ func (parser *arguments) getArg(options ...string) (arg string, double bool, exi
if exists { if exists {
existCount++ existCount++
} }
} }
value, exists = parser.globals[option] value, exists = parser.globals[option]
@ -217,14 +217,13 @@ func (parser *arguments) getArg(options ...string) (arg string, double bool, exi
if exists { if exists {
existCount++ existCount++
} }
} }
} }
double = existCount >= 2 double = existCount >= 2
exists = existCount >= 1 exists = existCount >= 1
return return arg, double, exists
} }
func (parser *arguments) addTarget(targets ...string) { func (parser *arguments) addTarget(targets ...string) {
@ -291,7 +290,6 @@ func (parser *arguments) formatGlobals() (args []string) {
} }
return return
} }
func formatArg(arg string) string { func formatArg(arg string) string {
@ -707,7 +705,7 @@ func hasParam(arg string) bool {
// Parses short hand options such as: // Parses short hand options such as:
// -Syu -b/some/path - // -Syu -b/some/path -
func (parser *arguments) parseShortOption(arg string, param string) (usedNext bool, err error) { func (parser *arguments) parseShortOption(arg, param string) (usedNext bool, err error) {
if arg == "-" { if arg == "-" {
err = parser.addArg("-") err = parser.addArg("-")
return return
@ -741,7 +739,7 @@ func (parser *arguments) parseShortOption(arg string, param string) (usedNext bo
// Parses full length options such as: // Parses full length options such as:
// --sync --refresh --sysupgrade --dbpath /some/path -- // --sync --refresh --sysupgrade --dbpath /some/path --
func (parser *arguments) parseLongOption(arg string, param string) (usedNext bool, err error) { func (parser *arguments) parseLongOption(arg, param string) (usedNext bool, err error) {
if arg == "--" { if arg == "--" {
err = parser.addArg(arg) err = parser.addArg(arg)
return return
@ -773,16 +771,14 @@ func (parser *arguments) parseStdin() error {
return os.Stdin.Close() return os.Stdin.Close()
} }
func (parser *arguments) parseCommandLine() (err error) { func (parser *arguments) parseCommandLine() error {
args := os.Args[1:] args := os.Args[1:]
usedNext := false usedNext := false
if len(args) < 1 { if len(args) < 1 {
_, err = parser.parseShortOption("-Syu", "") if _, err := parser.parseShortOption("-Syu", ""); err != nil {
if err != nil { return err
return
} }
} else { } else {
for k, arg := range args { for k, arg := range args {
var nextArg string var nextArg string
@ -796,6 +792,7 @@ func (parser *arguments) parseCommandLine() (err error) {
nextArg = args[k+1] nextArg = args[k+1]
} }
var err error
switch { switch {
case parser.existsArg("--"): case parser.existsArg("--"):
parser.addTarget(arg) parser.addTarget(arg)
@ -808,7 +805,7 @@ func (parser *arguments) parseCommandLine() (err error) {
} }
if err != nil { if err != nil {
return return err
} }
} }
} }
@ -818,25 +815,21 @@ func (parser *arguments) parseCommandLine() (err error) {
} }
if parser.existsArg("-") { if parser.existsArg("-") {
var file *os.File if err := parser.parseStdin(); err != nil {
err = parser.parseStdin() return err
}
parser.delArg("-") parser.delArg("-")
file, err := os.Open("/dev/tty")
if err != nil { if err != nil {
return return err
}
file, err = os.Open("/dev/tty")
if err != nil {
return
} }
os.Stdin = file os.Stdin = file
} }
cmdArgs.extractYayOptions() cmdArgs.extractYayOptions()
return return nil
} }
func (parser *arguments) extractYayOptions() { func (parser *arguments) extractYayOptions() {

View File

@ -12,7 +12,7 @@ import (
) )
// Show provides completion info for shells // Show provides completion info for shells
func Show(alpmHandle *alpm.Handle, aurURL string, cacheDir string, interval int, force bool) error { func Show(alpmHandle *alpm.Handle, aurURL, cacheDir string, interval int, force bool) error {
path := filepath.Join(cacheDir, "completion.cache") path := filepath.Join(cacheDir, "completion.cache")
err := Update(alpmHandle, aurURL, cacheDir, interval, force) err := Update(alpmHandle, aurURL, cacheDir, interval, force)
@ -31,7 +31,7 @@ func Show(alpmHandle *alpm.Handle, aurURL string, cacheDir string, interval int,
} }
// Update updates completion cache to be used by Complete // Update updates completion cache to be used by Complete
func Update(alpmHandle *alpm.Handle, aurURL string, cacheDir string, interval int, force bool) error { func Update(alpmHandle *alpm.Handle, aurURL, cacheDir string, interval int, force bool) error {
path := filepath.Join(cacheDir, "completion.cache") path := filepath.Join(cacheDir, "completion.cache")
info, err := os.Stat(path) info, err := os.Stat(path)

View File

@ -4,8 +4,8 @@ import (
"strconv" "strconv"
"strings" "strings"
"unicode" "unicode"
"github.com/Jguer/yay/v9/pkg/stringset"
"github.com/Jguer/yay/v9/pkg/stringset"
) )
// IntRange stores a max and min amount for range // IntRange stores a max and min amount for range
@ -68,11 +68,12 @@ func Max(a, b int) int {
// intended to allow words inside of number menus. e.g. 'all' 'none' 'abort' // intended to allow words inside of number menus. e.g. 'all' 'none' 'abort'
// of course the implementation is up to the caller, this function mearley parses // of course the implementation is up to the caller, this function mearley parses
// the input and organizes it // the input and organizes it
func ParseNumberMenu(input string) (IntRanges, IntRanges, stringset.StringSet, stringset.StringSet) { func ParseNumberMenu(input string) (include, exclude IntRanges,
include := make(IntRanges, 0) otherInclude, otherExclude stringset.StringSet) {
exclude := make(IntRanges, 0) include = make(IntRanges, 0)
otherInclude := make(stringset.StringSet) exclude = make(IntRanges, 0)
otherExclude := make(stringset.StringSet) otherInclude = make(stringset.StringSet)
otherExclude = make(stringset.StringSet)
words := strings.FieldsFunc(input, func(c rune) bool { words := strings.FieldsFunc(input, func(c rune) bool {
return unicode.IsSpace(c) || c == ',' return unicode.IsSpace(c) || c == ','

View File

@ -1,8 +1,9 @@
package intrange package intrange
import ( import (
"github.com/Jguer/yay/v9/pkg/stringset"
"testing" "testing"
"github.com/Jguer/yay/v9/pkg/stringset"
) )
func TestParseNumberMenu(t *testing.T) { func TestParseNumberMenu(t *testing.T) {
@ -29,15 +30,39 @@ func TestParseNumberMenu(t *testing.T) {
} }
expected := []result{ expected := []result{
{IntRanges{makeIntRange(1, 1), makeIntRange(2, 2), makeIntRange(3, 3), makeIntRange(4, 4), makeIntRange(5, 5)}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)}, {IntRanges{makeIntRange(1, 1),
{IntRanges{makeIntRange(1, 10), makeIntRange(5, 15)}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)}, makeIntRange(2, 2),
{IntRanges{makeIntRange(5, 10), makeIntRange(85, 90)}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)}, makeIntRange(3, 3),
{IntRanges{makeIntRange(1, 1), makeIntRange(99, 99), makeIntRange(60, 62)}, IntRanges{makeIntRange(2, 2), makeIntRange(5, 10), makeIntRange(38, 40), makeIntRange(123, 123)}, make(stringset.StringSet), make(stringset.StringSet)}, makeIntRange(4, 4),
makeIntRange(5, 5)}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)},
{IntRanges{makeIntRange(1, 10),
makeIntRange(5, 15)}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)},
{IntRanges{makeIntRange(5, 10),
makeIntRange(85, 90)}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)},
{IntRanges{makeIntRange(1, 1),
makeIntRange(99, 99),
makeIntRange(60, 62)},
IntRanges{makeIntRange(2, 2),
makeIntRange(5, 10),
makeIntRange(38, 40),
makeIntRange(123, 123)},
make(stringset.StringSet), make(stringset.StringSet)},
{IntRanges{}, IntRanges{}, stringset.Make("abort", "all", "none"), make(stringset.StringSet)}, {IntRanges{}, IntRanges{}, stringset.Make("abort", "all", "none"), make(stringset.StringSet)},
{IntRanges{}, IntRanges{}, stringset.Make("a-b"), stringset.Make("abort", "a-b")}, {IntRanges{}, IntRanges{}, stringset.Make("a-b"), stringset.Make("abort", "a-b")},
{IntRanges{}, IntRanges{}, stringset.Make("-9223372036854775809-9223372036854775809"), make(stringset.StringSet)}, {IntRanges{}, IntRanges{}, stringset.Make("-9223372036854775809-9223372036854775809"), make(stringset.StringSet)},
{IntRanges{makeIntRange(1, 1), makeIntRange(2, 2), makeIntRange(3, 3), makeIntRange(4, 4), makeIntRange(5, 5)}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)}, {IntRanges{makeIntRange(1, 1),
{IntRanges{makeIntRange(1, 1), makeIntRange(2, 2), makeIntRange(3, 3), makeIntRange(4, 4), makeIntRange(5, 5), makeIntRange(6, 6), makeIntRange(7, 7), makeIntRange(8, 8)}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)}, makeIntRange(2, 2),
makeIntRange(3, 3),
makeIntRange(4, 4),
makeIntRange(5, 5)}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)},
{IntRanges{makeIntRange(1, 1),
makeIntRange(2, 2),
makeIntRange(3, 3),
makeIntRange(4, 4),
makeIntRange(5, 5),
makeIntRange(6, 6),
makeIntRange(7, 7),
makeIntRange(8, 8)}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)},
{IntRanges{}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)}, {IntRanges{}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)},
{IntRanges{}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)}, {IntRanges{}, IntRanges{}, make(stringset.StringSet), make(stringset.StringSet)},
{IntRanges{}, IntRanges{}, stringset.Make("a", "b", "c", "d", "e"), make(stringset.StringSet)}, {IntRanges{}, IntRanges{}, stringset.Make("a", "b", "c", "d", "e"), make(stringset.StringSet)},

View File

@ -14,7 +14,7 @@ type MapStringSet map[string]StringSet
// Add adds a new value to the Map. // Add adds a new value to the Map.
// If n is already in the map, then v is appended to the StringSet under that key. // If n is already in the map, then v is appended to the StringSet under that key.
// Otherwise a new StringSet is creayed containing v // Otherwise a new StringSet is creayed containing v
func (mss MapStringSet) Add(n string, v string) { func (mss MapStringSet) Add(n, v string) {
_, ok := mss[n] _, ok := mss[n]
if !ok { if !ok {
mss[n] = make(StringSet) mss[n] = make(StringSet)

View File

@ -12,10 +12,10 @@ import (
"strings" "strings"
"time" "time"
"github.com/Jguer/yay/v9/pkg/intrange"
"github.com/Jguer/yay/v9/pkg/stringset"
rpc "github.com/mikkeloscar/aur" rpc "github.com/mikkeloscar/aur"
"github.com/Jguer/yay/v9/pkg/intrange"
"github.com/Jguer/yay/v9/pkg/stringset"
) )
const arrow = "==>" const arrow = "==>"
@ -45,7 +45,6 @@ func (warnings *aurWarnings) print() {
} }
fmt.Println() fmt.Println()
} }
} }
// human method returns results in human readable format. // human method returns results in human readable format.
@ -65,7 +64,7 @@ func human(size int64) string {
func (q aurQuery) printSearch(start int) { func (q aurQuery) printSearch(start int) {
localDB, _ := alpmHandle.LocalDB() localDB, _ := alpmHandle.LocalDB()
for i, res := range q { for i := range q {
var toprint string var toprint string
if config.SearchMode == numberMenu { if config.SearchMode == numberMenu {
switch config.SortMode { switch config.SortMode {
@ -77,31 +76,31 @@ func (q aurQuery) printSearch(start int) {
fmt.Println("Invalid Sort Mode. Fix with yay -Y --bottomup --save") fmt.Println("Invalid Sort Mode. Fix with yay -Y --bottomup --save")
} }
} else if config.SearchMode == minimal { } else if config.SearchMode == minimal {
fmt.Println(res.Name) fmt.Println(q[i].Name)
continue continue
} }
toprint += bold(colourHash("aur")) + "/" + bold(res.Name) + toprint += bold(colorHash("aur")) + "/" + bold(q[i].Name) +
" " + cyan(res.Version) + " " + cyan(q[i].Version) +
bold(" (+"+strconv.Itoa(res.NumVotes)) + bold(" (+"+strconv.Itoa(q[i].NumVotes)) +
" " + bold(strconv.FormatFloat(res.Popularity, 'f', 2, 64)+"%) ") " " + bold(strconv.FormatFloat(q[i].Popularity, 'f', 2, 64)+"%) ")
if res.Maintainer == "" { if q[i].Maintainer == "" {
toprint += bold(red("(Orphaned)")) + " " toprint += bold(red("(Orphaned)")) + " "
} }
if res.OutOfDate != 0 { if q[i].OutOfDate != 0 {
toprint += bold(red("(Out-of-date "+formatTime(res.OutOfDate)+")")) + " " toprint += bold(red("(Out-of-date "+formatTime(q[i].OutOfDate)+")")) + " "
} }
if pkg := localDB.Pkg(res.Name); pkg != nil { if pkg := localDB.Pkg(q[i].Name); pkg != nil {
if pkg.Version() != res.Version { if pkg.Version() != q[i].Version {
toprint += bold(green("(Installed: " + pkg.Version() + ")")) toprint += bold(green("(Installed: " + pkg.Version() + ")"))
} else { } else {
toprint += bold(green("(Installed)")) toprint += bold(green("(Installed)"))
} }
} }
toprint += "\n " + res.Description toprint += "\n " + q[i].Description
fmt.Println(toprint) fmt.Println(toprint)
} }
} }
@ -124,7 +123,7 @@ func (s repoQuery) printSearch() {
continue continue
} }
toprint += bold(colourHash(res.DB().Name())) + "/" + bold(res.Name()) + toprint += bold(colorHash(res.DB().Name())) + "/" + bold(res.Name()) +
" " + cyan(res.Version()) + " " + cyan(res.Version()) +
bold(" ("+human(res.Size())+ bold(" ("+human(res.Size())+
" "+human(res.ISize())+") ") " "+human(res.ISize())+") ")
@ -152,12 +151,12 @@ func (s repoQuery) printSearch() {
// Pretty print a set of packages from the same package base. // Pretty print a set of packages from the same package base.
// Packages foo and bar from a pkgbase named base would print like so: // Packages foo and bar from a pkgbase named base would print like so:
// base (foo bar) // base (foo bar)
func (base Base) String() string { func (b Base) String() string {
pkg := base[0] pkg := b[0]
str := pkg.PackageBase str := pkg.PackageBase
if len(base) > 1 || pkg.PackageBase != pkg.Name { if len(b) > 1 || pkg.PackageBase != pkg.Name {
str2 := " (" str2 := " ("
for _, split := range base { for _, split := range b {
str2 += split.Name + " " str2 += split.Name + " "
} }
str2 = str2[:len(str2)-1] + ")" str2 = str2[:len(str2)-1] + ")"
@ -169,7 +168,7 @@ func (base Base) String() string {
} }
func (u upgrade) StylizedNameWithRepository() string { func (u upgrade) StylizedNameWithRepository() string {
return bold(colourHash(u.Repository)) + "/" + bold(u.Name) return bold(colorHash(u.Repository)) + "/" + bold(u.Name)
} }
// Print prints the details of the packages to upgrade. // Print prints the details of the packages to upgrade.
@ -177,8 +176,8 @@ func (u upSlice) print() {
longestName, longestVersion := 0, 0 longestName, longestVersion := 0, 0
for _, pack := range u { for _, pack := range u {
packNameLen := len(pack.StylizedNameWithRepository()) packNameLen := len(pack.StylizedNameWithRepository())
version, _ := getVersionDiff(pack.LocalVersion, pack.RemoteVersion) packVersion, _ := getVersionDiff(pack.LocalVersion, pack.RemoteVersion)
packVersionLen := len(version) packVersionLen := len(packVersion)
longestName = intrange.Max(packNameLen, longestName) longestName = intrange.Max(packNameLen, longestName)
longestVersion = intrange.Max(packVersionLen, longestVersion) longestVersion = intrange.Max(packVersionLen, longestVersion)
} }
@ -358,7 +357,7 @@ func localStatistics() error {
return err return err
} }
fmt.Printf(bold("Yay version v%s\n"), version) fmt.Printf(bold("Yay version v%s\n"), yayVersion)
fmt.Println(bold(cyan("==========================================="))) fmt.Println(bold(cyan("===========================================")))
fmt.Println(bold(green("Total installed packages: ")) + cyan(strconv.Itoa(info.Totaln))) 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("Total foreign installed packages: ")) + cyan(strconv.Itoa(len(remoteNames))))
@ -376,7 +375,6 @@ func localStatistics() error {
//TODO: Make it less hacky //TODO: Make it less hacky
func printNumberOfUpdates() error { func printNumberOfUpdates() error {
//todo
warnings := makeWarnings() warnings := makeWarnings()
old := os.Stdout // keep backup of the real stdout old := os.Stdout // keep backup of the real stdout
os.Stdout = nil os.Stdout = nil
@ -470,7 +468,7 @@ type item struct {
Creator string `xml:"dc:creator"` Creator string `xml:"dc:creator"`
} }
func (item item) print(buildTime time.Time) { func (item *item) print(buildTime time.Time) {
var fd string var fd string
date, err := time.Parse(time.RFC1123Z, item.PubDate) date, err := time.Parse(time.RFC1123Z, item.PubDate)
@ -486,7 +484,6 @@ func (item item) print(buildTime time.Time) {
} }
fmt.Println(bold(magenta(fd)), bold(strings.TrimSpace(item.Title))) fmt.Println(bold(magenta(fd)), bold(strings.TrimSpace(item.Title)))
//fmt.Println(strings.TrimSpace(item.Link))
if !cmdArgs.existsArg("q", "quiet") { if !cmdArgs.existsArg("q", "quiet") {
desc := strings.TrimSpace(parseNews(item.Description)) desc := strings.TrimSpace(parseNews(item.Description))
@ -519,10 +516,10 @@ func printNewsFeed() error {
return err return err
} }
rss := rss{} rssGot := rss{}
d := xml.NewDecoder(bytes.NewReader(body)) d := xml.NewDecoder(bytes.NewReader(body))
err = d.Decode(&rss) err = d.Decode(&rssGot)
if err != nil { if err != nil {
return err return err
} }
@ -533,12 +530,12 @@ func printNewsFeed() error {
} }
if config.SortMode == bottomUp { if config.SortMode == bottomUp {
for i := len(rss.Channel.Items) - 1; i >= 0; i-- { for i := len(rssGot.Channel.Items) - 1; i >= 0; i-- {
rss.Channel.Items[i].print(buildTime) rssGot.Channel.Items[i].print(buildTime)
} }
} else { } else {
for i := 0; i < len(rss.Channel.Items); i++ { for i := 0; i < len(rssGot.Channel.Items); i++ {
rss.Channel.Items[i].print(buildTime) rssGot.Channel.Items[i].print(buildTime)
} }
} }
@ -605,9 +602,9 @@ func bold(in string) string {
return stylize(boldCode, in) return stylize(boldCode, in)
} }
// Colours text using a hashing algorithm. The same text will always produce the // Colors text using a hashing algorithm. The same text will always produce the
// same colour while different text will produce a different colour. // same color while different text will produce a different color.
func colourHash(name string) (output string) { func colorHash(name string) (output string) {
if !useColor { if !useColor {
return name return name
} }

View File

@ -9,11 +9,11 @@ import (
"time" "time"
alpm "github.com/Jguer/go-alpm" alpm "github.com/Jguer/go-alpm"
rpc "github.com/mikkeloscar/aur"
"github.com/Jguer/yay/v9/pkg/intrange" "github.com/Jguer/yay/v9/pkg/intrange"
"github.com/Jguer/yay/v9/pkg/multierror" "github.com/Jguer/yay/v9/pkg/multierror"
"github.com/Jguer/yay/v9/pkg/stringset" "github.com/Jguer/yay/v9/pkg/stringset"
rpc "github.com/mikkeloscar/aur"
) )
type aurWarnings struct { type aurWarnings struct {
@ -71,8 +71,10 @@ func (q aurQuery) Swap(i, j int) {
} }
// FilterPackages filters packages based on source and type from local repository. // FilterPackages filters packages based on source and type from local repository.
func filterPackages() (local []alpm.Package, remote []alpm.Package, func filterPackages() (
localNames []string, remoteNames []string, err error) { local, remote []alpm.Package,
localNames, remoteNames []string,
err error) {
localDB, err := alpmHandle.LocalDB() localDB, err := alpmHandle.LocalDB()
if err != nil { if err != nil {
return return
@ -106,7 +108,7 @@ func filterPackages() (local []alpm.Package, remote []alpm.Package,
} }
err = localDB.PkgCache().ForEach(f) err = localDB.PkgCache().ForEach(f)
return return local, remote, localNames, remoteNames, err
} }
func getSearchBy(value string) rpc.By { func getSearchBy(value string) rpc.By {
@ -162,14 +164,14 @@ func narrowSearch(pkgS []string, sortS bool) (aurQuery, error) {
var aq aurQuery var aq aurQuery
var n int var n int
for _, res := range r { for i := range r {
match := true match := true
for i, pkgN := range pkgS { for i, pkgN := range pkgS {
if usedIndex == i { if usedIndex == i {
continue continue
} }
if !(strings.Contains(res.Name, pkgN) || strings.Contains(strings.ToLower(res.Description), pkgN)) { if !(strings.Contains(r[i].Name, pkgN) || strings.Contains(strings.ToLower(r[i].Description), pkgN)) {
match = false match = false
break break
} }
@ -177,7 +179,7 @@ func narrowSearch(pkgS []string, sortS bool) (aurQuery, error) {
if match { if match {
n++ n++
aq = append(aq, res) aq = append(aq, r[i])
} }
} }
@ -222,7 +224,7 @@ func syncSearch(pkgS []string) (err error) {
pq.printSearch() pq.printSearch()
} }
default: default:
return fmt.Errorf("Invalid Sort Mode. Fix with yay -Y --bottomup --save") return fmt.Errorf("invalid Sort Mode. Fix with yay -Y --bottomup --save")
} }
if aurErr != nil { if aurErr != nil {
@ -234,13 +236,13 @@ func syncSearch(pkgS []string) (err error) {
} }
// SyncInfo serves as a pacman -Si for repo packages and AUR packages. // SyncInfo serves as a pacman -Si for repo packages and AUR packages.
func syncInfo(pkgS []string) (err error) { func syncInfo(pkgS []string) error {
var info []*rpc.Pkg var info []*rpc.Pkg
missing := false missing := false
pkgS = removeInvalidTargets(pkgS) pkgS = removeInvalidTargets(pkgS)
aurS, repoS, err := packageSlices(pkgS) aurS, repoS, err := packageSlices(pkgS)
if err != nil { if err != nil {
return return err
} }
if len(aurS) != 0 { if len(aurS) != 0 {
@ -266,7 +268,7 @@ func syncInfo(pkgS []string) (err error) {
err = show(passToPacman(arguments)) err = show(passToPacman(arguments))
if err != nil { if err != nil {
return return err
} }
} }
@ -284,7 +286,7 @@ func syncInfo(pkgS []string) (err error) {
err = fmt.Errorf("") err = fmt.Errorf("")
} }
return return err
} }
// Search handles repo searches. Creates a RepoSearch struct. // Search handles repo searches. Creates a RepoSearch struct.
@ -315,10 +317,10 @@ func queryRepo(pkgInputN []string) (s repoQuery, err error) {
} }
// PackageSlices separates an input slice into aur and repo slices // PackageSlices separates an input slice into aur and repo slices
func packageSlices(toCheck []string) (aur []string, repo []string, err error) { func packageSlices(toCheck []string) (aur, repo []string, err error) {
dbList, err := alpmHandle.SyncDBs() dbList, err := alpmHandle.SyncDBs()
if err != nil { if err != nil {
return return nil, nil, err
} }
for _, _pkg := range toCheck { for _, _pkg := range toCheck {
@ -337,7 +339,6 @@ func packageSlices(toCheck []string) (aur []string, repo []string, err error) {
if db.Pkg(name) != nil { if db.Pkg(name) != nil {
found = true found = true
return fmt.Errorf("") return fmt.Errorf("")
} }
return nil return nil
}) })
@ -353,7 +354,7 @@ func packageSlices(toCheck []string) (aur []string, repo []string, err error) {
} }
} }
return return aur, repo, nil
} }
// HangingPackages returns a list of packages installed as deps // HangingPackages returns a list of packages installed as deps
@ -443,7 +444,7 @@ func hangingPackages(removeOptional bool) (hanging []string, err error) {
return nil return nil
}) })
return return hanging, err
} }
func lastBuildTime() (time.Time, error) { func lastBuildTime() (time.Time, error) {
@ -465,18 +466,18 @@ func lastBuildTime() (time.Time, error) {
} }
// Statistics returns statistics about packages installed in system // Statistics returns statistics about packages installed in system
func statistics() (info struct { func statistics() (*struct {
Totaln int Totaln int
Expln int Expln int
TotalSize int64 TotalSize int64
}, err error) { }, error) {
var tS int64 // TotalSize var tS int64 // TotalSize
var nPkg int var nPkg int
var ePkg int var ePkg int
localDB, err := alpmHandle.LocalDB() localDB, err := alpmHandle.LocalDB()
if err != nil { if err != nil {
return return nil, err
} }
for _, pkg := range localDB.PkgCache().Slice() { for _, pkg := range localDB.PkgCache().Slice() {
@ -487,7 +488,7 @@ func statistics() (info struct {
} }
} }
info = struct { info := &struct {
Totaln int Totaln int
Expln int Expln int
TotalSize int64 TotalSize int64
@ -495,7 +496,7 @@ func statistics() (info struct {
nPkg, ePkg, tS, nPkg, ePkg, tS,
} }
return return info, err
} }
// Queries the aur for information about specified packages. // Queries the aur for information about specified packages.
@ -518,9 +519,8 @@ func aurInfo(names []string, warnings *aurWarnings) ([]*rpc.Pkg, error) {
return return
} }
mux.Lock() mux.Lock()
for _, _i := range tempInfo { for i := range tempInfo {
i := _i info = append(info, &tempInfo[i])
info = append(info, &i)
} }
mux.Unlock() mux.Unlock()
} }

View File

@ -7,11 +7,13 @@ import (
"unicode" "unicode"
alpm "github.com/Jguer/go-alpm" alpm "github.com/Jguer/go-alpm"
"github.com/Jguer/yay/v9/pkg/intrange" "github.com/Jguer/yay/v9/pkg/intrange"
rpc "github.com/mikkeloscar/aur"
"github.com/Jguer/yay/v9/pkg/multierror" "github.com/Jguer/yay/v9/pkg/multierror"
"github.com/Jguer/yay/v9/pkg/stringset" "github.com/Jguer/yay/v9/pkg/stringset"
rpc "github.com/mikkeloscar/aur"
) )
// upgrade type describes a system upgrade. // upgrade type describes a system upgrade.
@ -63,7 +65,6 @@ func (u upSlice) Less(i, j int) bool {
iRunes := []rune(u[i].Repository) iRunes := []rune(u[i].Repository)
jRunes := []rune(u[j].Repository) jRunes := []rune(u[j].Repository)
return LessRunes(iRunes, jRunes) return LessRunes(iRunes, jRunes)
} }
func getVersionDiff(oldVersion, newVersion string) (left, right string) { func getVersionDiff(oldVersion, newVersion string) (left, right string) {
@ -109,21 +110,18 @@ func getVersionDiff(oldVersion, newVersion string) (left, right string) {
left = samePart + red(oldVersion[diffPosition:]) left = samePart + red(oldVersion[diffPosition:])
right = samePart + green(newVersion[diffPosition:]) right = samePart + green(newVersion[diffPosition:])
return return left, right
} }
// upList returns lists of packages to upgrade from each source. // upList returns lists of packages to upgrade from each source.
func upList(warnings *aurWarnings) (upSlice, upSlice, error) { func upList(warnings *aurWarnings) (aurUp, repoUp upSlice, err error) {
local, remote, _, remoteNames, err := filterPackages() _, remote, _, remoteNames, err := filterPackages()
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
var wg sync.WaitGroup var wg sync.WaitGroup
var develUp upSlice var develUp upSlice
var repoUp upSlice
var aurUp upSlice
var errs multierror.MultiError var errs multierror.MultiError
aurdata := make(map[string]*rpc.Pkg) aurdata := make(map[string]*rpc.Pkg)
@ -138,7 +136,7 @@ func upList(warnings *aurWarnings) (upSlice, upSlice, error) {
fmt.Println(bold(cyan("::") + bold(" Searching databases for updates..."))) fmt.Println(bold(cyan("::") + bold(" Searching databases for updates...")))
wg.Add(1) wg.Add(1)
go func() { go func() {
repoUp, err = upRepo(local) repoUp, err = upRepo()
errs.Add(err) errs.Add(err)
wg.Done() wg.Done()
}() }()
@ -157,8 +155,7 @@ func upList(warnings *aurWarnings) (upSlice, upSlice, error) {
wg.Add(1) wg.Add(1)
go func() { go func() {
aurUp, err = upAUR(remote, aurdata) aurUp = upAUR(remote, aurdata)
errs.Add(err)
wg.Done() wg.Done()
}() }()
@ -194,7 +191,7 @@ func upList(warnings *aurWarnings) (upSlice, upSlice, error) {
return aurUp, repoUp, errs.Return() return aurUp, repoUp, errs.Return()
} }
func upDevel(remote []alpm.Package, aurdata map[string]*rpc.Pkg) (toUpgrade upSlice) { func upDevel(remote []alpm.Package, aurdata map[string]*rpc.Pkg) upSlice {
toUpdate := make([]alpm.Package, 0) toUpdate := make([]alpm.Package, 0)
toRemove := make([]string, 0) toRemove := make([]string, 0)
@ -230,6 +227,7 @@ func upDevel(remote []alpm.Package, aurdata map[string]*rpc.Pkg) (toUpgrade upSl
wg.Wait() wg.Wait()
toUpgrade := make(upSlice, 0, len(toUpdate))
for _, pkg := range toUpdate { for _, pkg := range toUpdate {
if pkg.ShouldIgnore() { if pkg.ShouldIgnore() {
printIgnoringPackage(pkg, "latest-commit") printIgnoringPackage(pkg, "latest-commit")
@ -239,12 +237,12 @@ func upDevel(remote []alpm.Package, aurdata map[string]*rpc.Pkg) (toUpgrade upSl
} }
removeVCSPackage(toRemove) removeVCSPackage(toRemove)
return return toUpgrade
} }
// upAUR gathers foreign packages and checks if they have new versions. // upAUR gathers foreign packages and checks if they have new versions.
// Output: Upgrade type package list. // Output: Upgrade type package list.
func upAUR(remote []alpm.Package, aurdata map[string]*rpc.Pkg) (upSlice, error) { func upAUR(remote []alpm.Package, aurdata map[string]*rpc.Pkg) upSlice {
toUpgrade := make(upSlice, 0) toUpgrade := make(upSlice, 0)
for _, pkg := range remote { for _, pkg := range remote {
@ -263,7 +261,7 @@ func upAUR(remote []alpm.Package, aurdata map[string]*rpc.Pkg) (upSlice, error)
} }
} }
return toUpgrade, nil return toUpgrade
} }
func printIgnoringPackage(pkg alpm.Package, newPkgVersion string) { func printIgnoringPackage(pkg alpm.Package, newPkgVersion string) {
@ -298,7 +296,7 @@ func printLocalNewerThanAUR(
// upRepo gathers local packages and checks if they have new versions. // upRepo gathers local packages and checks if they have new versions.
// Output: Upgrade type package list. // Output: Upgrade type package list.
func upRepo(local []alpm.Package) (upSlice, error) { func upRepo() (upSlice, error) {
slice := upSlice{} slice := upSlice{}
localDB, err := alpmHandle.LocalDB() localDB, err := alpmHandle.LocalDB()
@ -339,9 +337,9 @@ func upRepo(local []alpm.Package) (upSlice, error) {
} }
// upgradePkgs handles updating the cache and installing updates. // upgradePkgs handles updating the cache and installing updates.
func upgradePkgs(aurUp, repoUp upSlice) (stringset.StringSet, stringset.StringSet, error) { func upgradePkgs(aurUp, repoUp upSlice) (ignore, aurNames stringset.StringSet, err error) {
ignore := make(stringset.StringSet) ignore = make(stringset.StringSet)
aurNames := make(stringset.StringSet) aurNames = make(stringset.StringSet)
allUpLen := len(repoUp) + len(aurUp) allUpLen := len(repoUp) + len(aurUp)
if allUpLen == 0 { if allUpLen == 0 {
@ -372,7 +370,6 @@ func upgradePkgs(aurUp, repoUp upSlice) (stringset.StringSet, stringset.StringSe
// upgrade menu asks you which packages to NOT upgrade so in this case // upgrade menu asks you which packages to NOT upgrade so in this case
// include and exclude are kind of swapped // include and exclude are kind of swapped
//include, exclude, other := parseNumberMenu(string(numberBuf))
include, exclude, otherInclude, otherExclude := intrange.ParseNumberMenu(numbers) include, exclude, otherInclude, otherExclude := intrange.ParseNumberMenu(numbers)
isInclude := len(exclude) == 0 && len(otherExclude) == 0 isInclude := len(exclude) == 0 && len(otherExclude) == 0

View File

@ -56,7 +56,8 @@ func TestGetVersionDiff(t *testing.T) {
o, n := getVersionDiff(pair.Old, pair.New) o, n := getVersionDiff(pair.Old, pair.New)
if o != out[i].Old || n != out[i].New { if o != out[i].Old || n != out[i].New {
t.Errorf("Test %d failed for update: expected (%s => %s) got (%s => %s) %d %d %d %d", i+1, in[i].Old, in[i].New, o, n, len(in[i].Old), len(in[i].New), len(o), len(n)) t.Errorf("Test %d failed for update: expected (%s => %s) got (%s => %s) %d %d %d %d",
i+1, in[i].Old, in[i].New, o, n, len(in[i].Old), len(in[i].New), len(o), len(n))
} }
} }
} }

17
vcs.go
View File

@ -9,8 +9,9 @@ import (
"sync" "sync"
"time" "time"
"github.com/Jguer/yay/v9/pkg/stringset"
gosrc "github.com/Morganamilo/go-srcinfo" gosrc "github.com/Morganamilo/go-srcinfo"
"github.com/Jguer/yay/v9/pkg/stringset"
) )
// Info contains the last commit sha of a repo // Info contains the last commit sha of a repo
@ -49,10 +50,10 @@ func createDevelDB() error {
return err return err
} }
for _, pkgbuild := range srcinfos { for i := range srcinfos {
for _, pkg := range pkgbuild.Packages { for iP := range srcinfos[i].Packages {
wg.Add(1) wg.Add(1)
go updateVCSData(pkg.Pkgname, pkgbuild.Source, &mux, &wg) go updateVCSData(srcinfos[i].Packages[iP].Pkgname, srcinfos[i].Source, &mux, &wg)
} }
} }
@ -62,7 +63,7 @@ func createDevelDB() error {
} }
// parseSource returns the git url, default branch and protocols it supports // parseSource returns the git url, default branch and protocols it supports
func parseSource(source string) (url string, branch string, protocols []string) { func parseSource(source string) (url, branch string, protocols []string) {
split := strings.Split(source, "::") split := strings.Split(source, "::")
source = split[len(split)-1] source = split[len(split)-1]
split = strings.SplitN(source, "://", 2) split = strings.SplitN(source, "://", 2)
@ -107,10 +108,10 @@ func parseSource(source string) (url string, branch string, protocols []string)
url = strings.Split(url, "?")[0] url = strings.Split(url, "?")[0]
branch = strings.Split(branch, "?")[0] branch = strings.Split(branch, "?")[0]
return return url, branch, protocols
} }
func updateVCSData(pkgName string, sources []gosrc.ArchString, mux *sync.Mutex, wg *sync.WaitGroup) { func updateVCSData(pkgName string, sources []gosrc.ArchString, mux sync.Locker, wg *sync.WaitGroup) {
defer wg.Done() defer wg.Done()
if savedInfo == nil { if savedInfo == nil {
@ -154,7 +155,7 @@ func updateVCSData(pkgName string, sources []gosrc.ArchString, mux *sync.Mutex,
} }
} }
func getCommit(url string, branch string, protocols []string) string { func getCommit(url, branch string, protocols []string) string {
if len(protocols) > 0 { if len(protocols) > 0 {
protocol := protocols[len(protocols)-1] protocol := protocols[len(protocols)-1]
var outbuf bytes.Buffer var outbuf bytes.Buffer

View File

@ -60,7 +60,8 @@ func TestParsing(t *testing.T) {
branch != compare.Branch || branch != compare.Branch ||
!isEqual(protocols, compare.Protocols) { !isEqual(protocols, compare.Protocols) {
t.Fatalf("Test %d failed: Expected: url=%+v branch=%+v protocols=%+v\ngot url=%+v branch=%+v protocols=%+v", n+1, compare.URL, compare.Branch, compare.Protocols, url, branch, protocols) t.Fatalf("Test %d failed: Expected: url=%+v branch=%+v protocols=%+v\ngot url=%+v branch=%+v protocols=%+v",
n+1, compare.URL, compare.Branch, compare.Protocols, url, branch, protocols)
} }
} }