dotenv 0.10.0 → 2.8.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA1:
3
- metadata.gz: bd2cbf743caa9a52aa0be269a6d85623a429e63f
4
- data.tar.gz: 8dbb6133dbb68670820f783469d680052b7ad6b9
2
+ SHA256:
3
+ metadata.gz: 53a782f20ccb8d0ed6e70eb3f6e626313a96460297e75dfc02356da40bea9ef1
4
+ data.tar.gz: 7dee9ae1c761ad5f069883443f8ccb0c3e8540187e432fc184783c88f1844ac6
5
5
  SHA512:
6
- metadata.gz: e214586a73a311cf7544a1e2141f2653fba3bcead5a43b5dadd865732a16d9aaed54c0f063f5bade068971191c915fe8917d8da7bcf16eaaf8c8b843642e404c
7
- data.tar.gz: 4b689ee34f098e79858a84ec03944d1a365905e9d896ccabbe41bb4181b6272466d97dded85ff58b4ddbdc86412090170ac853a6529ead2088a03ae4fa1e9ab0
6
+ metadata.gz: 0425caeb0f6321954bc8731438793f3d24306b72e0bf17c7de14e45c093bd2af892899d9b91780e0b688371e5db03a819eead8fe2475a7550fb1fc4762989e23
7
+ data.tar.gz: 52414dd28acab5d41879dc1740c08f8fe4265c66476dd04e1580291104701c0c5b5dcda87575d9aa4433f92587efcee87bf3aa7bb32eab35685b2fa2dd580855
data/README.md CHANGED
@@ -1,10 +1,10 @@
1
- # dotenv [![Build Status](https://secure.travis-ci.org/bkeepers/dotenv.png?branch=master)](https://travis-ci.org/bkeepers/dotenv)
1
+ # dotenv [![Gem Version](https://badge.fury.io/rb/dotenv.svg)](https://badge.fury.io/rb/dotenv) [![Join the chat at https://gitter.im/bkeepers/dotenv](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/bkeepers/dotenv?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
2
2
 
3
- Dotenv loads environment variables from `.env` into `ENV`.
3
+ Shim to load environment variables from `.env` into `ENV` in *development*.
4
4
 
