From d5872c83b427e14c380da87324cabbdc219459b7 Mon Sep 17 00:00:00 2001 From: Brandon Keepers Date: Fri, 13 Dec 2024 07:55:06 -0500 Subject: [PATCH] Restore previous parser behavior of returning existing variables Part of the optimization in #515 was to skip parsing variables that were already defined. But that had the side-effect of not returning them in the resulting hash. This adds a test for this behavior and restores it. --- lib/dotenv/parser.rb | 14 +++++++------- spec/dotenv/parser_spec.rb | 9 +++++++-- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/lib/dotenv/parser.rb b/lib/dotenv/parser.rb index 402074b3..3ed50f52 100644 --- a/lib/dotenv/parser.rb +++ b/lib/dotenv/parser.rb @@ -52,11 +52,11 @@ def call @string.scan(LINE) do match = $LAST_MATCH_INFO - # Skip parsing values that will be ignored - next if ignore?(match[:key]) - - # Check for exported variable with no value - if match[:export] && !match[:value] + if existing?(match[:key]) + # Use value from already defined variable + @hash[match[:key]] = ENV[match[:key]] + elsif match[:export] && !match[:value] + # Check for exported variable with no value if !@hash.member?(match[:key]) raise FormatError, "Line #{match.to_s.inspect} has an unset variable" end @@ -70,8 +70,8 @@ def call private - # Determine if the key can be ignored. - def ignore?(key) + # Determine if a variable is already defined and should not be overwritten. + def existing?(key) !@overwrite && key != "DOTENV_LINEBREAK_MODE" && ENV.key?(key) end diff --git a/spec/dotenv/parser_spec.rb b/spec/dotenv/parser_spec.rb index 64cff97f..70b191b1 100644 --- a/spec/dotenv/parser_spec.rb +++ b/spec/dotenv/parser_spec.rb @@ -1,8 +1,8 @@ require "spec_helper" describe Dotenv::Parser do - def env(string) - Dotenv::Parser.call(string) + def env(...) + Dotenv::Parser.call(...) end it "parses unquoted values" do @@ -298,4 +298,9 @@ def env(string) end end end + + it "returns existing value for redefined variable" do + ENV["FOO"] = "existing" + expect(env("FOO=bar")).to eql("FOO" => "existing") + end end