dotenv 2.8.1 → 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: ac1a9e8e04f95f111da23bf2541070f2617864fc3c55ac4e11e6b91c78d11a9b
4
- data.tar.gz: 24bf24be5be7020e72877e32d8cd2d9cf022a74b182569c77b2c81c0d482696b
3
+ metadata.gz: d94f968de5def640d49274915a92e82c9dcf9e5783e58fee39fa2b72a9b7ac0d
4
+ data.tar.gz: e892cb84dfbcc7c38bd484f4c747849c52f3050fc170719180c3f79eef63a2ef
5
5
  SHA512:
6
- metadata.gz: 1f8d6ae3bfd67c1b57bc4d72346d670c02570d07cee953930d6b7f9018cc053ac42624d1bc4d59dd112abe5ba711d551199ff92a2672d5434577356b0a24d0c0
7
- data.tar.gz: 38488d0f24d6f6014f87415775f94969cd56236bcb848c77b5dd4d066285ec47993006f87f1ab1afb50a033db101fe206741ec8e561de602a88717ad6fff3bdf
6
+ metadata.gz: 5ce6017a1069f68382d9a0a241130243bc807a388788bd17129ce2a135d10cdb1dd607b8fbb69ce469540114d77014a833dbe2ebc416ae77560c5bf40db09e0c
7
+ data.tar.gz: 301e709c9e0d322668a145ee6cf723a532b2805a6112a6479624b6cd61be0e4b60a42234be611bc1901195f99c799598402b846c257f813744ef286bd0326987
data/README.md CHANGED
@@ -1,4 +1,4 @@
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)
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,52 +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
- # 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']
29
+ config.fog_directory = ENV['S3_BUCKET']
39
30
  ```
40
31
 
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`.
32
+ See the [API Docs](https://rubydoc.info/github/bkeepers/dotenv/main) for more.
42
33
 
43
- ```ruby
44
- gem 'dotenv-rails', require: 'dotenv/rails-now'
45
- gem 'gem-that-requires-env-variables'
46
- ```
47
-
48
- ### Sinatra or Plain ol' Ruby
34
+ ### Rails
49
35
 
50
- Install the gem:
36
+ Dotenv will automatically load when your Rails app boots. See [Customizing Rails](#customizing-rails) to change which files are loaded and when.
51
37
 
52
- ```shell
53
- $ gem install dotenv
54
- ```
38
+ ### Sinatra / Ruby
55
39
 
56
- As early as possible in your application bootstrap process, load `.env`:
40
+ Load Dotenv as early as possible in your application bootstrap process:
57
41
 
58
42
  ```ruby
59
43
  require 'dotenv/load'
@@ -63,24 +47,27 @@ require 'dotenv'
63
47
  Dotenv.load
64
48
  ```
65
49
 
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.
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`.
67
54
 
68
55
  ```ruby
69
56
  require 'dotenv'
70
57
  Dotenv.load('file1.env', 'file2.env')
71
58
  ```
72
59
 
73
- Alternatively, you can use the `dotenv` executable to launch your application:
60
+ ### Autorestore in tests
74
61
 
75
- ```shell
76
- $ dotenv ./script.rb
77
- ```
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`.
78
63
 
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.
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).
80
65
 
81
- ```
82
- $ dotenv -f ".env.local,.env" ./script.rb
83
- ```
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
84
71
 
85
72
  To ensure `.env` is loaded in rake, load the tasks:
86
73
 
@@ -88,41 +75,121 @@ To ensure `.env` is loaded in rake, load the tasks:
88
75
  require 'dotenv/tasks'
89
76
 
90
77
  task mytask: :dotenv do
91
- # things that require .env
78
+ # things that require .env
92
79
  end
93
80
  ```
94
81
 
95
- ## Usage
82
+ ### CLI
96
83
 
97
- 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:
98
85
 
99
- ```shell
100
- S3_BUCKET=YOURS3BUCKET
101
- SECRET_KEY=YOURSECRETKEYGOESHERE
86
+ ```console
87
+ $ dotenv ./script.rb
102
88
  ```
103
89
 
104
- 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.
105
91
 
106
- ```ruby
107
- config.fog_directory = ENV['S3_BUCKET']
92
+ ```console
93
+ $ dotenv -f ".env.local,.env" ./script.rb
108
94
  ```
109
95
 
110
- 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.
111
97
 
112
- ```shell
113
- export S3_BUCKET=YOURS3BUCKET
114
- export SECRET_KEY=YOURSECRETKEYGOESHERE
98
+ ```console
99
+ $ dotenv -i -f ".env.local,.env" ./script.rb
115
100
  ```
116
101
 
117
- ### Multi-line values
102
+ ### Load Order
118
103
 
119
- 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`.
120
105
 
121
- ```shell
122
- 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'
123
109
  ```
124
110
 
125
- Alternatively, multi-line values with line breaks are now supported for quoted values.
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
181
+ ```
182
+
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.
126
193
 
127
194
  ```shell
128
195
  PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
@@ -132,7 +199,12 @@ HkVN9...
132
199
  -----END DSA PRIVATE KEY-----"
133
200
  ```
134
201
 
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.
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
+ ```
136
208
 
137
209
  ### Command Substitution
138
210
 
@@ -144,7 +216,7 @@ DATABASE_URL="postgres://$(whoami)@localhost/my_database"
144
216
 
145
217
  ### Variable Substitution
146
218
 
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.
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.
148
220
 
149
221
  ```shell
150
222
  DATABASE_URL="postgres://${USER}@localhost/my_database"
@@ -166,6 +238,15 @@ SECRET_KEY=YOURSECRETKEYGOESHERE # comment
166
238
  SECRET_HASH="something-with-a-#-hash"
167
239
  ```
168
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
+
169
250
  ### Required Keys
170
251
 
171
252
  If a particular configuration value is required but not set, it's appropriate to raise an error.
@@ -191,42 +272,14 @@ Dotenv.parse(".env.local", ".env")
191
272
 
192
273
  This method returns a hash of the ENV var name/value pairs.
193
274
 
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
-
275
+ ### Templates
224
276
 
225
277
  You can use the `-t` or `--template` flag on the dotenv cli to create a template of your `.env` file.
226
- ```shell
278
+
279
+ ```console
227
280
  $ dotenv -t .env
228
281
  ```
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.
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.
230
283
 
231
284
  The template will contain all the environment variables in your `.env` file but with their values set to the variable names.
232
285
 
@@ -244,14 +297,32 @@ S3_BUCKET=S3_BUCKET
244
297
  SECRET_KEY=SECRET_KEY
245
298
  ```
246
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
+
247
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.
248
315
 
249
- ### Why is it not overriding existing `ENV` variables?
316
+ ### Why is it not overwriting existing `ENV` variables?
250
317
 
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`.
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`.
252
319
 
253
- You can also use the `-o` or `--overload` flag on the dotenv cli to override existing `ENV` variables.
254
- ```shell
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
255
326
  $ dotenv -o -f ".env.local,.env"
256
327
  ```
257
328
 
@@ -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,26 +4,32 @@ require "dotenv/template"
4
4
  require "optparse"
5
5
 
6
6
  module Dotenv
7
- # The command line interface
7
+ # The `dotenv` command line interface. Run `$ dotenv --help` to see usage.
8
8
  class CLI < OptionParser
9
- attr_reader :argv, :filenames, :overload
9
+ attr_reader :argv, :filenames, :overwrite
10
10
 
11
11
  def initialize(argv = [])
12
12
  @argv = argv.dup
13
13
  @filenames = []
14
- @overload = false
14
+ @ignore = false
15
+ @overwrite = false
15
16
 
16
- super "Usage: dotenv [options]"
17
+ super("Usage: dotenv [options]")
17
18
  separator ""
18
19
 
19
20
  on("-f FILES", Array, "List of env files to parse") do |list|
20
21
  @filenames = list
21
22
  end
22
23
 
23
- on("-o", "--overload", "override existing ENV variables") do
24
- @overload = true
24
+ on("-i", "--ignore", "ignore missing env files") do
25
+ @ignore = true
25
26
  end
26
27
 
28
+ on("-o", "--overwrite", "overwrite existing ENV variables") do
29
+ @overwrite = true
30
+ end
31
+ on("--overload") { @overwrite = true }
32
+
27
33
  on("-h", "--help", "Display help") do
28
34
  puts self
29
35
  exit
@@ -43,11 +49,7 @@ module Dotenv
43
49
  end
44
50
 
45
51
  def run
46
- if @overload
47
- Dotenv.overload!(*@filenames)
48
- else
49
- Dotenv.load!(*@filenames)
50
- end
52
+ Dotenv.load(*@filenames, overwrite: @overwrite, ignore: @ignore)
51
53
  rescue Errno::ENOENT => e
52
54
  abort e.message
53
55
  else
@@ -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
@@ -0,0 +1,61 @@
1
+ require "active_support/log_subscriber"
2
+
3
+ module Dotenv
4
+ # Logs instrumented events
5
+ #
6
+ # Usage:
7
+ # require "active_support/notifications"
8
+ # require "dotenv/log_subscriber"
9
+ # Dotenv.instrumenter = ActiveSupport::Notifications
10
+ #
11
+ class LogSubscriber < ActiveSupport::LogSubscriber
12
+ attach_to :dotenv
13
+
14
+ def logger
15
+ Dotenv::Rails.logger
16
+ end
17
+
18
+ def load(event)
19
+ env = event.payload[:env]
20
+
21
+ info "Loaded #{color_filename(env.filename)}"
22
+ end
23
+
24
+ def update(event)
25
+ diff = event.payload[:diff]
26
+ changed = diff.env.keys.map { |key| color_var(key) }
27
+ debug "Set #{changed.join(", ")}" if diff.any?
28
+ end
29
+
30
+ def save(event)
31
+ info "Saved a snapshot of #{color_env_constant}"
32
+ end
33
+
34
+ def restore(event)
35
+ diff = event.payload[:diff]
36
+
37
+ removed = diff.removed.keys.map { |key| color(key, :RED) }
38
+ restored = (diff.changed.keys + diff.added.keys).map { |key| color_var(key) }
39
+
40
+ if removed.any? || restored.any?
41
+ info "Restored snapshot of #{color_env_constant}"
42
+ debug "Unset #{removed.join(", ")}" if removed.any?
43
+ debug "Restored #{restored.join(", ")}" if restored.any?
44
+ end
45
+ end
46
+
47
+ private
48
+
49
+ def color_filename(filename)
50
+ color(Pathname.new(filename).relative_path_from(Dotenv::Rails.root.to_s).to_s, :YELLOW)
51
+ end
52
+
53
+ def color_var(name)
54
+ color(name, :CYAN)
55
+ end
56
+
57
+ def color_env_constant
58
+ color("ENV", :GREEN)
59
+ end
60
+ end
61
+ end
@@ -3,7 +3,7 @@ module Dotenv
3
3
 
4
4
  class MissingKeys < Error # :nodoc:
5
5
  def initialize(keys)
6
- key_word = "key#{keys.size > 1 ? "s" : ""}"
6
+ key_word = "key#{"s" if keys.size > 1}"
7
7
  super("Missing required configuration #{key_word}: #{keys.inspect}")
8
8
  end
9
9
  end