Skip to content

Commit

Permalink
Add DOTENV_LINEBREAK_MODE=legacy to preserve newline expansion
Browse files Browse the repository at this point in the history
  • Loading branch information
bkeepers committed Jan 20, 2024
1 parent c95f516 commit e68028c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
6 changes: 5 additions & 1 deletion lib/dotenv/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,11 @@ def unescape_characters(value)
end

def expand_newlines(value)
value.gsub('\n', "\\\\\\n").gsub('\r', "\r")
if (@hash["DOTENV_LINEBREAK_MODE"] || ENV["DOTENV_LINEBREAK_MODE"]) == "legacy"
value.gsub('\n', "\n").gsub('\r', "\r")
else
value.gsub('\n', "\\\\\\n").gsub('\r', "\\\\\\r")
end
end

def variable_not_set?(line)
Expand Down
23 changes: 20 additions & 3 deletions spec/dotenv/parser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,25 @@ def env(string)
end.to raise_error(Dotenv::FormatError, 'Line "export OH_NO_NOT_SET" has an unset variable')
end

it "expands newlines in quoted strings" do
it 'escapes \n in quoted strings' do
expect(env('FOO="bar\nbaz"')).to eql("FOO" => "bar\\nbaz")
expect(env('FOO="bar\\nbaz"')).to eql("FOO" => "bar\\nbaz")
end

it 'expands \n and \r in quoted strings with DOTENV_LINEBREAK_MODE=legacy in current file' do
ENV["DOTENV_LINEBREAK_MODE"] = "strict"

contents = [
'DOTENV_LINEBREAK_MODE=legacy',
'FOO="bar\nbaz\rfizz"'
].join("\n")
expect(env(contents)).to eql("DOTENV_LINEBREAK_MODE" => "legacy", "FOO" => "bar\nbaz\rfizz")
end

it 'expands \n and \r in quoted strings with DOTENV_LINEBREAK_MODE=legacy in ENV' do
ENV['DOTENV_LINEBREAK_MODE'] = 'legacy'
contents = 'FOO="bar\nbaz\rfizz"'
expect(env(contents)).to eql("FOO" => "bar\nbaz\rfizz")
end

it 'parses variables with "." in the name' do
Expand Down Expand Up @@ -259,8 +276,8 @@ def env(string)
expect(env("FOO=bar\r\nbaz=fbb")).to eql("FOO" => "bar", "baz" => "fbb")
end

it "expands carriage return in quoted strings" do
expect(env('FOO="bar\rbaz"')).to eql("FOO" => "bar\rbaz")
it "escapes carriage return in quoted strings" do
expect(env('FOO="bar\rbaz"')).to eql("FOO" => "bar\\rbaz")
end

it "escape $ properly when no alphabets/numbers/_ are followed by it" do
Expand Down

0 comments on commit e68028c

Please sign in to comment.