Skip to content

Commit

Permalink
Merge pull request bkeepers#181 from sorah/expand-vars-correctly
Browse files Browse the repository at this point in the history
Expand variables correctly
  • Loading branch information
bkeepers committed Apr 3, 2015
2 parents b583145 + aed02ac commit 3023cae
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 18 deletions.
31 changes: 13 additions & 18 deletions lib/dotenv/substitutions/variable.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require "English"

module Dotenv
module Substitutions
# Substitute variables in a value.
Expand All @@ -8,30 +10,23 @@ 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 |variable|
match = $LAST_MATCH_INFO

if match[1] == '\\'
variable[1..-1]
else
# Replace it with the value from the environment
replace = env.fetch(parts.last) { ENV[parts.last] }
env.fetch(match[3]) { ENV[match[3]] }
end

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

value
end
end
end
Expand Down
2 changes: 2 additions & 0 deletions spec/dotenv/parser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ 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 3023cae

Please sign in to comment.