diff options
author | Valery Piashchynski <[email protected]> | 2021-02-16 00:04:05 +0300 |
---|---|---|
committer | Valery Piashchynski <[email protected]> | 2021-02-16 00:04:05 +0300 |
commit | 87b3130a95e2ff2904e7910f9bc87bc3020dbe27 (patch) | |
tree | cc08fda6ccdc56ec26b0ef39f2fa80d6b950086a /plugins | |
parent | f8dd689d3b7c9f953d21775110f7d3182768cfba (diff) |
Add support for flag overwriting
Signed-off-by: Valery Piashchynski <[email protected]>
Diffstat (limited to 'plugins')
-rwxr-xr-x | plugins/config/plugin.go | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/plugins/config/plugin.go b/plugins/config/plugin.go index ce2baa85..ddb7fe88 100755 --- a/plugins/config/plugin.go +++ b/plugins/config/plugin.go @@ -2,6 +2,7 @@ package config import ( "bytes" + "fmt" "strings" "github.com/spf13/viper" @@ -14,6 +15,9 @@ type Viper struct { Prefix string Type string ReadInCfg []byte + // user defined Flags in the form of <option>.<key> = <value> + // which overwrites initial config key + Flags []string } // Inits config provider. @@ -40,6 +44,23 @@ func (v *Viper) Init() error { v.viper.SetConfigFile(v.Path) v.viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) + err := v.viper.ReadInConfig() + if err != nil { + return errors.E(op, err) + } + + // override config Flags + if len(v.Flags) > 0 { + for _, f := range v.Flags { + key, val, err := parseFlag(f) + if err != nil { + return errors.E(op, err) + } + + v.viper.Set(key, val) + } + } + return v.viper.ReadInConfig() } @@ -82,3 +103,25 @@ func (v *Viper) Get(name string) interface{} { func (v *Viper) Has(name string) bool { return v.viper.IsSet(name) } + +func parseFlag(flag string) (string, string, error) { + const op = errors.Op("parse_flag") + if !strings.Contains(flag, "=") { + return "", "", errors.E(op, errors.Errorf("invalid flag `%s`", flag)) + } + + parts := strings.SplitN(strings.TrimLeft(flag, " \"'`"), "=", 2) + + return strings.Trim(parts[0], " \n\t"), parseValue(strings.Trim(parts[1], " \n\t")), nil +} + +func parseValue(value string) string { + escape := []rune(value)[0] + + if escape == '"' || escape == '\'' || escape == '`' { + value = strings.Trim(value, string(escape)) + value = strings.ReplaceAll(value, fmt.Sprintf("\\%s", string(escape)), string(escape)) + } + + return value +} |