From dc72197df73cc157874d606e7eeec25596f060a3 Mon Sep 17 00:00:00 2001 From: Johannes Gehrs Date: Thu, 7 Nov 2024 16:34:13 +0100 Subject: [PATCH] Read should behave as Load does According to the docs Read() should have the "same file loading semantics as Load". But currently it overrides. This commit fixes it. --- fixtures/read_overrides.env | 1 + godotenv.go | 4 +++- godotenv_test.go | 32 ++++++++++++++++++++++++-------- 3 files changed, 28 insertions(+), 9 deletions(-) create mode 100644 fixtures/read_overrides.env diff --git a/fixtures/read_overrides.env b/fixtures/read_overrides.env new file mode 100644 index 0000000..f554e77 --- /dev/null +++ b/fixtures/read_overrides.env @@ -0,0 +1 @@ +OPTION_A=99 diff --git a/godotenv.go b/godotenv.go index 61b0ebb..b81e66c 100644 --- a/godotenv.go +++ b/godotenv.go @@ -98,7 +98,9 @@ func Read(filenames ...string) (envMap map[string]string, err error) { } for key, value := range individualEnvMap { - envMap[key] = value + if _, ok := envMap[key]; !ok { + envMap[key] = value + } } } diff --git a/godotenv_test.go b/godotenv_test.go index c6b5725..6a6c18c 100644 --- a/godotenv_test.go +++ b/godotenv_test.go @@ -134,7 +134,23 @@ func TestLoadDoesNotOverride(t *testing.T) { "OPTION_A": "do_not_override", "OPTION_B": "", } + loadEnvAndCompareValues(t, Load, envFileName, expectedValues, presets) + +} + +func TestReadDoesNotOverride(t *testing.T) { + envFileName := "fixtures/plain.env" + overrideEnvName := "fixtures/read_overrides.env" + + envMap, err := Read(envFileName, overrideEnvName) + if err != nil { + t.Error("Error reading file") + } + + if envMap["OPTION_A"] != "1" { + t.Error("Read falsely overrode OPTION_A") + } } func TestOverloadDoesOverride(t *testing.T) { @@ -588,42 +604,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", }, }