Skip to content

Commit

Permalink
Merge pull request #502 from maxjacobson/mj/template-multi-line-varia…
Browse files Browse the repository at this point in the history
…bles

Fix template (-t) handling of multi-line variables
  • Loading branch information
bkeepers committed Apr 30, 2024
2 parents c9ecfa4 + 1982e3c commit e43d34a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
30 changes: 24 additions & 6 deletions lib/dotenv/template.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,35 @@ def create_template
File.open(@env_file, "r") do |env_file|
File.open("#{@env_file}.template", "w") do |env_template|
env_file.each do |line|
env_template.puts template_line(line)
if is_comment?(line)
env_template.puts line
elsif (var = var_defined?(line))
if line.match(EXPORT_COMMAND)
env_template.puts "export #{var}=#{var}"
else
env_template.puts "#{var}=#{var}"
end
elsif line_blank?(line)
env_template.puts
end
end
end
end
end

def template_line(line)
var, value = line.split("=")
template = var.gsub(EXPORT_COMMAND, "")
is_a_comment = var.strip[0].eql?("#")
(value.nil? || is_a_comment) ? line : "#{var}=#{template}"
private

def is_comment?(line)
line.strip.start_with?("#")
end

def var_defined?(line)
match = Dotenv::Parser::LINE.match(line)
match && match[1]
end

def line_blank?(line)
line.strip.length.zero?
end
end
end
14 changes: 14 additions & 0 deletions spec/dotenv/cli_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,20 @@ def run(*args)
expect(@buffer.string).to eq("export FOO=FOO\nexport FOO2=FOO2\n")
end

it "templates multi-line variables" do
@input = StringIO.new(<<~TEXT)
FOO=BAR
FOO2="BAR2
BAR2"
TEXT
allow(File).to receive(:open).with(@origin_filename, "r").and_yield(@input)
allow(File).to receive(:open).with(@template_filename, "w").and_yield(@buffer)
# call the function that writes to the file
Dotenv::CLI.new(["-t", @origin_filename])
# reading the buffer and checking its content.
expect(@buffer.string).to eq("FOO=FOO\nFOO2=FOO2\n")
end

it "ignores blank lines" do
@input = StringIO.new("\nFOO=BAR\nFOO2=BAR2")
allow(File).to receive(:open).with(@origin_filename, "r").and_yield(@input)
Expand Down

0 comments on commit e43d34a

Please sign in to comment.