From e6bfb6ef5f298586276fb7eee3865b982b9e7159 Mon Sep 17 00:00:00 2001 From: Antonio Pagano Date: Mon, 15 Apr 2024 14:41:13 -0500 Subject: [PATCH] fix: fixing envor variables with multiple equals --- envor/envor.go | 24 +++++++++++++++----- envor/envor_test.go | 54 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 6 deletions(-) create mode 100644 envor/envor_test.go diff --git a/envor/envor.go b/envor/envor.go index 2c5b9e4..1b57941 100644 --- a/envor/envor.go +++ b/envor/envor.go @@ -2,6 +2,7 @@ package envor import ( "bufio" + "io" "os" "strings" "sync" @@ -34,7 +35,19 @@ func loadENV() { return } - scanner := bufio.NewScanner(file) + for key, value := range parseVars(file) { + err := os.Setenv(key, value) + if err != nil { + continue + } + } +} + +// parseVars reads the variables from the reader and sets them +// in the environment. +func parseVars(r io.Reader) map[string]string { + vars := make(map[string]string) + scanner := bufio.NewScanner(r) for scanner.Scan() { line := scanner.Text() if line == "" { @@ -46,7 +59,7 @@ func loadENV() { continue } - pair := strings.Split(line, "=") + pair := strings.SplitN(line, "=", 2) if len(pair) != 2 { continue } @@ -55,9 +68,8 @@ func loadENV() { value := strings.TrimSpace(pair[1]) value = strings.Trim(value, "\"") - err := os.Setenv(key, value) - if err != nil { - continue - } + vars[key] = value } + + return vars } diff --git a/envor/envor_test.go b/envor/envor_test.go new file mode 100644 index 0000000..3239de7 --- /dev/null +++ b/envor/envor_test.go @@ -0,0 +1,54 @@ +package envor + +import ( + "strings" + "testing" +) + +func TestParseVars(t *testing.T) { + + t.Run("simple one", func(t *testing.T) { + r := strings.NewReader("KEY=value\n") + vars := parseVars(r) + + if vars["KEY"] != "value" { + t.Errorf("Expected value to be 'value', got %s", vars["KEY"]) + } + }) + + t.Run("multiple", func(t *testing.T) { + vars := parseVars(strings.NewReader(` + KEY=value + KEY2=value + `)) + + if vars["KEY"] != "value" { + t.Errorf("Expected value to be 'value', got %s", vars["KEY"]) + } + + if vars["KEY2"] != "value" { + t.Errorf("Expected value to be 'value', got %s", vars["KEY"]) + } + }) + + t.Run("quotes", func(t *testing.T) { + vars := parseVars(strings.NewReader(` + KEY="value" + `)) + + if vars["KEY"] != "value" { + t.Errorf("Expected value to be 'value', got %s", vars["KEY"]) + } + }) + + t.Run("multiple equals sign", func(t *testing.T) { + vars := parseVars(strings.NewReader(` + KEY="value=with=equals" + `)) + + if vars["KEY"] != "value=with=equals" { + t.Errorf("Expected value to be 'value=with=equals', got %s", vars["KEY"]) + } + }) + +}