Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Guard against restore being called with no previously saved state #503

Merged
merged 1 commit into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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