mediocre-blog/srv/cfg/cfg.go

201 lines
4.7 KiB
Go
Raw Normal View History

// Package cfg implements a simple wrapper around go's flag package, in order to
// implement initialization hooks.
package cfg
import (
"context"
"flag"
2022-05-06 02:17:59 +00:00
"fmt"
"os"
2022-05-06 02:17:59 +00:00
"strconv"
"strings"
)
// Cfger is a component which can be used with Cfg to setup its initialization.
type Cfger interface {
SetupCfg(*Cfg)
}
2022-05-06 02:17:59 +00:00
// Params are used to initialize a Cfg instance.
type Params struct {
// Args are the command line arguments, excluding the command-name.
//
// Defaults to os.Args[1:]
Args []string
// Env is the process's environment variables.
//
// Defaults to the real environment variables.
Env map[string]string
// EnvPrefix indicates a string to prefix to all environment variable names
// that Cfg will read. Will be automatically suffixed with a "_" if given.
EnvPrefix string
}
func (p Params) withDefaults() Params {
if p.Args == nil {
p.Args = os.Args[1:]
}
if p.Env == nil {
p.Env = map[string]string{}
for _, envVar := range os.Environ() {
parts := strings.SplitN(envVar, "=", 2)
if len(parts) < 2 {
panic(fmt.Sprintf("envVar %q returned from os.Environ() somehow", envVar))
}
p.Env[parts[0]] = parts[1]
}
}
if p.EnvPrefix != "" {
p.EnvPrefix = strings.TrimSuffix(p.EnvPrefix, "_") + "_"
}
return p
}
// Cfg is a wrapper around the stdlib's FlagSet and a set of initialization
// hooks.
type Cfg struct {
2022-05-06 02:17:59 +00:00
params Params
flagSet *flag.FlagSet
hooks []func(ctx context.Context) error
}
// New initializes and returns a new instance of *Cfg.
2022-05-06 02:17:59 +00:00
func New(params Params) *Cfg {
params = params.withDefaults()
return &Cfg{
2022-05-06 02:17:59 +00:00
params: params,
flagSet: flag.NewFlagSet("", flag.ExitOnError),
}
}
// OnInit appends the given callback to the sequence of hooks which will run on
// a call to Init.
func (c *Cfg) OnInit(cb func(context.Context) error) {
c.hooks = append(c.hooks, cb)
}
// Init runs all hooks registered using OnInit, in the same order OnInit was
// called. If one returns an error that error is returned and no further hooks
// are run.
func (c *Cfg) Init(ctx context.Context) error {
2022-05-06 02:17:59 +00:00
if err := c.flagSet.Parse(c.params.Args); err != nil {
return err
}
for _, h := range c.hooks {
if err := h(ctx); err != nil {
return err
}
}
return nil
}
2022-05-06 02:17:59 +00:00
func (c *Cfg) envifyName(name string) string {
name = c.params.EnvPrefix + name
name = strings.Replace(name, "-", "_", -1)
name = strings.ToUpper(name)
return name
}
func envifyUsage(envName, usage string) string {
return fmt.Sprintf("%s (overrides %s)", usage, envName)
}
// StringVar is equivalent to flag.FlagSet's StringVar method, but will
// additionally set up an environment variable for the parameter.
func (c *Cfg) StringVar(p *string, name, value, usage string) {
envName := c.envifyName(name)
c.flagSet.StringVar(p, name, value, envifyUsage(envName, usage))
if val := c.params.Env[envName]; val != "" {
*p = val
}
}
// String is equivalent to flag.FlagSet's String method, but will additionally
// set up an environment variable for the parameter.
func (c *Cfg) String(name, value, usage string) *string {
p := new(string)
c.StringVar(p, name, value, usage)
return p
}
// IntVar is equivalent to flag.FlagSet's IntVar method, but will additionally
// set up an environment variable for the parameter.
func (c *Cfg) IntVar(p *int, name string, value int, usage string) {
envName := c.envifyName(name)
c.flagSet.IntVar(p, name, value, envifyUsage(envName, usage))
// if we can't parse the envvar now then just hold onto the error until
// Init, otherwise we'd have to panic here and that'd be ugly.
var err error
if valStr := c.params.Env[envName]; valStr != "" {
var val int
val, err = strconv.Atoi(valStr)
if err != nil {
err = fmt.Errorf(
"parsing envvar %q with value %q: %w",
envName, valStr, err,
)
} else {
*p = val
}
}
c.OnInit(func(context.Context) error { return err })
}
// Int is equivalent to flag.FlagSet's Int method, but will additionally set up
// an environment variable for the parameter.
func (c *Cfg) Int(name string, value int, usage string) *int {
p := new(int)
c.IntVar(p, name, value, usage)
return p
}
// SubCmd should be called _after_ Init. Init will have consumed all arguments
// up until the first non-flag argument. This non-flag argument is a
// sub-command, and is returned by this method. This method also resets Cfg's
// internal state so that new options can be added to it.
//
// If there is no sub-command following the initial set of flags then this will
// return empty string.
func (c *Cfg) SubCmd() string {
2022-05-06 02:17:59 +00:00
c.params.Args = c.flagSet.Args()
if len(c.params.Args) == 0 {
return ""
}
2022-05-06 02:17:59 +00:00
subCmd := c.params.Args[0]
2022-05-06 02:17:59 +00:00
c.flagSet = flag.NewFlagSet(subCmd, flag.ExitOnError)
c.hooks = nil
2022-05-06 02:17:59 +00:00
c.params.Args = c.params.Args[1:]
return subCmd
}