Class: Bundler::EnvironmentPreserver

Inherits:
Object
  • Object
show all
Defined in:
lib/bundler/environment_preserver.rb

Constant Summary collapse

INTENTIONALLY_NIL =
"BUNDLER_ENVIRONMENT_PRESERVER_INTENTIONALLY_NIL".freeze
BUNDLER_KEYS =
%w[
  BUNDLE_BIN_PATH
  BUNDLE_GEMFILE
  BUNDLER_VERSION
  BUNDLER_SETUP
  GEM_HOME
  GEM_PATH
  MANPATH
  PATH
  RB_USER_INSTALL
  RUBYLIB
  RUBYOPT
].map(&:freeze).freeze
BUNDLER_PREFIX =
"BUNDLER_ORIG_".freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env, keys) ⇒ EnvironmentPreserver

Returns a new instance of EnvironmentPreserver.

Parameters:

  • env (Hash)
  • keys (Array<String>)


34
35
36
37
38
# File 'lib/bundler/environment_preserver.rb', line 34

def initialize(env, keys)
  @original = env
  @keys = keys
  @prefix = BUNDLER_PREFIX
end

Class Method Details

.env_to_hash(env) ⇒ Object



25
26
27
28
29
30
# File 'lib/bundler/environment_preserver.rb', line 25

def self.env_to_hash(env)
  to_hash = env.to_hash
  return to_hash unless Gem.win_platform?

  to_hash.each_with_object({}) {|(k,v), a| a[k.upcase] = v }
end

.from_envObject



21
22
23
# File 'lib/bundler/environment_preserver.rb', line 21

def self.from_env
  new(env_to_hash(ENV), BUNDLER_KEYS)
end

Instance Method Details

#backupHash

Returns:

  • (Hash)


57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/bundler/environment_preserver.rb', line 57

def backup
  env = @original.clone
  @keys.each do |key|
    value = env[key]
    if !value.nil? && !value.empty?
      env[@prefix + key] ||= value
    elsif value.nil?
      env[@prefix + key] ||= INTENTIONALLY_NIL
    end
  end
  env
end

#replace_with_backupObject

Replaces ‘ENV` with the bundler environment variables backed up



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/bundler/environment_preserver.rb', line 41

def replace_with_backup
  unless Gem.win_platform?
    ENV.replace(backup)
    return
  end

  # Fallback logic for Windows below to workaround
  # https://bugs.ruby-lang.org/issues/16798. Can be dropped once all
  # supported rubies include the fix for that.

  ENV.clear

  backup.each {|k, v| ENV[k] = v }
end

#restoreHash

Returns:

  • (Hash)


71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/bundler/environment_preserver.rb', line 71

def restore
  env = @original.clone
  @keys.each do |key|
    value_original = env[@prefix + key]
    next if value_original.nil? || value_original.empty?
    if value_original == INTENTIONALLY_NIL
      env.delete(key)
    else
      env[key] = value_original
    end
    env.delete(@prefix + key)
  end
  env
end