fix(init): refactor init to use runtime

This commit is contained in:
jguer 2020-07-05 03:17:35 +02:00
parent cd02fa459c
commit 2dc01d8a3e
No known key found for this signature in database
GPG key ID: 6D6CC9BEA8556B35
8 changed files with 137 additions and 125 deletions

6
cmd.go
View file

@ -144,7 +144,7 @@ func handleCmd() error {
return handleHelp()
}
if config.SudoLoop && cmdArgs.NeedRoot(&config.Runtime) {
if config.SudoLoop && cmdArgs.NeedRoot(config.Runtime) {
sudoLoopBackground()
}
@ -213,9 +213,9 @@ func handlePrint() (err error) {
quiet := cmdArgs.ExistsArg("q", "quiet")
err = news.PrintNewsFeed(alpmHandle, config.SortMode, double, quiet)
case cmdArgs.ExistsDouble("c", "complete"):
err = completion.Show(alpmHandle, config.AURURL, cacheHome, config.CompletionInterval, true)
err = completion.Show(alpmHandle, config.AURURL, config.Runtime.CompletionPath, config.CompletionInterval, true)
case cmdArgs.ExistsArg("c", "complete"):
err = completion.Show(alpmHandle, config.AURURL, cacheHome, config.CompletionInterval, false)
err = completion.Show(alpmHandle, config.AURURL, config.Runtime.CompletionPath, config.CompletionInterval, false)
case cmdArgs.ExistsArg("s", "stats"):
err = localStatistics()
default:

View file

@ -26,24 +26,9 @@ var yayVersion = "10.0.0"
var localePath = "/usr/share/locale"
// configFileName holds the name of the config file.
const configFileName string = "config.json"
// vcsFileName holds the name of the vcs file.
const vcsFileName string = "vcs.json"
// configHome handles config directory home
var configHome string
// cacheHome handles cache home
var cacheHome string
// savedInfo holds the current vcs info
var savedInfo vcsInfo
// configfile holds yay config file path.
var configFile string
// vcsfile holds yay vcs info file path.
var vcsFile string

View file

@ -85,7 +85,7 @@ func passToPacman(args *settings.Arguments) *exec.Cmd {
mSudoFlags := strings.Fields(config.SudoFlags)
if args.NeedRoot(&config.Runtime) {
if args.NeedRoot(config.Runtime) {
argArr = append(argArr, config.SudoBin)
argArr = append(argArr, mSudoFlags...)
}
@ -100,7 +100,7 @@ func passToPacman(args *settings.Arguments) *exec.Cmd {
argArr = append(argArr, "--config", config.PacmanConf, "--")
argArr = append(argArr, args.Targets...)
if args.NeedRoot(&config.Runtime) {
if args.NeedRoot(config.Runtime) {
waitLock()
}
return exec.Command(argArr[0], argArr[1:]...)

View file

@ -357,7 +357,7 @@ func install(parser *settings.Arguments) (err error) {
}
}
go exitOnError(completion.Update(alpmHandle, config.AURURL, cacheHome, config.CompletionInterval, false))
go exitOnError(completion.Update(alpmHandle, config.AURURL, config.Runtime.CompletionPath, config.CompletionInterval, false))
err = downloadPkgbuildsSources(do.Aur, incompatible)
if err != nil {

62
main.go
View file

@ -5,39 +5,16 @@ import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
alpm "github.com/Jguer/go-alpm"
pacmanconf "github.com/Morganamilo/go-pacmanconf"
"github.com/leonelquinteros/gotext"
"github.com/Jguer/yay/v10/pkg/settings"
"github.com/Jguer/yay/v10/pkg/text"
)
func setPaths() error {
if configHome = os.Getenv("XDG_CONFIG_HOME"); configHome != "" {
configHome = filepath.Join(configHome, "yay")
} else if configHome = os.Getenv("HOME"); configHome != "" {
configHome = filepath.Join(configHome, ".config/yay")
} else {
return errors.New(gotext.Get("%s and %s unset", "XDG_CONFIG_HOME", "HOME"))
}
if cacheHome = os.Getenv("XDG_CACHE_HOME"); cacheHome != "" {
cacheHome = filepath.Join(cacheHome, "yay")
} else if cacheHome = os.Getenv("HOME"); cacheHome != "" {
cacheHome = filepath.Join(cacheHome, ".cache/yay")
} else {
return errors.New(gotext.Get("%s and %s unset", "XDG_CACHE_HOME", "HOME"))
}
configFile = filepath.Join(configHome, configFileName)
vcsFile = filepath.Join(cacheHome, vcsFileName)
return nil
}
func initGotext() {
if envLocalePath := os.Getenv("LOCALE_PATH"); envLocalePath != "" {
localePath = envLocalePath
@ -46,17 +23,17 @@ func initGotext() {
gotext.Configure(localePath, os.Getenv("LANG"), "yay")
}
func initConfig() error {
cfile, err := os.Open(configFile)
func initConfig(configPath string) error {
cfile, err := os.Open(configPath)
if !os.IsNotExist(err) && err != nil {
return errors.New(gotext.Get("failed to open config file '%s': %s", configFile, err))
return errors.New(gotext.Get("failed to open config file '%s': %s", configPath, err))
}
defer cfile.Close()
if !os.IsNotExist(err) {
decoder := json.NewDecoder(cfile)
if err = decoder.Decode(&config); err != nil {
return errors.New(gotext.Get("failed to read config file '%s': %s", configFile, err))
return errors.New(gotext.Get("failed to read config file '%s': %s", configPath, err))
}
}
@ -85,26 +62,6 @@ func initVCS() error {
return nil
}
func initHomeDirs() error {
if _, err := os.Stat(configHome); os.IsNotExist(err) {
if err = os.MkdirAll(configHome, 0755); err != nil {
return errors.New(gotext.Get("failed to create config directory '%s': %s", configHome, err))
}
} else if err != nil {
return err
}
if _, err := os.Stat(cacheHome); os.IsNotExist(err) {
if err = os.MkdirAll(cacheHome, 0755); err != nil {
return errors.New(gotext.Get("failed to create cache directory '%s': %s", cacheHome, err))
}
} else if err != nil {
return err
}
return nil
}
func initBuildDir() error {
if _, err := os.Stat(config.BuildDir); os.IsNotExist(err) {
if err = os.MkdirAll(config.BuildDir, 0755); err != nil {
@ -225,13 +182,14 @@ func main() {
text.Warnln(gotext.Get("Avoid running yay as root/sudo."))
}
exitOnError(setPaths())
runtime, err := settings.MakeRuntime()
exitOnError(err)
config = defaultSettings()
exitOnError(initHomeDirs())
exitOnError(initConfig())
config.Runtime = runtime
exitOnError(initConfig(runtime.ConfigPath))
exitOnError(cmdArgs.ParseCommandLine(config))
if config.Runtime.SaveConfig {
err := config.SaveConfig(configFile)
err := config.SaveConfig(runtime.ConfigPath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}

View file

@ -14,10 +14,8 @@ import (
)
// Show provides completion info for shells
func Show(alpmHandle *alpm.Handle, aurURL, cacheDir string, interval int, force bool) error {
completionPath := filepath.Join(cacheDir, "completion.cache")
err := Update(alpmHandle, aurURL, cacheDir, interval, force)
func Show(alpmHandle *alpm.Handle, aurURL, completionPath string, interval int, force bool) error {
err := Update(alpmHandle, aurURL, completionPath, interval, force)
if err != nil {
return err
}
@ -33,8 +31,7 @@ func Show(alpmHandle *alpm.Handle, aurURL, cacheDir string, interval int, force
}
// Update updates completion cache to be used by Complete
func Update(alpmHandle *alpm.Handle, aurURL, cacheDir string, interval int, force bool) error {
completionPath := filepath.Join(cacheDir, "completion.cache")
func Update(alpmHandle *alpm.Handle, aurURL, completionPath string, interval int, force bool) error {
info, err := os.Stat(completionPath)
if os.IsNotExist(err) || (interval != -1 && time.Since(info.ModTime()).Hours() >= float64(interval*24)) || force {

View file

@ -15,50 +15,50 @@ const (
// Configuration stores yay's config.
type Configuration struct {
AURURL string `json:"aururl"`
BuildDir string `json:"buildDir"`
ABSDir string `json:"absdir"`
Editor string `json:"editor"`
EditorFlags string `json:"editorflags"`
MakepkgBin string `json:"makepkgbin"`
MakepkgConf string `json:"makepkgconf"`
PacmanBin string `json:"pacmanbin"`
PacmanConf string `json:"pacmanconf"`
ReDownload string `json:"redownload"`
ReBuild string `json:"rebuild"`
AnswerClean string `json:"answerclean"`
AnswerDiff string `json:"answerdiff"`
AnswerEdit string `json:"answeredit"`
AnswerUpgrade string `json:"answerupgrade"`
GitBin string `json:"gitbin"`
GpgBin string `json:"gpgbin"`
GpgFlags string `json:"gpgflags"`
MFlags string `json:"mflags"`
SortBy string `json:"sortby"`
SearchBy string `json:"searchby"`
GitFlags string `json:"gitflags"`
RemoveMake string `json:"removemake"`
SudoBin string `json:"sudobin"`
SudoFlags string `json:"sudoflags"`
RequestSplitN int `json:"requestsplitn"`
SearchMode int `json:"-"`
SortMode int `json:"sortmode"`
CompletionInterval int `json:"completionrefreshtime"`
SudoLoop bool `json:"sudoloop"`
TimeUpdate bool `json:"timeupdate"`
NoConfirm bool `json:"-"`
Devel bool `json:"devel"`
CleanAfter bool `json:"cleanAfter"`
Provides bool `json:"provides"`
PGPFetch bool `json:"pgpfetch"`
UpgradeMenu bool `json:"upgrademenu"`
CleanMenu bool `json:"cleanmenu"`
DiffMenu bool `json:"diffmenu"`
EditMenu bool `json:"editmenu"`
CombinedUpgrade bool `json:"combinedupgrade"`
UseAsk bool `json:"useask"`
BatchInstall bool `json:"batchinstall"`
Runtime Runtime `json:"-"`
AURURL string `json:"aururl"`
BuildDir string `json:"buildDir"`
ABSDir string `json:"absdir"`
Editor string `json:"editor"`
EditorFlags string `json:"editorflags"`
MakepkgBin string `json:"makepkgbin"`
MakepkgConf string `json:"makepkgconf"`
PacmanBin string `json:"pacmanbin"`
PacmanConf string `json:"pacmanconf"`
ReDownload string `json:"redownload"`
ReBuild string `json:"rebuild"`
AnswerClean string `json:"answerclean"`
AnswerDiff string `json:"answerdiff"`
AnswerEdit string `json:"answeredit"`
AnswerUpgrade string `json:"answerupgrade"`
GitBin string `json:"gitbin"`
GpgBin string `json:"gpgbin"`
GpgFlags string `json:"gpgflags"`
MFlags string `json:"mflags"`
SortBy string `json:"sortby"`
SearchBy string `json:"searchby"`
GitFlags string `json:"gitflags"`
RemoveMake string `json:"removemake"`
SudoBin string `json:"sudobin"`
SudoFlags string `json:"sudoflags"`
RequestSplitN int `json:"requestsplitn"`
SearchMode int `json:"-"`
SortMode int `json:"sortmode"`
CompletionInterval int `json:"completionrefreshtime"`
SudoLoop bool `json:"sudoloop"`
TimeUpdate bool `json:"timeupdate"`
NoConfirm bool `json:"-"`
Devel bool `json:"devel"`
CleanAfter bool `json:"cleanAfter"`
Provides bool `json:"provides"`
PGPFetch bool `json:"pgpfetch"`
UpgradeMenu bool `json:"upgrademenu"`
CleanMenu bool `json:"cleanmenu"`
DiffMenu bool `json:"diffmenu"`
EditMenu bool `json:"editmenu"`
CombinedUpgrade bool `json:"combinedupgrade"`
UseAsk bool `json:"useask"`
BatchInstall bool `json:"batchinstall"`
Runtime *Runtime `json:"-"`
}
// SaveConfig writes yay config to file.

View file

@ -1,7 +1,23 @@
package settings
import (
"os"
"path/filepath"
"github.com/leonelquinteros/gotext"
"github.com/pkg/errors"
)
type TargetMode int
// configFileName holds the name of the config file.
const configFileName string = "config.json"
// vcsFileName holds the name of the vcs file.
const vcsFileName string = "vcs.json"
const completionFileName string = "completion.cache"
const (
ModeAny TargetMode = iota
ModeAUR
@ -9,6 +25,62 @@ const (
)
type Runtime struct {
Mode TargetMode
SaveConfig bool
Mode TargetMode
SaveConfig bool
CompletionPath string
ConfigPath string
VCSPath string
}
func MakeRuntime() (*Runtime, error) {
cacheHome := ""
configHome := ""
runtime := &Runtime{
Mode: ModeAny,
SaveConfig: false,
CompletionPath: "",
}
if configHome = os.Getenv("XDG_CONFIG_HOME"); configHome != "" {
configHome = filepath.Join(configHome, "yay")
} else if configHome = os.Getenv("HOME"); configHome != "" {
configHome = filepath.Join(configHome, ".config/yay")
} else {
return nil, errors.New(gotext.Get("%s and %s unset", "XDG_CONFIG_HOME", "HOME"))
}
if err := initDir(configHome); err != nil {
return nil, err
}
if cacheHome = os.Getenv("XDG_CACHE_HOME"); cacheHome != "" {
cacheHome = filepath.Join(cacheHome, "yay")
} else if cacheHome = os.Getenv("HOME"); cacheHome != "" {
cacheHome = filepath.Join(cacheHome, ".cache/yay")
} else {
return nil, errors.New(gotext.Get("%s and %s unset", "XDG_CACHE_HOME", "HOME"))
}
if err := initDir(cacheHome); err != nil {
return runtime, err
}
runtime.ConfigPath = filepath.Join(configHome, configFileName)
runtime.VCSPath = filepath.Join(cacheHome, vcsFileName)
runtime.CompletionPath = filepath.Join(cacheHome, completionFileName)
return runtime, nil
}
func initDir(dir string) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err = os.MkdirAll(dir, 0755); err != nil {
return errors.New(gotext.Get("failed to create config directory '%s': %s", dir, err))
}
} else if err != nil {
return err
}
return nil
}