1 # frozen_string_literal: true
3 require_relative "bundler/vendored_fileutils"
7 require_relative "bundler/errors"
8 require_relative "bundler/environment_preserver"
9 require_relative "bundler/plugin"
10 require_relative "bundler/rubygems_ext"
11 require_relative "bundler/rubygems_integration"
12 require_relative "bundler/version"
13 require_relative "bundler/constants"
14 require_relative "bundler/current_ruby"
15 require_relative "bundler/build_metadata"
17 # Bundler provides a consistent environment for Ruby projects by
18 # tracking and installing the exact gems and versions that are needed.
20 # Bundler is a part of Ruby's standard library.
22 # Bundler is used by creating _gemfiles_ listing all the project dependencies
23 # and (optionally) their versions and then using
25 # require 'bundler/setup'
27 # or Bundler.setup to setup environment where only specified gems and their
28 # specified versions could be used.
30 # See {Bundler website}[https://bundler.io/docs.html] for extensive documentation
31 # on gemfiles creation and Bundler usage.
33 # As a standard library inside project, Bundler could be used for introspection
34 # of loaded and required modules.
37 environment_preserver = EnvironmentPreserver.from_env
38 ORIGINAL_ENV = environment_preserver.restore
39 environment_preserver.replace_with_backup
40 SUDO_MUTEX = Thread::Mutex.new
42 autoload :Checksum, File.expand_path("bundler/checksum", __dir__)
43 autoload :CLI, File.expand_path("bundler/cli", __dir__)
44 autoload :CIDetector, File.expand_path("bundler/ci_detector", __dir__)
45 autoload :Definition, File.expand_path("bundler/definition", __dir__)
46 autoload :Dependency, File.expand_path("bundler/dependency", __dir__)
47 autoload :Deprecate, File.expand_path("bundler/deprecate", __dir__)
48 autoload :Digest, File.expand_path("bundler/digest", __dir__)
49 autoload :Dsl, File.expand_path("bundler/dsl", __dir__)
50 autoload :EndpointSpecification, File.expand_path("bundler/endpoint_specification", __dir__)
51 autoload :Env, File.expand_path("bundler/env", __dir__)
52 autoload :Fetcher, File.expand_path("bundler/fetcher", __dir__)
53 autoload :FeatureFlag, File.expand_path("bundler/feature_flag", __dir__)
54 autoload :GemHelper, File.expand_path("bundler/gem_helper", __dir__)
55 autoload :GemHelpers, File.expand_path("bundler/gem_helpers", __dir__)
56 autoload :GemVersionPromoter, File.expand_path("bundler/gem_version_promoter", __dir__)
57 autoload :Graph, File.expand_path("bundler/graph", __dir__)
58 autoload :Index, File.expand_path("bundler/index", __dir__)
59 autoload :Injector, File.expand_path("bundler/injector", __dir__)
60 autoload :Installer, File.expand_path("bundler/installer", __dir__)
61 autoload :LazySpecification, File.expand_path("bundler/lazy_specification", __dir__)
62 autoload :LockfileParser, File.expand_path("bundler/lockfile_parser", __dir__)
63 autoload :MatchRemoteMetadata, File.expand_path("bundler/match_remote_metadata", __dir__)
64 autoload :ProcessLock, File.expand_path("bundler/process_lock", __dir__)
65 autoload :RemoteSpecification, File.expand_path("bundler/remote_specification", __dir__)
66 autoload :Resolver, File.expand_path("bundler/resolver", __dir__)
67 autoload :Retry, File.expand_path("bundler/retry", __dir__)
68 autoload :RubyDsl, File.expand_path("bundler/ruby_dsl", __dir__)
69 autoload :RubyVersion, File.expand_path("bundler/ruby_version", __dir__)
70 autoload :Runtime, File.expand_path("bundler/runtime", __dir__)
71 autoload :SelfManager, File.expand_path("bundler/self_manager", __dir__)
72 autoload :Settings, File.expand_path("bundler/settings", __dir__)
73 autoload :SharedHelpers, File.expand_path("bundler/shared_helpers", __dir__)
74 autoload :Source, File.expand_path("bundler/source", __dir__)
75 autoload :SourceList, File.expand_path("bundler/source_list", __dir__)
76 autoload :SourceMap, File.expand_path("bundler/source_map", __dir__)
77 autoload :SpecSet, File.expand_path("bundler/spec_set", __dir__)
78 autoload :StubSpecification, File.expand_path("bundler/stub_specification", __dir__)
79 autoload :UI, File.expand_path("bundler/ui", __dir__)
80 autoload :URICredentialsFilter, File.expand_path("bundler/uri_credentials_filter", __dir__)
81 autoload :URINormalizer, File.expand_path("bundler/uri_normalizer", __dir__)
82 autoload :SafeMarshal, File.expand_path("bundler/safe_marshal", __dir__)
86 @configure ||= configure_gem_home_and_path
90 (defined?(@ui) && @ui) || (self.ui = UI::Shell.new)
94 Bundler.rubygems.ui = UI::RGProxy.new(ui)
98 # Returns absolute path of where gems are installed on the filesystem.
100 @bundle_path ||= Pathname.new(configured_bundle_path.path).expand_path(root)
103 def create_bundle_path
104 mkdir_p(bundle_path) unless bundle_path.exist?
106 @bundle_path = bundle_path.realpath
108 raise PathError, "Could not install to path `#{bundle_path}` " \
109 "because a file already exists at that path. Either remove or rename the file so the directory can be created."
112 def configured_bundle_path
113 @configured_bundle_path ||= settings.path.tap(&:validate!)
116 # Returns absolute location of where binstubs are installed to.
119 path = settings[:bin] || "bin"
120 path = Pathname.new(path).expand_path(root).expand_path
126 # Turns on the Bundler runtime. After +Bundler.setup+ call, all +load+ or
127 # +require+ of the gems would be allowed only if they are part of
128 # the Gemfile or Ruby's standard library. If the versions specified
129 # in Gemfile, only those versions would be loaded.
133 # gem 'first_gem', '= 1.0'
135 # gem 'second_gem', '= 1.0'
138 # The code using Bundler.setup works as follows:
140 # require 'third_gem' # allowed, required from global gems
141 # require 'first_gem' # allowed, loads the last installed version
143 # require 'fourth_gem' # fails with LoadError
144 # require 'second_gem' # loads exactly version 1.0
146 # +Bundler.setup+ can be called only once, all subsequent calls are no-op.
148 # If _groups_ list is provided, only gems from specified groups would
149 # be allowed (gems specified outside groups belong to special +:default+ group).
151 # To require all gems from Gemfile (or only some groups), see Bundler.require.
154 # Return if all groups are already loaded
155 return @setup if defined?(@setup) && @setup
157 definition.validate_runtime!
159 SharedHelpers.print_major_deprecations!
162 # Load all groups, but only once
169 # Automatically install dependencies if Bundler.settings[:auto_install] exists.
170 # This is set through config cmd `bundle config set --global auto_install 1`.
172 # Note that this method `nil`s out the global Definition object, so it
173 # should be called first, before you instantiate anything like an
174 # `Installer` that'll keep a reference to the old one instead.
176 return unless settings[:auto_install]
180 rescue GemNotFound, GitError
181 ui.info "Automatically installing missing gems."
183 CLI::Install.new({}).run
188 # Setups Bundler environment (see Bundler.setup) if it is not already set,
189 # and loads all gems from groups specified. Unlike ::setup, can be called
190 # multiple times with different groups (if they were allowed by setup).
194 # gem 'first_gem', '= 1.0'
196 # gem 'second_gem', '= 1.0'
199 # The code will work as follows:
201 # Bundler.setup # allow all groups
202 # Bundler.require(:default) # requires only first_gem
204 # Bundler.require(:test) # requires second_gem
208 setup(*groups).require(*groups)
212 @load ||= Runtime.new(root, definition)
216 SharedHelpers.major_deprecation 2, "Bundler.environment has been removed in favor of Bundler.load", print_caller_location: true
220 # Returns an instance of Bundler::Definition for given Gemfile and lockfile
222 # @param unlock [Hash, Boolean, nil] Gems that have been requested
223 # to be updated or true if all gems should be updated
224 # @param lockfile [Pathname] Path to Gemfile.lock
225 # @return [Bundler::Definition]
226 def definition(unlock = nil, lockfile = default_lockfile)
227 @definition = nil if unlock
228 @definition ||= begin
230 Definition.build(default_gemfile, lockfile, unlock)
235 frozen = settings[:frozen]
236 return frozen unless frozen.nil?
238 settings[:deployment]
243 if defined?(@definition) && @definition
244 definition.locked_gems
245 elsif Bundler.default_lockfile.file?
246 lock = Bundler.read_file(Bundler.default_lockfile)
247 LockfileParser.new(lock)
251 def most_specific_locked_platform?(platform)
252 return false unless defined?(@definition) && @definition
254 definition.most_specific_locked_platform == platform
258 "#{Bundler.rubygems.ruby_engine}/#{RbConfig::CONFIG["ruby_version"]}"
263 home = Bundler.rubygems.user_home
264 bundle_home = home ? File.join(home, ".bundle") : nil
266 warning = if home.nil?
267 "Your home directory is not set."
268 elsif !File.directory?(home)
269 "`#{home}` is not a directory."
270 elsif !File.writable?(home) && (!File.directory?(bundle_home) || !File.writable?(bundle_home))
271 "`#{home}` is not writable."
275 Bundler.ui.warn "#{warning}\n"
276 user_home = tmp_home_path
277 Bundler.ui.warn "Bundler will use `#{user_home}' as your home directory temporarily.\n"
285 def user_bundle_path(dir = "home")
286 env_var, fallback = case dir
288 ["BUNDLE_USER_HOME", proc { Pathname.new(user_home).join(".bundle") }]
290 ["BUNDLE_USER_CACHE", proc { user_bundle_path.join("cache") }]
292 ["BUNDLE_USER_CONFIG", proc { user_bundle_path.join("config") }]
294 ["BUNDLE_USER_PLUGIN", proc { user_bundle_path.join("plugin") }]
296 raise BundlerError, "Unknown user path requested: #{dir}"
298 # `fallback` will already be a Pathname, but Pathname.new() is
299 # idempotent so it's OK
300 Pathname.new(ENV.fetch(env_var, &fallback))
304 user_bundle_path("cache")
308 bundle_path.join("bundler")
316 bundle_path.join("specifications")
322 rescue GemfileNotFound
323 bundle_dir = default_bundle_dir
324 raise GemfileNotFound, "Could not locate Gemfile or .bundle/ directory" unless bundle_dir
325 Pathname.new(File.expand_path("..", bundle_dir))
330 if app_config = ENV["BUNDLE_APP_CONFIG"]
331 app_config_pathname = Pathname.new(app_config)
333 if app_config_pathname.absolute?
336 app_config_pathname.expand_path(root)
343 def app_cache(custom_path = nil)
344 path = custom_path || root
345 Pathname.new(path).join(settings.app_cache_path)
348 def tmp(name = Process.pid.to_s)
349 Kernel.send(:require, "tmpdir")
350 Pathname.new(Dir.mktmpdir(["bundler", name]))
354 FileUtils.remove_entry_secure(path) if path && File.exist?(path)
358 @settings ||= Settings.new(app_config_path)
359 rescue GemfileNotFound
360 @settings = Settings.new(Pathname.new(".bundle").expand_path)
363 # @return [Hash] Environment present before Bundler was activated
368 # @deprecated Use `unbundled_env` instead
371 "`Bundler.clean_env` has been deprecated in favor of `Bundler.unbundled_env`. " \
372 "If you instead want the environment before bundler was originally loaded, use `Bundler.original_env`"
374 "`Bundler.clean_env` has been removed in favor of `Bundler.unbundled_env`. " \
375 "If you instead want the environment before bundler was originally loaded, use `Bundler.original_env`"
376 Bundler::SharedHelpers.major_deprecation(2, message, removed_message: removed_message, print_caller_location: true)
380 # @return [Hash] Environment with all bundler-related variables removed
384 if env.key?("BUNDLER_ORIG_MANPATH")
385 env["MANPATH"] = env["BUNDLER_ORIG_MANPATH"]
388 env.delete_if {|k, _| k[0, 7] == "BUNDLE_" }
390 if env.key?("RUBYOPT")
391 rubyopt = env["RUBYOPT"].split(" ")
392 rubyopt.delete("-r#{File.expand_path("bundler/setup", __dir__)}")
393 rubyopt.delete("-rbundler/setup")
394 env["RUBYOPT"] = rubyopt.join(" ")
397 if env.key?("RUBYLIB")
398 rubylib = env["RUBYLIB"].split(File::PATH_SEPARATOR)
399 rubylib.delete(__dir__)
400 env["RUBYLIB"] = rubylib.join(File::PATH_SEPARATOR)
406 # Run block with environment present before Bundler was activated
407 def with_original_env
408 with_env(original_env) { yield }
411 # @deprecated Use `with_unbundled_env` instead
414 "`Bundler.with_clean_env` has been deprecated in favor of `Bundler.with_unbundled_env`. " \
415 "If you instead want the environment before bundler was originally loaded, use `Bundler.with_original_env`"
417 "`Bundler.with_clean_env` has been removed in favor of `Bundler.with_unbundled_env`. " \
418 "If you instead want the environment before bundler was originally loaded, use `Bundler.with_original_env`"
419 Bundler::SharedHelpers.major_deprecation(2, message, removed_message: removed_message, print_caller_location: true)
420 with_env(unbundled_env) { yield }
423 # Run block with all bundler-related variables removed
424 def with_unbundled_env
425 with_env(unbundled_env) { yield }
428 # Run subcommand with the environment present before Bundler was activated
429 def original_system(*args)
430 with_original_env { Kernel.system(*args) }
433 # @deprecated Use `unbundled_system` instead
434 def clean_system(*args)
436 "`Bundler.clean_system` has been deprecated in favor of `Bundler.unbundled_system`. " \
437 "If you instead want to run the command in the environment before bundler was originally loaded, use `Bundler.original_system`"
439 "`Bundler.clean_system` has been removed in favor of `Bundler.unbundled_system`. " \
440 "If you instead want to run the command in the environment before bundler was originally loaded, use `Bundler.original_system`"
441 Bundler::SharedHelpers.major_deprecation(2, message, removed_message: removed_message, print_caller_location: true)
442 with_env(unbundled_env) { Kernel.system(*args) }
445 # Run subcommand in an environment with all bundler related variables removed
446 def unbundled_system(*args)
447 with_unbundled_env { Kernel.system(*args) }
450 # Run a `Kernel.exec` to a subcommand with the environment present before Bundler was activated
451 def original_exec(*args)
452 with_original_env { Kernel.exec(*args) }
455 # @deprecated Use `unbundled_exec` instead
456 def clean_exec(*args)
458 "`Bundler.clean_exec` has been deprecated in favor of `Bundler.unbundled_exec`. " \
459 "If you instead want to exec to a command in the environment before bundler was originally loaded, use `Bundler.original_exec`"
461 "`Bundler.clean_exec` has been removed in favor of `Bundler.unbundled_exec`. " \
462 "If you instead want to exec to a command in the environment before bundler was originally loaded, use `Bundler.original_exec`"
463 Bundler::SharedHelpers.major_deprecation(2, message, removed_message: removed_message, print_caller_location: true)
464 with_env(unbundled_env) { Kernel.exec(*args) }
467 # Run a `Kernel.exec` to a subcommand in an environment with all bundler related variables removed
468 def unbundled_exec(*args)
469 with_env(unbundled_env) { Kernel.exec(*args) }
473 return Gem::Platform::RUBY if settings[:force_ruby_platform]
478 SharedHelpers.default_gemfile
482 SharedHelpers.default_lockfile
485 def default_bundle_dir
486 SharedHelpers.default_bundle_dir
490 # Gem.bindir doesn't always return the location that RubyGems will install
491 # system binaries. If you put '-n foo' in your .gemrc, RubyGems will
492 # install binstubs there instead. Unfortunately, RubyGems doesn't expose
493 # that directory at all, so rather than parse .gemrc ourselves, we allow
494 # the directory to be set as well, via `bundle config set --local bindir foo`.
495 Bundler.settings[:system_bindir] || Bundler.rubygems.gem_bindir
498 def preferred_gemfile_name
499 Bundler.settings[:init_gems_rb] ? "gems.rb" : "Gemfile"
503 configured_bundle_path.use_system_gems?
507 SharedHelpers.filesystem_access(path, :write) do |p|
512 def which(executable)
513 if File.file?(executable) && File.executable?(executable)
515 elsif paths = ENV["PATH"]
517 paths.split(File::PATH_SEPARATOR).find do |path|
518 path = path[1..-2] if path.start_with?(quote) && path.end_with?(quote)
519 executable_path = File.expand_path(executable, path)
520 return executable_path if File.file?(executable_path) && File.executable?(executable_path)
526 SharedHelpers.filesystem_access(file, :read) do
527 File.open(file, "r:UTF-8", &:read)
531 def safe_load_marshal(data)
532 if Gem.respond_to?(:load_safe_marshal)
533 Gem.load_safe_marshal
535 Gem::SafeMarshal.safe_load(data)
536 rescue Gem::SafeMarshal::Reader::Error, Gem::SafeMarshal::Visitors::ToRuby::Error => e
537 raise MarshalError, "#{e.class}: #{e.message}"
540 load_marshal(data, marshal_proc: SafeMarshal.proc)
544 def load_gemspec(file, validate = false)
545 @gemspec_cache ||= {}
546 key = File.expand_path(file)
547 @gemspec_cache[key] ||= load_gemspec_uncached(file, validate)
548 # Protect against caching side-effected gemspecs by returning a
549 # new instance each time.
550 @gemspec_cache[key]&.dup
553 def load_gemspec_uncached(file, validate = false)
554 path = Pathname.new(file)
555 contents = read_file(file)
556 spec = if contents.start_with?("---") # YAML header
557 eval_yaml_gemspec(path, contents)
559 # Eval the gemspec from its parent directory, because some gemspecs
560 # depend on "./" relative paths.
561 SharedHelpers.chdir(path.dirname.to_s) do
562 eval_gemspec(path, contents)
566 spec.loaded_from = path.expand_path.to_s
567 Bundler.rubygems.validate(spec) if validate
571 def clear_gemspec_cache
576 return @git_present if defined?(@git_present)
577 @git_present = Bundler.which("git#{RbConfig::CONFIG["EXEEXT"]}")
581 @feature_flag ||= FeatureFlag.new(VERSION)
584 def load_plugins(definition = Bundler.definition)
585 return if defined?(@load_plugins_ran)
587 Bundler.rubygems.load_plugins
589 requested_path_gems = definition.requested_specs.select {|s| s.source.is_a?(Source::Path) }
590 path_plugin_files = requested_path_gems.map do |spec|
591 Bundler.rubygems.spec_matches_for_glob(spec, "rubygems_plugin#{Bundler.rubygems.suffix_pattern}")
593 error_message = "#{spec.name} #{spec.version} has an invalid gemspec"
594 raise Gem::InvalidSpecificationException, error_message
596 Bundler.rubygems.load_plugin_files(path_plugin_files)
597 Bundler.rubygems.load_env_plugins
598 @load_plugins_ran = true
607 def reset_settings_and_root!
614 @bundler_major_version = nil
617 @configured_bundle_path = nil
628 return unless defined?(@rubygems) && @rubygems
629 rubygems.undo_replacements
634 def configure_gem_home_and_path(path = bundle_path)
636 configure_gem_home(path)
637 Bundler.rubygems.clear_paths
641 @self_manager ||= begin
642 require_relative "bundler/self_manager"
643 Bundler::SelfManager.new
649 def load_marshal(data, marshal_proc: nil)
650 Marshal.load(data, marshal_proc)
651 rescue TypeError => e
652 raise MarshalError, "#{e.class}: #{e.message}"
655 def eval_yaml_gemspec(path, contents)
656 Kernel.require "psych"
658 Gem::Specification.from_yaml(contents)
659 rescue ::Psych::SyntaxError, ArgumentError, Gem::EndOfYAMLException, Gem::Exception
660 eval_gemspec(path, contents)
663 def eval_gemspec(path, contents)
664 eval(contents, TOPLEVEL_BINDING.dup, path.expand_path.to_s)
665 rescue ScriptError, StandardError => e
666 msg = "There was an error while loading `#{path.basename}`: #{e.message}"
668 raise GemspecError, Dsl::DSLError.new(msg, path, e.backtrace, contents)
671 def configure_gem_path
672 unless use_system_gems?
673 # this needs to be empty string to cause
674 # PathSupport.split_gem_path to only load up the
675 # Bundler --path setting as the GEM_PATH.
676 Bundler::SharedHelpers.set_env "GEM_PATH", ""
680 def configure_gem_home(path)
681 Bundler::SharedHelpers.set_env "GEM_HOME", path.to_s
685 Kernel.send(:require, "tmpdir")
686 SharedHelpers.filesystem_access(Dir.tmpdir) do
688 at_exit { Bundler.rm_rf(path) }