diff options
| author | Misty De Meo | 2017-07-13 17:14:21 -0700 |
|---|---|---|
| committer | Misty De Meo | 2017-07-15 17:39:55 -0700 |
| commit | 30adcab6cfc18c13eae3a2cc7d6486c812162d57 (patch) | |
| tree | 1eeb9209338f0be2d16626a095d25a526b293652 /Library/Homebrew/utils.rb | |
| parent | 4ca2efb12dd1399526e0aa845b56ede58daecddd (diff) | |
| download | brew-30adcab6cfc18c13eae3a2cc7d6486c812162d57.tar.bz2 | |
Add `with_env` helper to set temporary ENV vars
Diffstat (limited to 'Library/Homebrew/utils.rb')
| -rw-r--r-- | Library/Homebrew/utils.rb | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/Library/Homebrew/utils.rb b/Library/Homebrew/utils.rb index 529f3492d..e888404f7 100644 --- a/Library/Homebrew/utils.rb +++ b/Library/Homebrew/utils.rb @@ -533,3 +533,27 @@ def migrate_legacy_keg_symlinks_if_necessary end FileUtils.rm_rf legacy_pinned_kegs end + +# Calls the given block with the passed environment variables +# added to ENV, then restores ENV afterwards. +# Example: +# with_env "PATH" => "/bin" do +# system "echo $PATH" +# end +# +# Note that this method is *not* thread-safe - other threads +# which happen to be scheduled during the block will also +# see these environment variables. +def with_env(hash) + old_values = {} + begin + hash.each do |key, value| + old_values[key] = ENV.delete(key) + ENV[key] = value + end + + yield if block_given? + ensure + ENV.update(old_values) + end +end |
