package config import ( "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 Domain string Packages []Package ) type Config struct { Domain string `toml:"domain"` Packages []Package `toml:"package" json:"packages"` } type Package struct { Name string `toml:"name"` Path string `toml:"path"` Repo string `toml:"repo"` SSH string `toml:"ssh"` Description string `toml:"description"` } func (pkg Package) Module() string { return fmt.Sprintf("%s/%s", Domain, pkg.Path) } // 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/.vanity/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 vanity home: %v", err) } if _, err := os.Create(configPath); err != nil { beaver.Fatalf("could not create vanity config: %v", err) } } if _, err := toml.DecodeFile(configPath, &cfg); err != nil { beaver.Fatalf("could not decode vanity 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 } Domain = cfg.Domain Packages = cfg.Packages } func Save() error { cfg.Domain = Domain 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 PackageMap() map[string]Package { pkgs := make(map[string]Package) for _, pkg := range Packages { pkgs[pkg.Path] = 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.Repo, p.Repo), 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) } }