dotenv 2.7.6 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f9897791ad9e8b033e9bf66513f4f53bd1afb7fa2d925995bcd4f46c6edff8f7
4
- data.tar.gz: 4bff08bdfbdc9f5709626ab2b46ed098d5c602ccfcb8063457f238dabf459f43
3
+ metadata.gz: d94f968de5def640d49274915a92e82c9dcf9e5783e58fee39fa2b72a9b7ac0d
4
+ data.tar.gz: e892cb84dfbcc7c38bd484f4c747849c52f3050fc170719180c3f79eef63a2ef
5
5
  SHA512:
6
- metadata.gz: 9594d44181f64067dd47b0e4a86a534620aa09278774ad8c86f08bb6d2d35f45d27a724a16207aee9189f508e00f102686c562d85f2feffd45fe506b6451f828
7
- data.tar.gz: 9352577bba48b8f713914b1688f17355fc543b4b004a918889ffc1a83dda939e60597ea49c6ef9f3aad7dfcc48fd837fefa4746dfa783088429ea96ffb7fbaed
6
+ metadata.gz: 5ce6017a1069f68382d9a0a241130243bc807a388788bd17129ce2a135d10cdb1dd607b8fbb69ce469540114d77014a833dbe2ebc416ae77560c5bf40db09e0c
7
+ data.tar.gz: 301e709c9e0d322668a145ee6cf723a532b2805a6112a6479624b6cd61be0e4b60a42234be611bc1901195f99c799598402b846c257f813744ef286bd0326987
data/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # dotenv [![Build Status](https://secure.travis-ci.org/bkeepers/dotenv.svg?branch=master)](https://travis-ci.org/bkeepers/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)
1
+ # dotenv [![Gem Version](https://badge.fury.io/rb/dotenv.svg)](https://badge.fury.io/rb/dotenv)
2
2
 
3
3
  Shim to load environment variables from `.env` into `ENV` in *development*.
4
4
 
@@ -8,49 +8,36 @@ But it is not always practical to set environment variables on development machi
8
8
 
9
9
  ## Installation
10
10
 
11
- ### Rails
12
-
13
- Add this line to the top of your application's Gemfile:
11
+ Add this line to the top of your application's Gemfile and run `bundle install`:
14
12
 
15
13
  ```ruby
16
- gem 'dotenv-rails', groups: [:development, :test]
14
+ gem 'dotenv', groups: [:development, :test]
17
15
  ```
18
16
 
19
- And then execute:
17
+ ## Usage
18
+
19
+ Add your application configuration to your `.env` file in the root of your project:
20
20
 
21
21
  ```shell
22
- $ bundle
22
+ S3_BUCKET=YOURS3BUCKET
23
+ SECRET_KEY=YOURSECRETKEYGOESHERE
23
24
  ```
24
25
 
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`.
26
+ Whenever your application loads, these variables will be available in `ENV`:
28
27
 
29
28
  ```ruby
