Skip to content

Commit

Permalink
Guard against restore being called with no previously saved state
Browse files Browse the repository at this point in the history
  • Loading branch information
bkeepers committed Apr 30, 2024
1 parent aeb2052 commit 2567e26
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/dotenv.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ def save
# @param env [Hash] Hash of keys and values to restore, defaults to the last saved state
# @param safe [Boolean] Is it safe to modify `ENV`? Defaults to `true` in the main thread, otherwise raises an error.
def restore(env = @diff&.a, safe: Thread.current == Thread.main)
# No previously saved or provided state to restore
return unless env

diff = Dotenv::Diff.new(b: env)
return unless diff.any?

Expand Down
11 changes: 11 additions & 0 deletions spec/dotenv_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,17 @@
end.join
expect(ENV["MODIFIED"]).to eq("true")
end

it "is a noop if nil state provided" do
expect { Dotenv.restore(nil) }.not_to raise_error
end

it "is a noop if no previously saved state" do
# Clear state saved in setup
expect(Dotenv.instance_variable_get(:@diff)).to be_instance_of(Dotenv::Diff)
Dotenv.instance_variable_set(:@diff, nil)
expect { Dotenv.restore }.not_to raise_error
end
end

describe "modify" do
Expand Down

0 comments on commit 2567e26

Please sign in to comment.