envconf/envconf.go

399 lines
9.0 KiB
Go
Raw Permalink Normal View History

2021-03-23 09:13:25 +00:00
package envconf
2021-03-23 08:48:02 +00:00
2021-03-26 16:17:52 +00:00
import (
"errors"
"fmt"
"os"
"strings"
"time"
"unicode"
)
2021-03-23 08:48:02 +00:00
2021-03-23 10:40:25 +00:00
type cEntry struct {
2021-03-26 16:17:52 +00:00
value string
parsed cValue
dtype DataType
unset bool
empty bool
2021-06-18 12:56:49 +00:00
defval string // The default value
hasdef bool // Default value is defined
2021-03-23 10:40:25 +00:00
}
2022-01-15 16:55:29 +00:00
2021-03-23 11:57:09 +00:00
type Config struct {
2021-03-26 16:17:52 +00:00
parsed bool
env map[string]cEntry
2022-01-15 16:55:29 +00:00
mapEnv map[string]map[string]cEntry
2021-03-23 10:08:26 +00:00
}
2021-03-26 11:06:39 +00:00
// NewConfig returns an envconf.Config that is used to read configuration from environment variables.
// The environment variables are stored in envconf.Config, so changes to the environment after NewConfig has been called
// will not be taken into account.
2021-03-26 16:17:52 +00:00
func NewConfig() *Config {
config := new(Config)
config.parsed = false
config.env = make(map[string]cEntry)
2022-01-15 16:55:29 +00:00
config.mapEnv = make(map[string]map[string]cEntry)
2021-03-26 16:17:52 +00:00
for _, v := range os.Environ() {
splitted := strings.SplitN(v, "=", 2)
if len(splitted) == 2 {
2022-01-15 16:55:29 +00:00
key := cleanKey(splitted[0])
keysplit := strings.Split(key, "_")
left := ""
right := ""
if len(keysplit) > 1 {
left = strings.Join(keysplit[:len(keysplit)-1], "_")
right = keysplit[len(keysplit)-1]
}
2021-03-26 16:17:52 +00:00
if unicode.IsLetter(getFirstRune(key)) {
var entry cEntry
entry.value = splitted[1]
entry.dtype = TypeNone
entry.unset = false
entry.empty = false
config.env[key] = entry
2022-01-15 16:55:29 +00:00
config.mapEnv[left][right] = entry
2021-03-26 16:17:52 +00:00
}
}
}
return config
2021-03-23 08:48:02 +00:00
}
2022-01-15 16:55:29 +00:00
// Define the type of an environment variable.
2021-03-26 11:06:39 +00:00
// Variables without a defined type will be ignored by Parse.
2021-03-23 10:40:25 +00:00
func (c *Config) Define(key string, dtype DataType) {
2021-03-26 16:17:52 +00:00
upper := strings.ToUpper(key)
entry, ok := c.env[upper]
if ok {
entry.dtype = dtype
c.env[upper] = entry
} else {
var entry cEntry
entry.dtype = dtype
entry.unset = true
entry.empty = true
c.env[upper] = entry
}
2021-03-23 10:40:25 +00:00
}
2021-03-23 11:57:09 +00:00
2022-01-15 16:55:29 +00:00
// Define the type of an environment variable.
// Variables without a defined type will be ignored by Parse.
func (c *Config) DefineMap(key string, dtype DataType) {
upper := strings.ToUpper(key)
entries, ok := c.mapEnv[upper]
if ok {
for mapKey, entry := range entries {
entry.dtype = dtype
c.mapEnv[key][mapKey] = entry
}
}
}
// Define the type and default value of an environment variable.
2021-03-26 11:06:39 +00:00
// Variables without a defined type will be ignored by Parse.
2021-03-23 11:57:09 +00:00
func (c *Config) DefineDefault(key string, val string, dtype DataType) {
2021-03-26 16:17:52 +00:00
upper := strings.ToUpper(key)
entry, ok := c.env[upper]
if ok {
if entry.unset {
entry.value = val
}
entry.dtype = dtype
entry.empty = false
2021-06-18 12:56:49 +00:00
entry.defval = val
2021-06-18 13:07:31 +00:00
entry.hasdef = true
2021-03-26 16:17:52 +00:00
c.env[upper] = entry
} else {
var entry cEntry
entry.dtype = dtype
entry.unset = true
entry.empty = false
entry.value = val
2021-06-18 12:56:49 +00:00
entry.defval = val
2021-06-18 13:07:31 +00:00
entry.hasdef = true
2021-03-26 16:17:52 +00:00
c.env[upper] = entry
}
2021-03-23 11:57:09 +00:00
}
2021-03-26 11:06:39 +00:00
// Parse parses the environment variables previously defined by Define and DefineDefault.
// Parse should only be called once for a given envconf.Config.
2021-03-23 11:57:09 +00:00
func (c *Config) Parse() {
2021-03-26 16:17:52 +00:00
if c.parsed {
return
}
c.parsed = true
2021-06-18 08:39:51 +00:00
failed := false
2021-03-26 16:17:52 +00:00
for k, v := range c.env {
if v.empty {
if v.unset {
2021-06-18 08:39:51 +00:00
failed = true
2021-03-26 16:17:52 +00:00
}
} else {
v.parsed = v.dtype.parse(k, v.value)
c.env[k] = v
}
}
2022-01-15 16:55:29 +00:00
for k, v := range c.mapEnv {
for mk, mv := range v {
mv.parsed = mv.dtype.parse(k+"_"+mk, mv.value)
c.mapEnv[k][mk] = mv
}
}
2021-06-18 09:48:40 +00:00
if failed {
for k, v := range c.env {
if (v.parsed.err == nil) && v.unset {
2021-06-18 09:00:08 +00:00
if v.empty {
2021-06-18 08:50:45 +00:00
v.parsed.err = errors.New(fmt.Sprintf(`Environment variable "%s" not found. It should have been of type %s.`, k, v.dtype))
c.env[k] = v
} else {
2021-06-18 09:48:40 +00:00
v.parsed.err = errors.New(fmt.Sprintf(`Environment variable "%s" not found. Default value "%s" of type %s used.`, k, v.value, v.dtype))
2021-06-18 08:50:45 +00:00
c.env[k] = v
}
2021-06-18 08:39:51 +00:00
}
}
}
2021-03-23 11:57:09 +00:00
}
2021-06-18 12:56:49 +00:00
func (c *Config) help() {
2021-06-18 12:29:18 +00:00
max := make([]int, 2, 2)
2021-06-18 13:07:31 +00:00
preq := false
pdef := false
2021-06-18 12:19:53 +00:00
for k, v := range c.env {
if v.dtype != TypeNone {
2021-06-18 12:29:18 +00:00
if len(k) > max[0] {
max[0] = len(k)
2021-06-18 12:19:53 +00:00
}
2021-06-18 12:29:18 +00:00
if len(v.dtype.String()) > max[1] {
max[1] = len(v.dtype.String())
2021-06-18 12:19:53 +00:00
}
2021-06-18 13:07:31 +00:00
if v.hasdef {
pdef = true
} else {
preq = true
}
2021-06-18 12:19:53 +00:00
}
}
2021-06-18 13:07:31 +00:00
if pdef {
fmt.Println()
for k, v := range c.env {
if v.dtype != TypeNone {
if v.hasdef {
2021-06-18 13:17:55 +00:00
format := fmt.Sprintf("Variable %%-%ds| Type %%-%ds| Default %%s\n", max[0]+5, max[1]+3)
2021-06-18 13:20:38 +00:00
fmt.Printf(format, fmt.Sprintf(`"%s"`, k), v.dtype, fmt.Sprintf(`"%s"`, v.defval))
2021-06-18 13:07:31 +00:00
}
2021-06-18 12:56:49 +00:00
}
}
}
2021-06-18 13:07:31 +00:00
if preq {
fmt.Println()
for k, v := range c.env {
if v.dtype != TypeNone {
if !v.hasdef {
2021-06-18 13:17:55 +00:00
format := fmt.Sprintf("Variable %%-%ds| Type %%-%ds| Required\n", max[0]+5, max[1]+3)
2021-06-18 13:20:38 +00:00
fmt.Printf(format, fmt.Sprintf(`"%s"`, k), v.dtype)
2021-06-18 13:07:31 +00:00
}
2021-06-18 12:56:49 +00:00
}
}
}
fmt.Println()
}
func (c *Config) StatusHelp() bool {
flags := make(map[string]bool)
flags["--help"] = true
flags["-help"] = true
flags["-h"] = true
if len(os.Args) > 1 {
key := strings.ToLower(strings.TrimSpace(os.Args[1]))
_, ok := flags[key]
if ok {
c.help()
return false
2021-06-18 12:19:53 +00:00
}
}
2021-06-18 12:56:49 +00:00
return c.Status()
2021-06-18 12:19:53 +00:00
}
2021-03-26 11:06:39 +00:00
// Status prints out failures that occured while parsing the environment to os.Stderr.
// Variables that have been defined without a default value and are
// missing from the environment will be considered a failure.
// If parsing of any of the variables has failed Status will return false.
2021-03-26 16:17:52 +00:00
func (c *Config) Status() (ok bool) {
ok = c.parsed
if ok {
for _, v := range c.env {
err := v.parsed.err
if err != nil {
ok = false
2021-06-18 09:56:07 +00:00
if !v.empty {
fmt.Fprintln(os.Stderr, err)
}
}
}
2022-01-15 16:55:29 +00:00
for _, v := range c.mapEnv {
for _, mv := range v {
err := mv.parsed.err
if err != nil {
ok = false
if !mv.empty {
fmt.Fprintln(os.Stderr, err)
}
}
}
}
2021-06-18 09:56:07 +00:00
if !ok {
fmt.Fprintln(os.Stderr, "")
for _, v := range c.env {
err := v.parsed.err
if (err != nil) && v.empty {
fmt.Fprintln(os.Stderr, err)
}
2021-03-26 16:17:52 +00:00
}
}
}
return
2021-03-23 11:57:09 +00:00
}
2022-01-15 16:55:29 +00:00
func cleanKey(str string) string {
fn := func(r rune) rune {
if (r >= '0' && r <= '9') || (r >= 'A' && r <= 'Z') || r == '_' {
return r
}
return -1
}
str = strings.Map(fn, strings.ToUpper(str))
oldlen := len(str) + 1
newlen := len(str)
for newlen < oldlen {
oldlen = newlen
str = strings.ReplaceAll(str, "__", "_")
newlen = len(str)
}
return str
}
2021-03-26 16:17:52 +00:00
func (c *Config) getRaw(key string, dtype DataType) (val cValue) {
val.dtype = TypeNone
if c.parsed {
upper := strings.ToUpper(key)
entry, ok := c.env[upper]
if ok && (entry.dtype == dtype) {
return entry.parsed
}
}
return
2021-03-25 13:18:26 +00:00
}
2022-01-15 16:55:29 +00:00
func (c *Config) getRawMap(key string, dtype DataType) (empty map[string]cValue) {
empty = make(map[string]cValue)
retval := make(map[string]cValue)
if c.parsed {
key = cleanKey(key)
entries, ok := c.mapEnv[key]
if ok {
for k, v := range entries {
if v.dtype == dtype {
retval[k] = v.parsed
} else {
return
}
}
return retval
}
}
return
}
2021-03-26 11:06:39 +00:00
// GetInt returns the value of an environment variable.
// If the variable is not defined as envconf.TypeInt the function will return 0.
2021-03-26 16:17:52 +00:00
func (c *Config) GetInt(key string) int64 {
val := c.getRaw(key, TypeInt)
return val.intval
2021-03-23 13:37:00 +00:00
}
2021-03-26 11:06:39 +00:00
// GetMetric returns the value of an environment variable.
// If the variable is not defined as envconf.TypeMetric the function will return 0.
2021-03-26 16:17:52 +00:00
func (c *Config) GetMetric(key string) int64 {
val := c.getRaw(key, TypeMetric)
return val.intval
2021-03-25 11:06:08 +00:00
}
2021-03-26 11:06:39 +00:00
// GetDirectory returns the value of an environment variable.
// If the variable is not defined as envconf.TypeDirectory the
// function will return the empty string.
2021-03-26 16:17:52 +00:00
func (c *Config) GetDirectory(key string) string {
val := c.getRaw(key, TypeDirectory)
return val.strval
2021-03-24 14:15:37 +00:00
}
2021-03-26 11:06:39 +00:00
// GetString returns the value of an environment variable.
// If the variable is not defined as envconf.TypeString the
// function will return the empty string.
2021-03-26 16:17:52 +00:00
func (c *Config) GetString(key string) string {
val := c.getRaw(key, TypeString)
return val.strval
2021-03-23 13:37:00 +00:00
}
2021-03-26 11:06:39 +00:00
// GetDuration returns the value of an environment variable.
// If the variable is not defined as envconf.TypeDuration the
// function will return time.Duration(0).
2021-03-26 16:17:52 +00:00
func (c *Config) GetDuration(key string) time.Duration {
val := c.getRaw(key, TypeDuration)
return val.durval
2021-03-23 13:37:00 +00:00
}
2021-03-26 11:06:39 +00:00
// GetBool returns the value of an environment variable.
// If the variable is not defined as envconf.TypeBool the
// function will return false.
2021-03-26 16:17:52 +00:00
func (c *Config) GetBool(key string) bool {
val := c.getRaw(key, TypeBool)
return val.boolval
2021-03-23 11:57:09 +00:00
}
2022-01-15 16:55:29 +00:00
func (c *Config) GetMapInt(key string) (retval map[string]int64) {
retval = make(map[string]int64)
for k, v := range c.getRawMap(key, TypeInt) {
retval[k] = v.intval
}
return
}
func (c *Config) GetMapDuration(key string) (retval map[string]time.Duration) {
retval = make(map[string]time.Duration)
for k, v := range c.getRawMap(key, TypeDuration) {
retval[k] = v.durval
}
return
}
func (c *Config) GetMapString(key string) (retval map[string]string) {
retval = make(map[string]string)
for k, v := range c.getRawMap(key, TypeString) {
retval[k] = v.strval
}
return
}
func (c *Config) GetMapBool(key string) (retval map[string]bool) {
retval = make(map[string]bool)
for k, v := range c.getRawMap(key, TypeBool) {
retval[k] = v.boolval
}
return
}
2021-03-26 16:17:52 +00:00
func getFirstRune(str string) rune {
for _, v := range str {
return v
}
return rune(0)
2021-03-23 11:57:09 +00:00
}