Skip to content

Commit

Permalink
Expand variables correctly
Browse files Browse the repository at this point in the history
Previously this fails:

    Variable.call("${FOO} \\${FOO} ${FOO}", "FOO" => "BAR")
    #=> "BAR BAR ${FOO}"
  • Loading branch information
sorah committed Apr 2, 2015
1 parent 79beb32 commit ae52cf8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 18 deletions.
27 changes: 9 additions & 18 deletions lib/dotenv/substitutions/variable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,21 @@ module Substitutions
module Variable
class << self
VARIABLE = /
(\\)? # is it escaped with a backslash?
(\$) # literal $
( # collect braces with var for sub
\{? # allow brace wrapping
([A-Z0-9_]+) # match the variable
\}? # closing brace
)
(\\)? # is it escaped with a backslash?
(\$) # literal $
\{? # allow brace wrapping
([A-Z0-9_]+) # match the variable
\}? # closing brace
/xi

def call(value, env)
# Process embedded variables
value.scan(VARIABLE).each do |parts|
if parts.first == '\\'
# Variable is escaped, don't replace it.
replace = parts[1...-1].join("")
value.gsub(VARIABLE) do |value|
if $1 == '\\'
value[1..-1]
else
# Replace it with the value from the environment
replace = env.fetch(parts.last) { ENV[parts.last] }
env.fetch($3) { ENV[$3] }
end

value = value.sub(parts[0...-1].join(""), replace || "")
end

value
end
end
end
Expand Down
1 change: 1 addition & 0 deletions spec/dotenv/parser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ def env(string)
it "does not expand escaped variables" do
expect(env('FOO="foo\$BAR"')).to eql("FOO" => "foo$BAR")
expect(env('FOO="foo\${BAR}"')).to eql("FOO" => "foo${BAR}")
expect(env("FOO=test\nBAR=\"foo\\${FOO} ${FOO}\"")).to eql("FOO" => "test", "BAR" => "foo${FOO} test")
end

it "parses yaml style options" do
Expand Down

0 comments on commit ae52cf8

Please sign in to comment.