gpm/modules/config/config.go

133 lines
2.6 KiB
Go

package config
import (
"encoding/json"
"fmt"
"github.com/AlecAivazis/survey/v2"
"github.com/BurntSushi/toml"
"github.com/mitchellh/go-homedir"
"go.jolheiser.com/beaver"
"os"
"path"
"strings"
)
var (
configPath string
cfg *Config
Version = "develop"
// Config items
GPMURL string
Packages []Package
)
type Config struct {
GPMURL string `toml:"gpm-url" json:"gpm_url"`
Packages []Package `toml:"package" json:"packages"`
}
type Package struct {
Name string `toml:"name" json:"name"`
Import string `toml:"import" json:"import"`
}
// Load on init so that CLI contexts are correctly populated
func init() {
home, err := homedir.Dir()
if err != nil {
beaver.Fatalf("could not locate home directory: %v", err)
}
configPath = fmt.Sprintf("%s/.gpm/config.toml", home)
if _, err := os.Stat(configPath); os.IsNotExist(err) {
if err := os.MkdirAll(path.Dir(configPath), os.ModePerm); err != nil {
beaver.Fatalf("could not create gpm home: %v", err)
}
if _, err := os.Create(configPath); err != nil {
beaver.Fatalf("could not create gpm config: %v", err)
}
}
if _, err := toml.DecodeFile(configPath, &cfg); err != nil {
beaver.Fatalf("could not decode gpm config: %v", err)
}
dupe := make(map[string]bool)
for _, pkg := range cfg.Packages {
name := strings.ToLower(pkg.Name)
if ok := dupe[name]; ok {
beaver.Fatalf("duplicate package for %s", pkg.Name)
}
dupe[name] = true
}
GPMURL = cfg.GPMURL
Packages = cfg.Packages
}
func Save() error {
cfg.GPMURL = GPMURL
cfg.Packages = Packages
fi, err := os.Create(configPath)
if err != nil {
return err
}
defer fi.Close()
if err := toml.NewEncoder(fi).Encode(cfg); err != nil {
return err
}
return nil
}
func Export() (string, error) {
data, err := json.Marshal(Packages)
return string(data), err
}
func PackageMap() map[string]Package {
pkgs := make(map[string]Package)
for _, pkg := range Packages {
pkgs[pkg.Name] = pkg
}
return pkgs
}
func AddPackages(force bool, pkgs ...Package) {
for _, pkg := range pkgs {
for idx, p := range Packages {
if strings.EqualFold(p.Name, pkg.Name) {
if force {
Packages[idx] = pkg
break
}
forceQuestion := &survey.Confirm{
Message: fmt.Sprintf("Package `%s` (%s) already exists. Overwrite with `%s`?", p.Name, p.Import, p.Import),
Default: false,
}
var forceAnswer bool
if err := survey.AskOne(forceQuestion, &forceAnswer); err != nil {
beaver.Error(err)
break
}
if !forceAnswer {
beaver.Errorf("leaving package `%s` as-is", pkg.Name)
break
}
Packages[idx] = pkg
break
}
}
Packages = append(Packages, pkg)
}
}