Skip to content

Commit

Permalink
Merge pull request #503 from bkeepers/guard-restore
Browse files Browse the repository at this point in the history
Guard against restore being called with no previously saved state
  • Loading branch information
bkeepers authored Apr 30, 2024
2 parents e43d34a + 2567e26 commit 6cbcf3c
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 @@ -75,6 +75,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 6cbcf3c

Please sign in to comment.