Skip to content

Commit

Permalink
Support comments in .env file (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
clovisphere authored May 6, 2024
1 parent 617e7a3 commit c2c7c06
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ import (
"time"
)

const (
charComment = '#'
// TODO: handle `prefix`, i.e. single and double quote
)

// GetStringOrDefault value.
func GetStringOrDefault(name, defaultV string) string {
v, ok := os.LookupEnv(name)
Expand Down Expand Up @@ -73,6 +78,9 @@ func Load(paths ...string) error {
for s.Scan() {
i++
line := s.Text()
if line[0] == charComment {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) < 2 {
return fmt.Errorf("missing equal sign on line %v in %v", i, path)
Expand Down
9 changes: 9 additions & 0 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,15 @@ func TestLoad(t *testing.T) {
is.Equal("missing equal sign on line 1 in testdata/invalid", err.Error())
})

t.Run("ignore comments in environment file", func(t *testing.T) {
is := is.New(t)
defer unsetenv("hat", "hats", "equals")
err := env.Load("testdata/with_comment")
is.NoErr(err)
equals := env.GetStringOrDefault("equals", "")
is.Equal("somethingwithequalsafter=", equals)
})

t.Run("gets the string value including equal signs", func(t *testing.T) {
is := is.New(t)
defer unsetenv("hat", "hats", "equals")
Expand Down
5 changes: 5 additions & 0 deletions testdata/with_comment
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# this a comment, and it should be ignored!!!!
hat=party
hats=2
equals=somethingwithequalsafter=
# this another comment and should be ignored!!!

0 comments on commit c2c7c06

Please sign in to comment.