30
- # config/application.rb
31
- Bundler.require(*Rails.groups)
32
-
33
- Dotenv::Railtie.load
34
-
35
- HOSTNAME = ENV['HOSTNAME']
29
+ config.fog_directory = ENV['S3_BUCKET']
36
30
  ```
37
31
 
38
- 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`.
32
+ See the [API Docs](https://rubydoc.info/github/bkeepers/dotenv/main) for more.
39
33
 
40
- ```ruby
41
- gem 'dotenv-rails', require: 'dotenv/rails-now'
42
- gem 'gem-that-requires-env-variables'
43
- ```
34
+ ### Rails
44
35
 
45
- ### Sinatra or Plain ol' Ruby
36
+ Dotenv will automatically load when your Rails app boots. See [Customizing Rails](#customizing-rails) to change which files are loaded and when.
46
37
 
47
- Install the gem:
38
+ ### Sinatra / Ruby
48
39
 
49
- ```shell
50
- $ gem install dotenv
51
- ```
52
-
53
- As early as possible in your application bootstrap process, load `.env`:
40
+ Load Dotenv as early as possible in your application bootstrap process:
54
41
 
55
42
  ```ruby
56
43
  require 'dotenv/load'
@@ -60,24 +47,27 @@ require 'dotenv'
60
47
  Dotenv.load
61
48
  ```
62
49
 
63
- 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.
50
+ By default, `load` will look for a file called `.env` in the current working directory.
51
+ Pass in multiple files and they will be loaded in order.
52
+ The first value set for a variable will win.
53
+ Existing environment variables will not be overwritten unless you set `overwrite: true`.
64
54
 
65
55
  ```ruby
66
56
  require 'dotenv'
67
57
  Dotenv.load('file1.env', 'file2.env')
68
58
  ```
69
59
 
70
- Alternatively, you can use the `dotenv` executable to launch your application:
60
+ ### Autorestore in tests
71
61
 
72
- ```shell
73
- $ dotenv ./script.rb
74
- ```
62
+ Since 3.0, dotenv in a Rails app will automatically restore `ENV` after each test. This means you can modify `ENV` in your tests without fear of leaking state to other tests. It works with both `ActiveSupport::TestCase` and `Rspec`.
75
63
 
76
- 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.
64
+ To disable this behavior, set `config.dotenv.autorestore = false` in `config/application.rb` or `config/environments/test.rb`. It is disabled by default if your app uses [climate_control](https://github.com/thoughtbot/climate_control) or [ice_age](https://github.com/dpep/ice_age_rb).
77
65
 
78
- ```
79
- $ dotenv -f ".env.local,.env" ./script.rb
80
- ```
66
+ To use this behavior outside of a Rails app, just `require "dotenv/autorestore"` in your test suite.
67
+
68
+ See [`Dotenv.save`](https://rubydoc.info/github/bkeepers/dotenv/main/Dotenv:save), [Dotenv.restore](https://rubydoc.info/github/bkeepers/dotenv/main/Dotenv:restore), and [`Dotenv.modify(hash) { ... }`](https://rubydoc.info/github/bkeepers/dotenv/main/Dotenv:modify) for manual usage.
69
+
70
+ ### Rake
81
71
 
82
72
  To ensure `.env` is loaded in rake, load the tasks:
83
73
 
@@ -85,41 +75,121 @@ To ensure `.env` is loaded in rake, load the tasks:
85
75
  require 'dotenv/tasks'
86
76
 
87
77
  task mytask: :dotenv do
88
- # things that require .env
78
+ # things that require .env
89
79
  end
90
80
  ```
91
81
 
92
- ## Usage
82
+ ### CLI
93
83
 
94
- Add your application configuration to your `.env` file in the root of your project:
84
+ You can use the `dotenv` executable load `.env` before launching your application:
95
85
 
96
- ```shell
97
- S3_BUCKET=YOURS3BUCKET
98
- SECRET_KEY=YOURSECRETKEYGOESHERE
86
+ ```console
87
+ $ dotenv ./script.rb
99
88
  ```
100
89
 
101
- Whenever your application loads, these variables will be available in `ENV`:
90
+ The `dotenv` executable also accepts the flag `-f`. Its value should be a comma-separated list of configuration files, in the order of the most important to the least important. All of the files must exist. There _must_ be a space between the flag and its value.
102
91
 
103
- ```ruby
104
- config.fog_directory = ENV['S3_BUCKET']
92
+ ```console
93
+ $ dotenv -f ".env.local,.env" ./script.rb
105
94
  ```
106
95
 
107
- You may also add `export` in front of each line so you can `source` the file in bash:
96
+ The `dotenv` executable can optionally ignore missing files with the `-i` or `--ignore` flag. For example, if the `.env.local` file does not exist, the following will ignore the missing file and only load the `.env` file.
108
97
 
109
- ```shell
110
- export S3_BUCKET=YOURS3BUCKET
111
- export SECRET_KEY=YOURSECRETKEYGOESHERE
98
+ ```console
99
+ $ dotenv -i -f ".env.local,.env" ./script.rb
112
100
  ```
113
101
 
114
- ### Multi-line values
102
+ ### Load Order
115
103
 
116
- If you need multiline variables, for example private keys, you can double quote strings and use the `\n` character for newlines:
104
+ If you use gems that require environment variables to be set before they are loaded, then list `dotenv` in the `Gemfile` before those other gems and require `dotenv/load`.
117
105
 
118
- ```shell
119
- PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nHkVN9...\n-----END DSA PRIVATE KEY-----\n"
106
+ ```ruby
107
+ gem 'dotenv', require: 'dotenv/load'
108
+ gem 'gem-that-requires-env-variables'
109
+ ```
110
+
111
+ ### Customizing Rails
112
+
113
+ Dotenv will load the following files depending on `RAILS_ENV`, with the first file having the highest precedence, and `.env` having the lowest precedence:
114
+
115
+ <table>
116
+ <thead>
117
+ <tr>
118
+ <th>Priority</th>
119
+ <th colspan="3">Environment</th>
120
+ <th><code>.gitignore</code>it?</th>
121
+ <th>Notes</th>
122
+ </tr>
123
+ <tr>
124
+ <th></th>
125
+ <th>development</th>
126
+ <th>test</th>
127
+ <th>production</th>
128
+ <th></th>
129
+ <th></th>
130
+ </tr>
131
+ </thead>
132
+ <tr>
133
+ <td>highest</td>
134
+ <td><code>.env.development.local</code></td>
135
+ <td><code>.env.test.local</code></td>
136
+ <td><code>.env.production.local</code></td>
137
+ <td>Yes</td>
138
+ <td>Environment-specific local overrides</td>
139
+ </tr>
140
+ <tr>
141
+ <td>2nd</td>
142
+ <td><code>.env.local</code></td>
143
+ <td><strong>N/A</strong></td>
144
+ <td><code>.env.local</code></td>
145
+ <td>Yes</td>
146
+ <td>Local overrides</td>
147
+ </tr>
148
+ <tr>
149
+ <td>3rd</td>
150
+ <td><code>.env.development</code></td>
151
+ <td><code>.env.test</code></td>
152
+ <td><code>.env.production</code></td>
153
+ <td>No</td>
154
+ <td>Shared environment-specific variables</td>
155
+ </tr>
156
+ <tr>
157
+ <td>last</td>
158
+ <td><code>.env</code></td>
159
+ <td><code>.env</code></td>
160
+ <td><code>.env</code></td>
161
+ <td><a href="#should-i-commit-my-env-file">Maybe</a></td>
162
+ <td>Shared for all environments</td>
163
+ </tr>
164
+ </table>
165
+
166
+
167
+ These files are loaded 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, or need to customize the loading process, you can do so at the top of `application.rb`
168
+
169
+ ```ruby
170
+ # config/application.rb
171
+ Bundler.require(*Rails.groups)
172
+
173
+ # Load .env.local in test
174
+ Dotenv::Rails.files.unshift(".env.local") if ENV["RAILS_ENV"] == "test"
175
+
176
+ module YourApp
177
+ class Application < Rails::Application
178
+ # ...
179
+ end
180
+ end
120
181
  ```
121
182
 
122
- Alternatively, multi-line values with line breaks are now supported for quoted values.
183
+ Available options:
184
+
185
+ * `Dotenv::Rails.files` - list of files to be loaded, in order of precedence.
186
+ * `Dotenv::Rails.overwrite` - Overwrite existing `ENV` variables with contents of `.env*` files
187
+ * `Dotenv::Rails.logger` - The logger to use for dotenv's logging. Defaults to `Rails.logger`
188
+ * `Dotenv::Rails.autorestore` - Enable or disable [autorestore](#autorestore-in-tests)
189
+
190
+ ### Multi-line values
191
+
192
+ Multi-line values with line breaks must be surrounded with double quotes.
123
193
 
124
194
  ```shell
125
195
  PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
@@ -129,7 +199,12 @@ HkVN9...
129
199
  -----END DSA PRIVATE KEY-----"
130
200
  ```
131
201
 
132
- 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.
202
+ Prior to 3.0, dotenv would replace `\n` in quoted strings with a newline, but that behavior is deprecated. To use the old behavior, set `DOTENV_LINEBREAK_MODE=legacy` before any variables that include `\n`:
203
+
204
+ ```shell
205
+ DOTENV_LINEBREAK_MODE=legacy
206
+ PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nHkVN9...\n-----END DSA PRIVATE KEY-----\n"
207
+ ```
133
208
 
134
209
  ### Command Substitution
135
210
 
@@ -141,7 +216,7 @@ DATABASE_URL="postgres://$(whoami)@localhost/my_database"
141
216
 
142
217
  ### Variable Substitution
143
218
 
144
- 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.
219
+ 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 unquoted or double-quoted values.
145
220
 
146
221
  ```shell
147
222
  DATABASE_URL="postgres://${USER}@localhost/my_database"
@@ -163,6 +238,15 @@ SECRET_KEY=YOURSECRETKEYGOESHERE # comment
163
238
  SECRET_HASH="something-with-a-#-hash"
164
239
  ```
165
240
 
241
+ ### Exports
242
+
243
+ For compatability, you may also add `export` in front of each line so you can `source` the file in bash:
244
+
245
+ ```shell
246
+ export S3_BUCKET=YOURS3BUCKET
247
+ export SECRET_KEY=YOURSECRETKEYGOESHERE
248
+ ```
249
+
166
250
  ### Required Keys
167
251
 
168
252
  If a particular configuration value is required but not set, it's appropriate to raise an error.
@@ -188,42 +272,14 @@ Dotenv.parse(".env.local", ".env")
188
272
 
189
273
  This method returns a hash of the ENV var name/value pairs.
190
274
 
191
- ## Frequently Answered Questions
192
-
193
- ### Can I use dotenv in production?
194
-
195
- 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.
196
-
197
- 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`.
198
-
199
- 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>`.
200
-
201
- ### What other .env* files can I use?
202
-
203
- `dotenv-rails` will override in the following order (highest defined variable overrides lower):
204
-
205
- | Hierarchy Priority | Filename | Environment | Should I `.gitignore`it? | Notes |
206
- | ------------------ | ------------------------ | -------------------- | --------------------------------------------------- | ------------------------------------------------------------ |
207
- | 1st (highest) | `.env.development.local` | Development | Yes! | Local overrides of environment-specific settings. |
208
- | 1st | `.env.test.local` | Test | Yes! | Local overrides of environment-specific settings. |
209
- | 1st | `.env.production.local` | Production | Yes! | Local overrides of environment-specific settings. |
210
- | 2nd | `.env.local` | Wherever the file is | Definitely. | Local overrides. This file is loaded for all environments _except_ `test`. |
211
- | 3rd | `.env.development` | Development | No. | Shared environment-specific settings |
212
- | 3rd | `.env.test` | Test | No. | Shared environment-specific settings |
213
- | 3rd | `.env.production` | Production | No. | Shared environment-specific settings |
214
- | Last | `.env` | All Environments | Depends (See [below](#should-i-commit-my-env-file)) | The Original® |
215
-
216
-
217
- ### Should I commit my .env file?
218
-
219
- 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.
220
-
275
+ ### Templates
221
276
 
222
277
  You can use the `-t` or `--template` flag on the dotenv cli to create a template of your `.env` file.
223
- ```shell
278
+
279
+ ```console
224
280
  $ dotenv -t .env
225
281
  ```
226
- A template will be created in your working directory named `{FINAME}.template`. So in the above example, it would create a `.env.template` file.
282
+ A template will be created in your working directory named `{FILENAME}.template`. So in the above example, it would create a `.env.template` file.
227
283
 
228
284
  The template will contain all the environment variables in your `.env` file but with their values set to the variable names.
229
285
 
@@ -233,7 +289,7 @@ S3_BUCKET=YOURS3BUCKET
233
289
  SECRET_KEY=YOURSECRETKEYGOESHERE
234
290
  ```
235
291
 
236
- Would become
292
+ Would become
237
293
 
238
294
  ```shell
239
295
  # .env.template
@@ -241,11 +297,34 @@ S3_BUCKET=S3_BUCKET
241
297
  SECRET_KEY=SECRET_KEY
242
298
  ```
243
299
 
300
+ ## Frequently Answered Questions
301
+
302
+ ### Can I use dotenv in production?
303
+
304
+ 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.
305
+
306
+ 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`.
307
+
308
+ 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>`.
309
+
310
+ ### Should I commit my .env file?
311
+
312
+ 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.
313
+
244
314
  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.
245
315
 
246
- ### Why is it not overriding existing `ENV` variables?
316
+ ### Why is it not overwriting existing `ENV` variables?
317
+
318
+ 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.load files, overwrite: true`.
247
319
 
248
- 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`.
320
+ To warn when a value was not overwritten (e.g. to make users aware of this gotcha),
321
+ use `Dotenv.load files, overwrite: :warn`.
322
+
323
+ You can also use the `-o` or `--overwrite` flag on the dotenv cli to overwrite existing `ENV` variables.
324
+
325
+ ```console
326
+ $ dotenv -o -f ".env.local,.env"
327
+ ```
249
328
 
250
329
  ## Contributing
251
330
 
@@ -0,0 +1,29 @@
1
+ # Automatically restore `ENV` to its original state after
2
+
3
+ if defined?(RSpec.configure)
4
+ RSpec.configure do |config|
5
+ # Save ENV before the suite starts
6
+ config.before(:suite) { Dotenv.save }
7
+
8
+ # Restore ENV after each example
9
+ config.after { Dotenv.restore }
10
+ end
11
+ end
12
+
13
+ if defined?(ActiveSupport)
14
+ ActiveSupport.on_load(:active_support_test_case) do
15
+ ActiveSupport::TestCase.class_eval do
16
+ # Save ENV before each test
17
+ setup { Dotenv.save }
18
+
19
+ # Restore ENV after each test
20
+ teardown do
21
+ Dotenv.restore
22
+ rescue ThreadError => e
23
+ # Restore will fail if running tests in parallel.
24
+ warn e.message
25
+ warn "Set `config.dotenv.autorestore = false` in `config/initializers/test.rb`" if defined?(Dotenv::Rails)
26
+ end
27
+ end
28
+ end
29
+ end
data/lib/dotenv/cli.rb CHANGED
@@ -4,77 +4,56 @@ require "dotenv/template"
4
4
  require "optparse"
5
5
 
6
6
  module Dotenv
7
- # The CLI is a class responsible of handling all the command line interface
8
- # logic.
9
- class CLI
10
- attr_reader :argv, :filenames
7
+ # The `dotenv` command line interface. Run `$ dotenv --help` to see usage.
8
+ class CLI < OptionParser
9
+ attr_reader :argv, :filenames, :overwrite
11
10
 
12
11
  def initialize(argv = [])
13
12
  @argv = argv.dup
14
13
  @filenames = []
15
- end
14
+ @ignore = false
15
+ @overwrite = false
16
16
 
17
- def run
18
- parse_argv!(@argv)
17
+ super("Usage: dotenv [options]")
18
+ separator ""
19
19
 
20
- begin
21
- Dotenv.load!(*@filenames)
22
- rescue Errno::ENOENT => e
23
- abort e.message
24
- else
25
- exec(*@argv) unless @argv.empty?
20
+ on("-f FILES", Array, "List of env files to parse") do |list|
21
+ @filenames = list
26
22
  end
27
- end
28
-
29
- private
30
23
 
31
- def parse_argv!(argv)
32
- parser = create_option_parser
33
- add_options(parser)
34
- parser.order!(argv)
35
-
36
- @filenames
37
- end
38
-
39
- def add_options(parser)
40
- add_files_option(parser)
41
- add_help_option(parser)
42
- add_version_option(parser)
43
- add_template_option(parser)
44
- end
24
+ on("-i", "--ignore", "ignore missing env files") do
25
+ @ignore = true
26
+ end
45
27
 
46
- def add_files_option(parser)
47
- parser.on("-f FILES", Array, "List of env files to parse") do |list|
48
- @filenames = list
28
+ on("-o", "--overwrite", "overwrite existing ENV variables") do
29
+ @overwrite = true
49
30
  end
50
- end
31
+ on("--overload") { @overwrite = true }
51
32
 
52
- def add_help_option(parser)
53
- parser.on("-h", "--help", "Display help") do
54
- puts parser
33
+ on("-h", "--help", "Display help") do
34
+ puts self
55
35
  exit
56
36
  end
57
- end
58
37
 
59
- def add_version_option(parser)
60
- parser.on("-v", "--version", "Show version") do
38
+ on("-v", "--version", "Show version") do
61
39
  puts "dotenv #{Dotenv::VERSION}"
62
40
  exit
63
41
  end
64
- end
65
42
 
66
- def add_template_option(parser)
67
- parser.on("-t", "--template=FILE", "Create a template env file") do |file|
43
+ on("-t", "--template=FILE", "Create a template env file") do |file|
68
44
  template = Dotenv::EnvTemplate.new(file)
69
45
  template.create_template
70
46
  end
47
+
48
+ order!(@argv)
71
49
  end
72
50
 
73
- def create_option_parser
74
- OptionParser.new do |parser|
75
- parser.banner = "Usage: dotenv [options]"
76
- parser.separator ""
77
- end
51
+ def run
52
+ Dotenv.load(*@filenames, overwrite: @overwrite, ignore: @ignore)
53
+ rescue Errno::ENOENT => e
54
+ abort e.message
55
+ else
56
+ exec(*@argv) unless @argv.empty?
78
57
  end
79
58
  end
80
59
  end
@@ -0,0 +1,59 @@
1
+ module Dotenv
2
+ # A diff between multiple states of ENV.
3
+ class Diff
4
+ # The initial state
5
+ attr_reader :a
6
+
7
+ # The final or current state
8
+ attr_reader :b
9
+
10
+ # Create a new diff. If given a block, the state of ENV after the block will be preserved as
11
+ # the final state for comparison. Otherwise, the current ENV will be the final state.
12
+ #
13
+ # @param a [Hash] the initial state, defaults to a snapshot of current ENV
14
+ # @param b [Hash] the final state, defaults to the current ENV
15
+ # @yield [diff] a block to execute before recording the final state
16
+ def initialize(a: snapshot, b: ENV, &block)
17
+ @a, @b = a, b
18
+ block&.call self
19
+ ensure
20
+ @b = snapshot if block
21
+ end
22
+
23
+ # Return a Hash of keys added with their new values
24
+ def added
25
+ b.slice(*(b.keys - a.keys))
26
+ end
27
+
28
+ # Returns a Hash of keys removed with their previous values
29
+ def removed
30
+ a.slice(*(a.keys - b.keys))
31
+ end
32
+
33
+ # Returns of Hash of keys changed with an array of their previous and new values
34
+ def changed
35
+ (b.slice(*a.keys).to_a - a.to_a).map do |(k, v)|
36
+ [k, [a[k], v]]
37
+ end.to_h
38
+ end
39
+
40
+ # Returns a Hash of all added, changed, and removed keys and their new values
41
+ def env
42
+ b.slice(*(added.keys + changed.keys)).merge(removed.transform_values { |v| nil })
43
+ end
44
+
45
+ # Returns true if any keys were added, removed, or changed
46
+ def any?
47
+ [added, removed, changed].any?(&:any?)
48
+ end
49
+
50
+ private
51
+
52
+ def snapshot
53
+ # `dup` should not be required here, but some people use `stub_const` to replace ENV with
54
+ # a `Hash`. This ensures that we get a frozen copy of that instead of freezing the original.
55
+ # https://github.com/bkeepers/dotenv/issues/482
56
+ ENV.to_h.dup.freeze
57
+ end
58
+ end
59
+ end
@@ -1,28 +1,25 @@
1
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.
2
+ # A `.env` file that will be read and parsed into a Hash
4
3
  class Environment < Hash
5
- attr_reader :filename
4
+ attr_reader :filename, :overwrite
6
5
 
7
- def initialize(filename, is_load = false)
6
+ # Create a new Environment
7
+ #
8
+ # @param filename [String] the path to the file to read
9
+ # @param overwrite [Boolean] whether the parser should assume existing values will be overwritten
10
+ def initialize(filename, overwrite: false)
11
+ super()
8
12
  @filename = filename
9
- load(is_load)
13
+ @overwrite = overwrite
14
+ load
10
15
  end
11
16
 
12
- def load(is_load = false)
13
- update Parser.call(read, is_load)
17
+ def load
18
+ update Parser.call(read, overwrite: overwrite)
14
19
  end
15
20
 
16
21
  def read
17
22
  File.open(@filename, "rb:bom|utf-8", &:read)
18
23
  end
19
-
20
- def apply
21
- each { |k, v| ENV[k] ||= v }
22
- end
23
-
24
- def apply!
25
- each { |k, v| ENV[k] = v }
26
- end
27
24
  end
28
25
  end
data/lib/dotenv/load.rb CHANGED
@@ -1,2 +1,3 @@
1
1
  require "dotenv"
2
- Dotenv.load
2
+
3
+ defined?(Dotenv::Rails) ? Dotenv::Rails.load : Dotenv.load