summaryrefslogtreecommitdiff
path: root/plugins/config/plugin.go
diff options
context:
space:
mode:
authorValery Piashchynski <[email protected]>2020-11-05 17:58:23 +0300
committerGitHub <[email protected]>2020-11-05 17:58:23 +0300
commit9fbe7726dd55cfedda724b7644e1b6bf7c1a6cb4 (patch)
treef2bf9b97d38103de51e2d140aa76666f9c6341c8 /plugins/config/plugin.go
parentedc45b3e24afdb5e56e74ffbbbd50e0e3b04922b (diff)
parent73da7300fcc9b8b22faa1c91fc1faff22ab944ff (diff)
Merge pull request #388 from spiral/enhancement/testsv2.0.0-alpha15
Tests for the new plugins
Diffstat (limited to 'plugins/config/plugin.go')
-rwxr-xr-xplugins/config/plugin.go91
1 files changed, 91 insertions, 0 deletions
diff --git a/plugins/config/plugin.go b/plugins/config/plugin.go
new file mode 100755
index 00000000..2555d28a
--- /dev/null
+++ b/plugins/config/plugin.go
@@ -0,0 +1,91 @@
+package config
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/spf13/viper"
+)
+
+type Viper struct {
+ viper *viper.Viper
+ Path string
+ Prefix string
+}
+
+// Inits config provider.
+func (v *Viper) Init() error {
+ v.viper = viper.New()
+
+ // read in environment variables that match
+ v.viper.AutomaticEnv()
+ if v.Prefix == "" {
+ return errors.New("prefix should be set")
+ }
+
+ v.viper.SetEnvPrefix(v.Prefix)
+ if v.Path == "" {
+ return errors.New("path should be set")
+ }
+
+ v.viper.SetConfigFile(v.Path)
+ v.viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
+
+ return v.viper.ReadInConfig()
+}
+
+// Overwrite overwrites existing config with provided values
+func (v *Viper) Overwrite(values map[string]string) error {
+ if len(values) != 0 {
+ for _, flag := range values {
+ key, value, err := parseFlag(flag)
+ if err != nil {
+ return err
+ }
+ v.viper.Set(key, value)
+ }
+ }
+
+ return nil
+}
+
+// UnmarshalKey reads configuration section into configuration object.
+func (v *Viper) UnmarshalKey(name string, out interface{}) error {
+ err := v.viper.UnmarshalKey(name, &out)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+// Get raw config in a form of config section.
+func (v *Viper) Get(name string) interface{} {
+ return v.viper.Get(name)
+}
+
+// Has checks if config section exists.
+func (v *Viper) Has(name string) bool {
+ return v.viper.IsSet(name)
+}
+
+func parseFlag(flag string) (string, string, error) {
+ if !strings.Contains(flag, "=") {
+ return "", "", fmt.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
+}