Skip to content

Commit

Permalink
Merge pull request #3 from leapkit/fix-envor-multiple-equals
Browse files Browse the repository at this point in the history
fix: fixing Envor variables with multiple equals
  • Loading branch information
paganotoni committed Apr 15, 2024
2 parents 2b7b445 + e6bfb6e commit 204724e
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 6 deletions.
24 changes: 18 additions & 6 deletions envor/envor.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package envor

import (
"bufio"
"io"
"os"
"strings"
"sync"
Expand Down Expand Up @@ -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 == "" {
Expand All @@ -46,7 +59,7 @@ func loadENV() {
continue
}

pair := strings.Split(line, "=")
pair := strings.SplitN(line, "=", 2)
if len(pair) != 2 {
continue
}
Expand All @@ -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
}
54 changes: 54 additions & 0 deletions envor/envor_test.go
Original file line number Diff line number Diff line change
@@ -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"])
}
})

}

0 comments on commit 204724e

Please sign in to comment.