Skip to content
This repository was archived by the owner on Jan 12, 2022. It is now read-only.

Commit 5c0e6c6

Browse files
authored
Merge pull request joho#69 from hairyhenderson/ignore-leading-whitespace
Fixing a couple whitespace bugs: ignoring leading whitespace, and supporting more kinds of empty lines
2 parents 823f94b + 61baafa commit 5c0e6c6

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

godotenv.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,13 @@ func parseLine(line string, envMap map[string]string) (key string, value string,
252252
}
253253

254254
// Parse the key
255-
re := regexp.MustCompile(`^\s*(?:export\s+)?(.*?)\s*$`)
255+
key = splitString[0]
256+
if strings.HasPrefix(key, "export") {
257+
key = strings.TrimPrefix(key, "export")
258+
}
259+
key = strings.TrimSpace(key)
260+
261+
re := regexp.MustCompile(`^\s*(?:export\s+)?(.*?)\s*$`)
256262
key = re.ReplaceAllString(splitString[0], "$1")
257263

258264
// Parse the value
@@ -324,7 +330,7 @@ func expandVariables(v string, m map[string]string) string {
324330
}
325331

326332
func isIgnoredLine(line string) bool {
327-
trimmedLine := strings.Trim(line, " \n\t")
333+
trimmedLine := strings.TrimSpace(line)
328334
return len(trimmedLine) == 0 || strings.HasPrefix(trimmedLine, "#")
329335
}
330336

godotenv_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,11 @@ func TestParsing(t *testing.T) {
362362
parseAndCompare(t, `KEY="`, "KEY", "\"")
363363
parseAndCompare(t, `KEY="value`, "KEY", "\"value")
364364

365+
// leading whitespace should be ignored
366+
parseAndCompare(t, " KEY =value", "KEY", "value")
367+
parseAndCompare(t, " KEY=value", "KEY", "value")
368+
parseAndCompare(t, "\tKEY=value", "KEY", "value")
369+
365370
// it 'throws an error if line format is incorrect' do
366371
// expect{env('lol$wut')}.to raise_error(Dotenv::FormatError)
367372
badlyFormattedLine := "lol$wut"
@@ -378,6 +383,10 @@ func TestLinesToIgnore(t *testing.T) {
378383
t.Error("Line with nothing but line break wasn't ignored")
379384
}
380385

386+
if !isIgnoredLine("\r\n") {
387+
t.Error("Line with nothing but windows-style line break wasn't ignored")
388+
}
389+
381390
if !isIgnoredLine("\t\t ") {
382391
t.Error("Line full of whitespace wasn't ignored")
383392
}

0 commit comments

Comments
 (0)