Allow to pass string list via Enviroment

Allow to pass comma-separated strings via Enviroment variables and store
them in a string slice.
This commit is contained in:
Ralf Haferkamp
2022-04-11 18:17:21 +02:00
parent e24a5a47d2
commit b0fb996b82
5 changed files with 74 additions and 12 deletions
+13
View File
@@ -0,0 +1,13 @@
package config_test
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestConfig(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Config Suite")
}
+11 -12
View File
@@ -1,17 +1,16 @@
package config
package config_test
import (
"fmt"
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/owncloud/ocis/ocis-pkg/config"
"gopkg.in/yaml.v2"
)
func TestDefaultConfig(t *testing.T) {
cfg := DefaultConfig()
yBytes, err := yaml.Marshal(cfg)
if err != nil {
panic(err)
}
fmt.Println(string(yBytes))
}
var _ = Describe("Config", func() {
It("Success generating the default config", func() {
cfg := config.DefaultConfig()
_, err := yaml.Marshal(cfg)
Expect(err).To(BeNil())
})
})
+14
View File
@@ -3,6 +3,7 @@ package config
import (
"fmt"
"reflect"
"strings"
gofig "github.com/gookit/config/v2"
"github.com/owncloud/ocis/ocis-pkg/shared"
@@ -35,6 +36,11 @@ func bindEnv(c *gofig.Config, bindings []shared.EnvBinding) error {
// defaults to float64
r := c.Float(bindings[i].EnvVars[j])
*bindings[i].Destination.(*float64) = r
case "*[]string":
// Treat values a comma-separated list
r := c.String(bindings[i].EnvVars[j])
vals := envStringToSlice(r)
*bindings[i].Destination.(*[]string) = vals
default:
// it is unlikely we will ever get here. Let this serve more as a runtime check for when debugging.
return fmt.Errorf("invalid type for env var: `%v`", bindings[i].EnvVars[j])
@@ -45,3 +51,11 @@ func bindEnv(c *gofig.Config, bindings []shared.EnvBinding) error {
return nil
}
func envStringToSlice(value string) []string {
vals := strings.Split(value, ",")
for i := range vals {
vals[i] = strings.TrimSpace(vals[i])
}
return vals
}
+35
View File
@@ -0,0 +1,35 @@
package config_test
import (
gofig "github.com/gookit/config/v2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
ociscfg "github.com/owncloud/ocis/ocis-pkg/config"
"github.com/owncloud/ocis/ocis-pkg/shared"
)
var _ = Describe("Environment", func() {
It("Succeed to parse a comma separated list in to a sting slice", func() {
cfg := gofig.NewEmpty("test")
err := cfg.Set("stringlist", "one,two,three")
Expect(err).To(Not(HaveOccurred()))
err = cfg.Set("stringlist2", "one ,two , t h r e e")
Expect(err).To(Not(HaveOccurred()))
var stringTest, stringTest2 []string
eb := []shared.EnvBinding{
{
EnvVars: []string{"stringlist"},
Destination: &stringTest,
},
{
EnvVars: []string{"stringlist2"},
Destination: &stringTest2,
},
}
err = ociscfg.BindEnv(cfg, eb)
Expect(err).To(Not(HaveOccurred()))
Expect(stringTest).To(Equal([]string{"one", "two", "three"}))
Expect(stringTest2).To(Equal([]string{"one", "two", "t h r e e"}))
})
})