Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix template (-t) handling of multi-line variables #502

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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