vanity/flags/config.go

106 lines
2.7 KiB
Go

package flags
import (
"os"
"strings"
"time"
"go.jolheiser.com/vanity/api"
"github.com/pelletier/go-toml"
"github.com/urfave/cli/v2"
"go.jolheiser.com/beaver"
)
type tomlConfig struct {
Port int `toml:"port"`
Domain string `toml:"domain"`
Service string `toml:"service"`
BaseURL string `toml:"base_url"`
Namespace string `toml:"namespace"`
Token string `toml:"token"`
Include []string `toml:"include"`
Exclude []string `toml:"exclude"`
Private bool `toml:"private"`
Fork bool `toml:"fork"`
Mirror bool `toml:"mirror"`
Archive bool `toml:"archive"`
Override []string `toml:"override"`
Interval time.Duration `toml:"interval"`
Debug bool `toml:"debug"`
Packages []*api.Package `toml:"packages"`
}
func setConfig(ctx *cli.Context) {
for _, env := range os.Environ() {
kv := strings.Split(env, "=")
if strings.HasPrefix(kv[0], "VANITY_OVERRIDES_") {
override := strings.ToLower(strings.TrimPrefix(kv[0], "VANITY_OVERRIDES_"))
Override[override] = kv[1]
}
}
var cfg tomlConfig
if configPath != "" {
beaver.Infof("Loading configuration from %s", configPath)
tree, err := toml.LoadFile(configPath)
if err != nil {
beaver.Errorf("Could not load configuration from %s: %v", configPath, err)
return
}
if err = tree.Unmarshal(&cfg); err != nil {
beaver.Errorf("Could not unmarshal configuration from %s: %v", configPath, err)
return
}
}
if !ctx.IsSet("port") && cfg.Port > 0 {
Port = cfg.Port
}
if !ctx.IsSet("domain") && cfg.Domain != "" {
Domain = cfg.Domain
}
if !ctx.IsSet("service") && cfg.Service != "" {
Service = cfg.Service
}
if !ctx.IsSet("base-url") && cfg.BaseURL != "" {
baseURL = cfg.BaseURL
}
if !ctx.IsSet("namespace") && cfg.Namespace != "" {
Namespace = cfg.Namespace
}
if !ctx.IsSet("token") && cfg.Token != "" {
Token = cfg.Token
}
if !ctx.IsSet("include") && len(cfg.Include) > 0 {
_ = include.Set(strings.Join(cfg.Include, ","))
}
if !ctx.IsSet("exclude") && len(cfg.Exclude) > 0 {
_ = exclude.Set(strings.Join(cfg.Exclude, ","))
}
if !ctx.IsSet("override") && len(cfg.Override) > 0 {
_ = override.Set(strings.Join(cfg.Override, ","))
}
if !ctx.IsSet("private") && cfg.Private {
Private = cfg.Private
}
if !ctx.IsSet("fork") && cfg.Fork {
Fork = cfg.Fork
}
if !ctx.IsSet("mirror") && cfg.Mirror {
Mirror = cfg.Mirror
}
if !ctx.IsSet("archive") && cfg.Archive {
Archive = cfg.Archive
}
if !ctx.IsSet("interval") && cfg.Interval.Seconds() > 0 {
Interval = cfg.Interval
}
if !ctx.IsSet("debug") && cfg.Debug {
Debug = cfg.Debug
}
ConfigPackages = cfg.Packages
}