5
- Storing [configuration in the environment](http://www.12factor.net/config) is one of the tenets of a [twelve-factor app](http://www.12factor.net/). Anything that is likely to change between deployment environments–such as resource handles for databases or credentials for external services–should be extracted from the code into environment variables.
5
+ Storing [configuration in the environment](http://12factor.net/config) is one of the tenets of a [twelve-factor app](http://12factor.net). Anything that is likely to change between deployment environments–such as resource handles for databases or credentials for external services–should be extracted from the code into environment variables.
6
6
 
7
- But it is not always practical to set environment variables on development machines or continuous integration servers where multiple projects are run. Dotenv load variables from a `.env` file into `ENV` when the environment is bootstrapped.
7
+ But it is not always practical to set environment variables on development machines or continuous integration servers where multiple projects are run. dotenv loads variables from a `.env` file into `ENV` when the environment is bootstrapped.
8
8
 
9
9
  ## Installation
10
10
 
@@ -13,7 +13,7 @@ But it is not always practical to set environment variables on development machi
13
13
  Add this line to the top of your application's Gemfile:
14
14
 
15
15
  ```ruby
16
- gem 'dotenv-rails', :groups => [:development, :test]
16
+ gem 'dotenv-rails', groups: [:development, :test]
17
17
  ```
18
18
 
19
19
  And then execute:
@@ -22,7 +22,28 @@ And then execute:
22
22
  $ bundle
23
23
  ```
24
24
 
25
- It should be listed in the Gemfile before any other gems that use environment variables, otherwise those gems will get initialized with the wrong values.
25
+ #### Note on load order
26
+
27
+ dotenv is initialized in your Rails app during the `before_configuration` callback, which is fired when the `Application` constant is defined in `config/application.rb` with `class Application < Rails::Application`. If you need it to be initialized sooner, you can manually call `Dotenv::Railtie.load`.
28
+
29
+ ```ruby
30
+ # config/application.rb
31
+ Bundler.require(*Rails.groups)
32
+
33
+ # Load dotenv only in development or test environment
34
+ if ['development', 'test'].include? ENV['RAILS_ENV']
35
+ Dotenv::Railtie.load
36
+ end
37
+
38
+ HOSTNAME = ENV['HOSTNAME']
39
+ ```
40
+
41
+ If you use gems that require environment variables to be set before they are loaded, then list `dotenv-rails` in the `Gemfile` before those other gems and require `dotenv/rails-now`.
42
+
43
+ ```ruby
44
+ gem 'dotenv-rails', require: 'dotenv/rails-now'
45
+ gem 'gem-that-requires-env-variables'
46
+ ```
26
47
 
27
48
  ### Sinatra or Plain ol' Ruby
28
49
 
@@ -35,14 +56,30 @@ $ gem install dotenv
35
56
  As early as possible in your application bootstrap process, load `.env`:
36
57
 
37
58
  ```ruby
59
+ require 'dotenv/load'
60
+
61
+ # or
38
62
  require 'dotenv'
39
63
  Dotenv.load
40
64
  ```
41
65
 
66
+ By default, `load` will look for a file called `.env` in the current working directory. Pass in multiple files and they will be loaded in order. The first value set for a variable will win.
67
+
68
+ ```ruby
69
+ require 'dotenv'
70
+ Dotenv.load('file1.env', 'file2.env')
71
+ ```
72
+
42
73
  Alternatively, you can use the `dotenv` executable to launch your application:
43
74
 
44
75
  ```shell
45
- $ dotenv ./script.py
76
+ $ dotenv ./script.rb
77
+ ```
78
+
79
+ The `dotenv` executable also accepts a single flag, `-f`. Its value should be a comma-separated list of configuration files, in the order of most important to least. All of the files must exist. There _must_ be a space between the flag and its value.
80
+
81
+ ```
82
+ $ dotenv -f ".env.local,.env" ./script.rb
46
83
  ```
47
84
 
48
85
  To ensure `.env` is loaded in rake, load the tasks:
@@ -50,7 +87,7 @@ To ensure `.env` is loaded in rake, load the tasks:
50
87
  ```ruby
51
88
  require 'dotenv/tasks'
52
89
 
53
- task :mytask => :dotenv do
90
+ task mytask: :dotenv do
54
91
  # things that require .env
55
92
  end
56
93
  ```
@@ -64,55 +101,164 @@ S3_BUCKET=YOURS3BUCKET
64
101
  SECRET_KEY=YOURSECRETKEYGOESHERE
65
102
  ```
66
103
 
67
- You can also create files per environment, such as `.env.test`.
104
+ Whenever your application loads, these variables will be available in `ENV`:
105
+
106
+ ```ruby
107
+ config.fog_directory = ENV['S3_BUCKET']
108
+ ```
109
+
110
+ You may also add `export` in front of each line so you can `source` the file in bash:
68
111
 
69
112
  ```shell
70
- S3_BUCKET=tests3bucket
71
- SECRET_KEY=testsecretkey
113
+ export S3_BUCKET=YOURS3BUCKET
114
+ export SECRET_KEY=YOURSECRETKEYGOESHERE
72
115
  ```
73
116
 
74
- An alternate yaml-like syntax is supported:
117
+ ### Multi-line values
118
+
119
+ If you need multiline variables, for example private keys, you can double quote strings and use the `\n` character for newlines:
75
120
 
76
- ```yaml
77
- S3_BUCKET: yamlstyleforyours3bucket
78
- SECRET_KEY: thisisalsoanokaysecret
121
+ ```shell
122
+ PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nHkVN9...\n-----END DSA PRIVATE KEY-----\n"
79
123
  ```
80
124
 
81
- Whenever your application loads, these variables will be available in `ENV`:
125
+ Alternatively, multi-line values with line breaks are now supported for quoted values.
82
126
 
83
- ```ruby
84
- config.fog_directory = ENV['S3_BUCKET']
127
+ ```shell
128
+ PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
129
+ ...
130
+ HkVN9...
131
+ ...
132
+ -----END DSA PRIVATE KEY-----"
85
133
  ```
86
134
 
87
- ## Capistrano integration
135
+ This is particularly helpful when using the Heroku command line plugin [`heroku-config`](https://github.com/xavdid/heroku-config) to pull configuration variables down that may have line breaks.
88
136
 
89
- If you want to use Dotenv with Capistrano in your production environment, make sure the dotenv gem is included in your Gemfile `:production` group.
137
+ ### Command Substitution
90
138
 
91
- ### Capistrano version 2.x.x
139
+ You need to add the output of a command in one of your variables? Simply add it with `$(your_command)`:
92
140
 
93
- Add the gem to your `config/deploy.rb` file:
141
+ ```shell
142
+ DATABASE_URL="postgres://$(whoami)@localhost/my_database"
143
+ ```
94
144
 
95
- ```ruby
96
- require "dotenv/capistrano"
145
+ ### Variable Substitution
146
+
147
+ You need to add the value of another variable in one of your variables? You can reference the variable with `${VAR}` or often just `$VAR` in unqoted or double-quoted values.
148
+
149
+ ```shell
150
+ DATABASE_URL="postgres://${USER}@localhost/my_database"
97
151
  ```
98
152
 
99
- It will symlink the `.env` located in `/path/to/shared` in the new release.
153
+ If a value contains a `$` and it is not intended to be a variable, wrap it in single quotes.
100
154
 
155
+ ```shell
156
+ PASSWORD='pas$word'
157
+ ```
101
158
 
102
- ### Capistrano version 3.x.x
159
+ ### Comments
103
160
 
104
- Just add `.env` to the list of linked files, for example:
161
+ Comments may be added to your file as such:
162
+
163
+ ```shell
164
+ # This is a comment
165
+ SECRET_KEY=YOURSECRETKEYGOESHERE # comment
166
+ SECRET_HASH="something-with-a-#-hash"
167
+ ```
168
+
169
+ ### Required Keys
170
+
171
+ If a particular configuration value is required but not set, it's appropriate to raise an error.
172
+
173
+ To require configuration keys:
174
+
175
+ ```ruby
176
+ # config/initializers/dotenv.rb
177
+
178
+ Dotenv.require_keys("SERVICE_APP_ID", "SERVICE_KEY", "SERVICE_SECRET")
179
+ ```
180
+
181
+ If any of the configuration keys above are not set, your application will raise an error during initialization. This method is preferred because it prevents runtime errors in a production application due to improper configuration.
182
+
183
+ ### Parsing
184
+
185
+ To parse a list of env files for programmatic inspection without modifying the ENV:
105
186
 
106
187
  ```ruby
107
- set :linked_files, %w{config/database.yml .env}
188
+ Dotenv.parse(".env.local", ".env")
189
+ # => {'S3_BUCKET' => 'YOURS3BUCKET', 'SECRET_KEY' => 'YOURSECRETKEYGOESHERE', ...}
190
+ ```
191
+
192
+ This method returns a hash of the ENV var name/value pairs.
193
+
194
+ ## Frequently Answered Questions
195
+
196
+ ### Can I use dotenv in production?
197
+
198
+ dotenv was originally created to load configuration variables into `ENV` in *development*. There are typically better ways to manage configuration in production environments - such as `/etc/environment` managed by [Puppet](https://github.com/puppetlabs/puppet) or [Chef](https://github.com/chef/chef), `heroku config`, etc.
199
+
200
+ However, some find dotenv to be a convenient way to configure Rails applications in staging and production environments, and you can do that by defining environment-specific files like `.env.production` or `.env.test`.
201
+
202
+ If you use this gem to handle env vars for multiple Rails environments (development, test, production, etc.), please note that env vars that are general to all environments should be stored in `.env`. Then, environment specific env vars should be stored in `.env.<that environment's name>`.
203
+
204
+ ### What other .env* files can I use?
205
+
206
+ `dotenv-rails` will override in the following order (highest defined variable overrides lower):
207
+
208
+ | Hierarchy Priority | Filename | Environment | Should I `.gitignore`it? | Notes |
209
+ | ------------------ | ------------------------ | -------------------- | --------------------------------------------------- | ------------------------------------------------------------ |
210
+ | 1st (highest) | `.env.development.local` | Development | Yes! | Local overrides of environment-specific settings. |
211
+ | 1st | `.env.test.local` | Test | Yes! | Local overrides of environment-specific settings. |
212
+ | 1st | `.env.production.local` | Production | Yes! | Local overrides of environment-specific settings. |
213
+ | 2nd | `.env.local` | Wherever the file is | Definitely. | Local overrides. This file is loaded for all environments _except_ `test`. |
214
+ | 3rd | `.env.development` | Development | No. | Shared environment-specific settings |
215
+ | 3rd | `.env.test` | Test | No. | Shared environment-specific settings |
216
+ | 3rd | `.env.production` | Production | No. | Shared environment-specific settings |
217
+ | Last | `.env` | All Environments | Depends (See [below](#should-i-commit-my-env-file)) | The Original® |
218
+
219
+
220
+ ### Should I commit my .env file?
221
+
222
+ Credentials should only be accessible on the machines that need access to them. Never commit sensitive information to a repository that is not needed by every development machine and server.
223
+
224
+
225
+ You can use the `-t` or `--template` flag on the dotenv cli to create a template of your `.env` file.
226
+ ```shell
227
+ $ dotenv -t .env
108
228
  ```
229
+ A template will be created in your working directory named `{FINAME}.template`. So in the above example, it would create a `.env.template` file.
109
230
 
110
- ## Should I commit my .env file?
231
+ The template will contain all the environment variables in your `.env` file but with their values set to the variable names.
232
+
233
+ ```shell
234
+ # .env
235
+ S3_BUCKET=YOURS3BUCKET
236
+ SECRET_KEY=YOURSECRETKEYGOESHERE
237
+ ```
111
238
 
112
- It is recommended that you store development-only settings in your `.env` file, and commit it to your repository. Make sure that all your credentials for your development environment are different from your other deployments. This makes it easy for other developers to get started on your project, without compromising your credentials for other environments.
239
+ Would become
240
+
241
+ ```shell
242
+ # .env.template
243
+ S3_BUCKET=S3_BUCKET
244
+ SECRET_KEY=SECRET_KEY
245
+ ```
246
+
247
+ Personally, I prefer to commit the `.env` file with development-only settings. This makes it easy for other developers to get started on the project without compromising credentials for other environments. If you follow this advice, make sure that all the credentials for your development environment are different from your other deployments and that the development credentials do not have access to any confidential data.
248
+
249
+ ### Why is it not overriding existing `ENV` variables?
250
+
251
+ By default, it **won't** overwrite existing environment variables as dotenv assumes the deployment environment has more knowledge about configuration than the application does. To overwrite existing environment variables you can use `Dotenv.overload`.
252
+
253
+ You can also use the `-o` or `--overload` flag on the dotenv cli to override existing `ENV` variables.
254
+ ```shell
255
+ $ dotenv -o -f ".env.local,.env"
256
+ ```
113
257
 
114
258
  ## Contributing
115
259
 
260
+ If you want a better idea of how dotenv works, check out the [Ruby Rogues Code Reading of dotenv](https://www.youtube.com/watch?v=lKmY_0uY86s).
261
+
116
262
  1. Fork it
117
263
  2. Create your feature branch (`git checkout -b my-new-feature`)
118
264
  3. Commit your changes (`git commit -am 'Added some feature'`)
data/bin/dotenv CHANGED
@@ -1,11 +1,4 @@
1
1
  #!/usr/bin/env ruby
2
2
 
3
- require 'dotenv'
4
-
5
- begin
6
- Dotenv.load!
7
- rescue Errno::ENOENT => e
8
- abort e.message
9
- else
10
- exec *ARGV unless ARGV.empty?
11
- end
3
+ require "dotenv/cli"
4
+ Dotenv::CLI.new(ARGV).run
data/lib/dotenv/cli.rb ADDED
@@ -0,0 +1,57 @@
1
+ require "dotenv"
2
+ require "dotenv/version"
3
+ require "dotenv/template"
4
+ require "optparse"
5
+
6
+ module Dotenv
7
+ # The command line interface
8
+ class CLI < OptionParser
9
+ attr_reader :argv, :filenames, :overload
10
+
11
+ def initialize(argv = [])
12
+ @argv = argv.dup
13
+ @filenames = []
14
+ @overload = false
15
+
16
+ super "Usage: dotenv [options]"
17
+ separator ""
18
+
19
+ on("-f FILES", Array, "List of env files to parse") do |list|
20
+ @filenames = list
21
+ end
22
+
23
+ on("-o", "--overload", "override existing ENV variables") do
24
+ @overload = true
25
+ end
26
+
27
+ on("-h", "--help", "Display help") do
28
+ puts self
29
+ exit
30
+ end
31
+
32
+ on("-v", "--version", "Show version") do
33
+ puts "dotenv #{Dotenv::VERSION}"
34
+ exit
35
+ end
36
+
37
+ on("-t", "--template=FILE", "Create a template env file") do |file|
38
+ template = Dotenv::EnvTemplate.new(file)
39
+ template.create_template
40
+ end
41
+
42
+ order!(@argv)
43
+ end
44
+
45
+ def run
46
+ if @overload
47
+ Dotenv.overload!(*@filenames)
48
+ else
49
+ Dotenv.load!(*@filenames)
50
+ end
51
+ rescue Errno::ENOENT => e
52
+ abort e.message
53
+ else
54
+ exec(*@argv) unless @argv.empty?
55
+ end
56
+ end
57
+ end
@@ -1,70 +1,28 @@
1
- require 'dotenv/format_error'
2
- require 'dotenv/substitutions/variable'
3
- if RUBY_VERSION > '1.8.7'
4
- require 'dotenv/substitutions/command'
5
- end
6
-
7
1
  module Dotenv
2
+ # This class inherits from Hash and represents the environment into which
3
+ # Dotenv will load key value pairs from a file.
8
4
  class Environment < Hash
9
- @@substitutions = Substitutions.constants.map { |const| Substitutions.const_get(const) }
5
+ attr_reader :filename
10
6
 
11
- LINE = /
12
- \A
13
- (?:export\s+)? # optional export
14
- ([\w\.]+) # key
15
- (?:\s*=\s*|:\s+?) # separator
16
- ( # optional value begin
17
- '(?:\'|[^'])*' # single quoted value
18
- | # or
19
- "(?:\"|[^"])*" # double quoted value
20
- | # or
21
- [^#\n]+ # unquoted value
22
- )? # value end
23
- (?:\s*\#.*)? # optional comment
24
- \z
25
- /x
26
-
27
- def initialize(filename)
7
+ def initialize(filename, is_load = false)
28
8
  @filename = filename
29
- load
9
+ load(is_load)
30
10
  end
31
11
 
32
- def load
33
- read.each do |line|
34
- if match = line.match(LINE)
35
- key, value = match.captures
36
-
37
- value ||= ''
38
- # Remove surrounding quotes
39
- value = value.strip.sub(/\A(['"])(.*)\1\z/, '\2')
40
-
41
- if $1 == '"'
42
- value = value.gsub('\n', "\n")
43
- # Unescape all characters except $ so variables can be escaped properly
44
- value = value.gsub(/\\([^$])/, '\1')
45
- end
46
-
47
- @@substitutions.each do |proc|
48
- value = proc.call(value, self)
49
- end
50
-
51
- self[key] = value
52
- elsif line !~ /\A\s*(?:#.*)?\z/ # not comment or blank line
53
- raise FormatError, "Line #{line.inspect} doesn't match format"
54
- end
55
- end
12
+ def load(is_load = false)
13
+ update Parser.call(read, is_load)
56
14
  end
57
15
 
58
16
  def read
59
- File.read(@filename).split("\n")
17
+ File.open(@filename, "rb:bom|utf-8", &:read)
60
18
  end
61
19
 
62
20
  def apply
63
- each { |k,v| ENV[k] ||= v }
21
+ each { |k, v| ENV[k] ||= v }
64
22
  end
65
23
 
66
24
  def apply!
67
- each { |k,v| ENV[k] = v }
25
+ each { |k, v| ENV[k] = v }
68
26
  end
69
27
  end
70
28
  end
@@ -0,0 +1,2 @@
1
+ require "dotenv"
2
+ Dotenv.load
@@ -0,0 +1,10 @@
1
+ module Dotenv
2
+ class Error < StandardError; end
3
+
4
+ class MissingKeys < Error # :nodoc:
5
+ def initialize(keys)
6
+ key_word = "key#{keys.size > 1 ? "s" : ""}"
7
+ super("Missing required configuration #{key_word}: #{keys.inspect}")
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,109 @@
1
+ require "dotenv/substitutions/variable"
2
+ require "dotenv/substitutions/command" if RUBY_VERSION > "1.8.7"
3
+
4
+ module Dotenv
5
+ class FormatError < SyntaxError; end
6
+
7
+ # This class enables parsing of a string for key value pairs to be returned
8
+ # and stored in the Environment. It allows for variable substitutions and
9
+ # exporting of variables.
10
+ class Parser
11
+ @substitutions =
12
+ [Dotenv::Substitutions::Variable, Dotenv::Substitutions::Command]
13
+
14
+ LINE = /
15
+ (?:^|\A) # beginning of line
16
+ \s* # leading whitespace
17
+ (?:export\s+)? # optional export
18
+ ([\w.]+) # key
19
+ (?:\s*=\s*?|:\s+?) # separator
20
+ ( # optional value begin
21
+ \s*'(?:\\'|[^'])*' # single quoted value
22
+ | # or
23
+ \s*"(?:\\"|[^"])*" # double quoted value
24
+ | # or
25
+ [^\#\r\n]+ # unquoted value
26
+ )? # value end
27
+ \s* # trailing whitespace
28
+ (?:\#.*)? # optional comment
29
+ (?:$|\z) # end of line
30
+ /x
31
+
32
+ class << self
33
+ attr_reader :substitutions
34
+
35
+ def call(string, is_load = false)
36
+ new(string, is_load).call
37
+ end
38
+ end
39
+
40
+ def initialize(string, is_load = false)
41
+ @string = string
42
+ @hash = {}
43
+ @is_load = is_load
44
+ end
45
+
46
+ def call
47
+ # Convert line breaks to same format
48
+ lines = @string.gsub(/\r\n?/, "\n")
49
+ # Process matches
50
+ lines.scan(LINE).each do |key, value|
51
+ @hash[key] = parse_value(value || "")
52
+ end
53
+ # Process non-matches
54
+ lines.gsub(LINE, "").split(/[\n\r]+/).each do |line|
55
+ parse_line(line)
56
+ end
57
+ @hash
58
+ end
59
+
60
+ private
61
+
62
+ def parse_line(line)
63
+ if line.split.first == "export"
64
+ if variable_not_set?(line)
65
+ raise FormatError, "Line #{line.inspect} has an unset variable"
66
+ end
67
+ end
68
+ end
69
+
70
+ def parse_value(value)
71
+ # Remove surrounding quotes
72
+ value = value.strip.sub(/\A(['"])(.*)\1\z/m, '\2')
73
+ maybe_quote = Regexp.last_match(1)
74
+ value = unescape_value(value, maybe_quote)
75
+ perform_substitutions(value, maybe_quote)
76
+ end
77
+
78
+ def unescape_characters(value)
79
+ value.gsub(/\\([^$])/, '\1')
80
+ end
81
+
82
+ def expand_newlines(value)
83
+ value.gsub('\n', "\n").gsub('\r', "\r")
84
+ end
85
+
86
+ def variable_not_set?(line)
87
+ !line.split[1..].all? { |var| @hash.member?(var) }
88
+ end
89
+
90
+ def unescape_value(value, maybe_quote)
91
+ if maybe_quote == '"'
92
+ unescape_characters(expand_newlines(value))
93
+ elsif maybe_quote.nil?
94
+ unescape_characters(value)
95
+ else
96
+ value
97
+ end
98
+ end
99
+
100
+ def perform_substitutions(value, maybe_quote)
101
+ if maybe_quote != "'"
102
+ self.class.substitutions.each do |proc|
103
+ value = proc.call(value, @hash, @is_load)
104
+ end
105
+ end
106
+ value
107
+ end
108
+ end
109
+ end
@@ -1,32 +1,41 @@
1
+ require "English"
2
+
1
3
  module Dotenv
2
4
  module Substitutions
5
+ # Substitute shell commands in a value.
6
+ #
7
+ # SHA=$(git rev-parse HEAD)
8
+ #
3
9
  module Command
4
10
  class << self
5
-
6
11
  INTERPOLATED_SHELL_COMMAND = /
7
- (?<backslash>\\)?
8
- \$
12
+ (?<backslash>\\)? # is it escaped with a backslash?
13
+ \$ # literal $
9
14
  (?<cmd> # collect command content for eval
10
15
  \( # require opening paren
11
- ([^()]|\g<cmd>)+ # allow any number of non-parens, or balanced parens (by nesting the <cmd> expression recursively)
16
+ (?:[^()]|\g<cmd>)+ # allow any number of non-parens, or balanced
17
+ # parens (by nesting the <cmd> expression
18
+ # recursively)
12
19
  \) # require closing paren
13
20
  )
14
21
  /x
15
22
 
16
- def call(value, env)
23
+ def call(value, _env, _is_load)
17
24
  # Process interpolated shell commands
18
25
  value.gsub(INTERPOLATED_SHELL_COMMAND) do |*|
19
- command = $~[:cmd][1..-2] # Eliminate opening and closing parentheses
26
+ # Eliminate opening and closing parentheses
27
+ command = $LAST_MATCH_INFO[:cmd][1..-2]
20
28
 
21
- if $~[:backslash]
22
- $~[0][1..-1]
29
+ if $LAST_MATCH_INFO[:backslash]
30
+ # Command is escaped, don't replace it.
31
+ $LAST_MATCH_INFO[0][1..]
23
32
  else
33
+ # Execute the command and return the value
24
34
  `#{command}`.chomp
25
35
  end
26
36
  end
27
37
  end
28
38
  end
29
-
30
39
  end
31
40
  end
32
41
  end