Skip to content

Commit

Permalink
Add Load function to the facade
Browse files Browse the repository at this point in the history
Signed-off-by: Ulysses Souza <[email protected]>
  • Loading branch information
ulyssessouza committed Apr 16, 2024
1 parent b26bfe6 commit 07e1132
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
26 changes: 26 additions & 0 deletions envlang.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ package envlang

import (
"io"
"os"

"github.com/antlr4-go/antlr/v4"
"github.com/ulyssessouza/envlang/dao"
"github.com/ulyssessouza/envlang/gen/fileparser"
"github.com/ulyssessouza/envlang/handlers"
)

const defaultEnvFile = ".env"

func GetVariablesFromInputStream(d dao.EnvLangDao, r io.Reader) map[string]*string {
return getVariablesFromInputStream(d, antlr.NewIoStream(r))
}
Expand All @@ -17,6 +20,29 @@ func GetVariables(d dao.EnvLangDao, s string) map[string]*string {
return getVariablesFromInputStream(d, antlr.NewInputStream(s))
}

func Load(paths ...string) error {
if len(paths) == 0 {
paths = []string{defaultEnvFile}
}

for _, p := range paths {
f, err := os.Open(p)
if err != nil {
return err
}
m := GetVariablesFromInputStream(dao.NewDefaultDaoFromEnv(os.Environ()), f)
for k, v := range m {
if v == nil {
str := ""
v = &str
}
os.Setenv(k, *v)
}
}

return nil
}

func getVariablesFromInputStream(d dao.EnvLangDao, ais *antlr.InputStream) map[string]*string {
lexer := fileparser.NewEnvLangFileLexer(ais)
stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
Expand Down
10 changes: 10 additions & 0 deletions envlang_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package envlang

import (
"os"
"strings"
"testing"

Expand All @@ -22,6 +23,15 @@ func TestGetFromReader(t *testing.T) {
assert.DeepEqual(t, expected, GetVariablesFromInputStream(d, strings.NewReader(`A=aaa`)))
}

func TestLoad(t *testing.T) {
const envlangOsLoadVariable = "ENVLANG_TEST_OSLOAD_VARIABLE"
err := Load("./fixtures/load.env")
assert.NilError(t, err)
osLoaded, ok := os.LookupEnv(envlangOsLoadVariable)
assert.Assert(t, ok)
assert.Equal(t, osLoaded, "ENVLANG_TEST_OSLOAD_VALUE")
}

//nolint:funlen
func TestGetValue(t *testing.T) {
tests := []struct {
Expand Down
1 change: 1 addition & 0 deletions fixtures/load.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ENVLANG_TEST_OSLOAD_VARIABLE=ENVLANG_TEST_OSLOAD_VALUE

0 comments on commit 07e1132

Please sign in to comment.