From 06011e07449a47a4929592116ba3d8ecdd021bee Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Sun, 29 May 2016 01:56:12 +0200 Subject: [PATCH] Added environment helpers --- env/env.go | 26 ++++++++++++++++++++ env/env_suite_test.go | 13 ++++++++++ env/env_test.go | 55 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 94 insertions(+) create mode 100644 env/env.go create mode 100644 env/env_suite_test.go create mode 100644 env/env_test.go diff --git a/env/env.go b/env/env.go new file mode 100644 index 0000000..14c9958 --- /dev/null +++ b/env/env.go @@ -0,0 +1,26 @@ +package env + +import "strings" + +// ListToMap converts a list of strings in format KEY=VALUE into a map +func ListToMap(list []string) map[string]string { + out := map[string]string{} + for _, entry := range list { + if len(entry) == 0 || entry[0] == '#' { + continue + } + + parts := strings.SplitN(entry, "=", 2) + out[parts[0]] = strings.Trim(parts[1], "\"") + } + return out +} + +// MapToList converts a map into a list of strings in format KEY=VALUE +func MapToList(envMap map[string]string) []string { + out := []string{} + for k, v := range envMap { + out = append(out, k+"="+v) + } + return out +} diff --git a/env/env_suite_test.go b/env/env_suite_test.go new file mode 100644 index 0000000..0054723 --- /dev/null +++ b/env/env_suite_test.go @@ -0,0 +1,13 @@ +package env_test + +import ( + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" + + "testing" +) + +func TestEnv(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "Env Suite") +} diff --git a/env/env_test.go b/env/env_test.go new file mode 100644 index 0000000..8cce912 --- /dev/null +++ b/env/env_test.go @@ -0,0 +1,55 @@ +package env_test + +import ( + "sort" + + . "github.com/Luzifer/go_helpers/env" + + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +var _ = Describe("Env", func() { + + Context("ListToMap", func() { + var ( + list = []string{ + "FIRST_KEY=firstvalue", + "SECOND_KEY=secondvalue", + "WEIRD=", + "", + } + emap = map[string]string{ + "FIRST_KEY": "firstvalue", + "SECOND_KEY": "secondvalue", + "WEIRD": "", + } + ) + + It("should convert the list in the expected way", func() { + Expect(ListToMap(list)).To(Equal(emap)) + }) + }) + + Context("MapToList", func() { + var ( + list = []string{ + "FIRST_KEY=firstvalue", + "SECOND_KEY=secondvalue", + "WEIRD=", + } + emap = map[string]string{ + "FIRST_KEY": "firstvalue", + "SECOND_KEY": "secondvalue", + "WEIRD": "", + } + ) + + It("should convert the map in the expected way", func() { + l := MapToList(emap) + sort.Strings(l) // Workaround: The test needs the elements to be in same order + Expect(l).To(Equal(list)) + }) + }) + +})