Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support comments in .env file #5

Merged
merged 3 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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!!!
Loading