From b3f1029832bbdcf032ea6a67197e8032f4610d30 Mon Sep 17 00:00:00 2001 From: uccs <1500846601@qq.com> Date: Sun, 15 Dec 2024 16:06:41 +0800 Subject: [PATCH] fix: if a line contains multiple # characters, there will be issues when traversing from back to front --- fixtures/comments.env | 2 ++ godotenv_test.go | 24 +++++++++++++----------- parser.go | 6 +++--- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/fixtures/comments.env b/fixtures/comments.env index af9781f..65e9fb4 100644 --- a/fixtures/comments.env +++ b/fixtures/comments.env @@ -1,4 +1,6 @@ # Full line comment +qux=thud # fred # other +thud=fred#qux # other foo=bar # baz bar=foo#baz baz="foo"#bar diff --git a/godotenv_test.go b/godotenv_test.go index c6b5725..6d9b6e0 100644 --- a/godotenv_test.go +++ b/godotenv_test.go @@ -477,9 +477,11 @@ func TestErrorParsing(t *testing.T) { func TestComments(t *testing.T) { envFileName := "fixtures/comments.env" expectedValues := map[string]string{ - "foo": "bar", - "bar": "foo#baz", - "baz": "foo", + "qux": "thud", + "thud": "fred#qux", + "foo": "bar", + "bar": "foo#baz", + "baz": "foo", } loadEnvAndCompareValues(t, Load, envFileName, expectedValues, noopPresets) @@ -588,42 +590,42 @@ func TestWhitespace(t *testing.T) { }{ "Leading whitespace": { input: " A=a\n", - key: "A", + key: "A", value: "a", }, "Leading tab": { input: "\tA=a\n", - key: "A", + key: "A", value: "a", }, "Leading mixed whitespace": { input: " \t \t\n\t \t A=a\n", - key: "A", + key: "A", value: "a", }, "Leading whitespace before export": { input: " \t\t export A=a\n", - key: "A", + key: "A", value: "a", }, "Trailing whitespace": { input: "A=a \t \t\n", - key: "A", + key: "A", value: "a", }, "Trailing whitespace with export": { input: "export A=a\t \t \n", - key: "A", + key: "A", value: "a", }, "No EOL": { input: "A=a", - key: "A", + key: "A", value: "a", }, "Trailing whitespace with no EOL": { input: "A=a ", - key: "A", + key: "A", value: "a", }, } diff --git a/parser.go b/parser.go index 098f05d..54c7057 100644 --- a/parser.go +++ b/parser.go @@ -143,9 +143,9 @@ func extractVarValue(src []byte, vars map[string]string) (value string, rest []b } // Work backwards to check if the line ends in whitespace then - // a comment (ie asdasd # some comment) - for i := endOfVar - 1; i >= 0; i-- { - if line[i] == charComment && i > 0 { + // a comment (ie asdasd # some comment # other) + for i := 0; i < endOfVar; i++ { + if line[i] == charComment && i < endOfVar { if isSpace(line[i-1]) { endOfVar = i break