summaryrefslogtreecommitdiff
path: root/lib/bundler/cli
diff options
context:
space:
mode:
Diffstat (limited to 'lib/bundler/cli')
-rw-r--r--lib/bundler/cli/add.rb24
-rw-r--r--lib/bundler/cli/binstubs.rb18
-rw-r--r--lib/bundler/cli/cache.rb26
-rw-r--r--lib/bundler/cli/check.rb12
-rw-r--r--lib/bundler/cli/clean.rb2
-rw-r--r--lib/bundler/cli/common.rb70
-rw-r--r--lib/bundler/cli/config.rb36
-rw-r--r--lib/bundler/cli/console.rb28
-rw-r--r--lib/bundler/cli/doctor.rb161
-rw-r--r--lib/bundler/cli/doctor/diagnose.rb167
-rw-r--r--lib/bundler/cli/doctor/ssl.rb249
-rw-r--r--lib/bundler/cli/exec.rb47
-rw-r--r--lib/bundler/cli/fund.rb36
-rw-r--r--lib/bundler/cli/gem.rb372
-rw-r--r--lib/bundler/cli/info.rb55
-rw-r--r--lib/bundler/cli/init.rb10
-rw-r--r--lib/bundler/cli/inject.rb60
-rw-r--r--lib/bundler/cli/install.rb168
-rw-r--r--lib/bundler/cli/issue.rb15
-rw-r--r--lib/bundler/cli/list.rb63
-rw-r--r--lib/bundler/cli/lock.rb83
-rw-r--r--lib/bundler/cli/open.rb19
-rw-r--r--lib/bundler/cli/outdated.rb225
-rw-r--r--lib/bundler/cli/package.rb48
-rw-r--r--lib/bundler/cli/platform.rb14
-rw-r--r--lib/bundler/cli/plugin.rb34
-rw-r--r--lib/bundler/cli/pristine.rb65
-rw-r--r--lib/bundler/cli/remove.rb3
-rw-r--r--lib/bundler/cli/show.rb20
-rw-r--r--lib/bundler/cli/update.rb38
-rw-r--r--lib/bundler/cli/viz.rb31
31 files changed, 1406 insertions, 793 deletions
diff --git a/lib/bundler/cli/add.rb b/lib/bundler/cli/add.rb
index 07b951f1ef..d65ed68b4a 100644
--- a/lib/bundler/cli/add.rb
+++ b/lib/bundler/cli/add.rb
@@ -12,12 +12,14 @@ module Bundler
end
def run
+ Bundler.ui.level = "warn" if options[:quiet]
+
validate_options!
inject_dependencies
perform_bundle_install unless options["skip-install"]
end
- private
+ private
def perform_bundle_install
Installer.install(Bundler.root, Bundler.definition)
@@ -28,19 +30,29 @@ module Bundler
dependencies = gems.map {|g| Bundler::Dependency.new(g, version, options) }
Injector.inject(dependencies,
- :conservative_versioning => options[:version].nil?, # Perform conservative versioning only when version is not specified
- :optimistic => options[:optimistic],
- :strict => options[:strict])
+ conservative_versioning: options[:version].nil?, # Perform conservative versioning only when version is not specified
+ pessimistic: options[:pessimistic],
+ strict: options[:strict])
end
def validate_options!
- raise InvalidOption, "You can not specify `--strict` and `--optimistic` at the same time." if options[:strict] && options[:optimistic]
+ raise InvalidOption, "You cannot specify `--git` and `--github` at the same time." if options["git"] && options["github"]
+
+ unless options["git"] || options["github"]
+ raise InvalidOption, "You cannot specify `--branch` unless `--git` or `--github` is specified." if options["branch"]
+
+ raise InvalidOption, "You cannot specify `--ref` unless `--git` or `--github` is specified." if options["ref"]
+ end
+
+ raise InvalidOption, "You cannot specify `--branch` and `--ref` at the same time." if options["branch"] && options["ref"]
+
+ raise InvalidOption, "You cannot specify `--strict` and `--pessimistic` at the same time." if options[:strict] && options[:pessimistic]
# raise error when no gems are specified
raise InvalidOption, "Please specify gems to add." if gems.empty?
version.to_a.each do |v|
- raise InvalidOption, "Invalid gem requirement pattern '#{v}'" unless Gem::Requirement::PATTERN =~ v.to_s
+ raise InvalidOption, "Invalid gem requirement pattern '#{v}'" unless Gem::Requirement::PATTERN.match?(v.to_s)
end
end
end
diff --git a/lib/bundler/cli/binstubs.rb b/lib/bundler/cli/binstubs.rb
index 266396eedc..8ce138df96 100644
--- a/lib/bundler/cli/binstubs.rb
+++ b/lib/bundler/cli/binstubs.rb
@@ -11,12 +11,16 @@ module Bundler
def run
Bundler.definition.validate_runtime!
path_option = options["path"]
- path_option = nil if path_option && path_option.empty?
+ path_option = nil if path_option&.empty?
Bundler.settings.set_command_option :bin, path_option if options["path"]
Bundler.settings.set_command_option_if_given :shebang, options["shebang"]
installer = Installer.new(Bundler.root, Bundler.definition)
- installer_opts = { :force => options[:force], :binstubs_cmd => true }
+ installer_opts = {
+ force: options[:force],
+ binstubs_cmd: true,
+ all_platforms: options["all-platforms"],
+ }
if options[:all]
raise InvalidOption, "Cannot specify --all with specific gems" unless gems.empty?
@@ -36,9 +40,13 @@ module Bundler
end
if options[:standalone]
- next Bundler.ui.warn("Sorry, Bundler can only be run via RubyGems.") if gem_name == "bundler"
- Bundler.settings.temporary(:path => (Bundler.settings[:path] || Bundler.root)) do
- installer.generate_standalone_bundler_executable_stubs(spec)
+ if gem_name == "bundler"
+ Bundler.ui.warn("Sorry, Bundler can only be run via RubyGems.") unless options[:all]
+ next
+ end
+
+ Bundler.settings.temporary(path: Bundler.settings[:path] || Bundler.root) do
+ installer.generate_standalone_bundler_executable_stubs(spec, installer_opts)
end
else
installer.generate_bundler_executable_stubs(spec, installer_opts)
diff --git a/lib/bundler/cli/cache.rb b/lib/bundler/cli/cache.rb
index 5e8420990f..59605df847 100644
--- a/lib/bundler/cli/cache.rb
+++ b/lib/bundler/cli/cache.rb
@@ -9,40 +9,24 @@ module Bundler
end
def run
- Bundler.ui.level = "error" if options[:quiet]
- Bundler.settings.set_command_option_if_given :path, options[:path]
+ Bundler.ui.level = "warn" if options[:quiet]
Bundler.settings.set_command_option_if_given :cache_path, options["cache-path"]
- setup_cache_all
install
- # TODO: move cache contents here now that all bundles are locked
- custom_path = Bundler.settings[:path] if options[:path]
-
- Bundler.settings.temporary(:cache_all_platforms => options["all-platforms"]) do
- Bundler.load.cache(custom_path)
+ Bundler.settings.temporary(cache_all_platforms: options["all-platforms"]) do
+ Bundler.load.cache
end
end
- private
+ private
def install
require_relative "install"
options = self.options.dup
options["local"] = false if Bundler.settings[:cache_all_platforms]
+ options["no-cache"] = true
Bundler::CLI::Install.new(options).run
end
-
- def setup_cache_all
- all = options.fetch(:all, Bundler.feature_flag.cache_all? || nil)
-
- Bundler.settings.set_command_option_if_given :cache_all, all
-
- if Bundler.definition.has_local_dependencies? && !Bundler.feature_flag.cache_all?
- Bundler.ui.warn "Your Gemfile contains path and git dependencies. If you want " \
- "to cache them as well, please pass the --all flag. This will be the default " \
- "on Bundler 3.0."
- end
- end
end
end
diff --git a/lib/bundler/cli/check.rb b/lib/bundler/cli/check.rb
index 19c0aaea06..493eb3ec6a 100644
--- a/lib/bundler/cli/check.rb
+++ b/lib/bundler/cli/check.rb
@@ -11,11 +11,13 @@ module Bundler
def run
Bundler.settings.set_command_option_if_given :path, options[:path]
+ definition = Bundler.definition
+ definition.validate_runtime!
+
begin
- definition = Bundler.definition
- definition.validate_runtime!
+ definition.check!
not_installed = definition.missing_specs
- rescue GemNotFound, VersionConflict
+ rescue GemNotFound, GitError, SolveFailure
Bundler.ui.error "Bundler can't satisfy your Gemfile's dependencies."
Bundler.ui.warn "Install missing gems with `bundle install`."
exit 1
@@ -27,10 +29,10 @@ module Bundler
Bundler.ui.warn "Install missing gems with `bundle install`"
exit 1
elsif !Bundler.default_lockfile.file? && Bundler.frozen_bundle?
- Bundler.ui.error "This bundle has been frozen, but there is no #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)} present"
+ Bundler.ui.error "This bundle has been frozen, but there is no #{SharedHelpers.relative_lockfile_path} present"
exit 1
else
- Bundler.load.lock(:preserve_unknown_sections => true) unless options[:"dry-run"]
+ definition.lock(true) unless options[:"dry-run"]
Bundler.ui.info "The Gemfile's dependencies are satisfied"
end
end
diff --git a/lib/bundler/cli/clean.rb b/lib/bundler/cli/clean.rb
index 4a407fbae7..c6b0968e3e 100644
--- a/lib/bundler/cli/clean.rb
+++ b/lib/bundler/cli/clean.rb
@@ -13,7 +13,7 @@ module Bundler
Bundler.load.clean(options[:"dry-run"])
end
- protected
+ protected
def require_path_or_force
return unless Bundler.use_system_gems? && !options[:force]
diff --git a/lib/bundler/cli/common.rb b/lib/bundler/cli/common.rb
index cec7bcadb4..2f332ff364 100644
--- a/lib/bundler/cli/common.rb
+++ b/lib/bundler/cli/common.rb
@@ -14,6 +14,21 @@ module Bundler
Bundler.ui.info msg
end
+ def self.output_fund_metadata_summary
+ return if Bundler.settings["ignore_funding_requests"]
+ definition = Bundler.definition
+ current_dependencies = definition.requested_dependencies
+ current_specs = definition.specs
+
+ count = current_dependencies.count {|dep| current_specs[dep.name].first.metadata.key?("funding_uri") }
+
+ return if count.zero?
+
+ intro = count > 1 ? "#{count} installed gems you directly depend on are" : "#{count} installed gem you directly depend on is"
+ message = "#{intro} looking for funding.\n Run `bundle fund` for details"
+ Bundler.ui.info message
+ end
+
def self.output_without_groups_message(command)
return if Bundler.settings[:without].empty?
Bundler.ui.confirm without_groups_message(command)
@@ -22,10 +37,15 @@ module Bundler
def self.without_groups_message(command)
command_in_past_tense = command == :install ? "installed" : "updated"
groups = Bundler.settings[:without]
+ "Gems in the #{verbalize_groups(groups)} were not #{command_in_past_tense}."
+ end
+
+ def self.verbalize_groups(groups)
+ groups.map! {|g| "'#{g}'" }
group_list = [groups[0...-1].join(", "), groups[-1..-1]].
reject {|s| s.to_s.empty? }.join(" and ")
group_str = groups.size == 1 ? "group" : "groups"
- "Gems in the #{group_str} #{group_list} were not #{command_in_past_tense}."
+ "#{group_str} #{group_list}"
end
def self.select_spec(name, regex_match = nil)
@@ -34,12 +54,21 @@ module Bundler
Bundler.definition.specs.each do |spec|
return spec if spec.name == name
- specs << spec if regexp && spec.name =~ regexp
+ specs << spec if regexp && spec.name.match?(regexp)
end
+ default_spec = default_gem_spec(name)
+ specs << default_spec if default_spec
+
case specs.count
when 0
- raise GemNotFound, gem_not_found_message(name, Bundler.definition.dependencies)
+ dep_in_other_group = Bundler.definition.current_dependencies.find {|dep|dep.name == name }
+
+ if dep_in_other_group
+ raise GemNotFound, "Could not find gem '#{name}', because it's in the #{verbalize_groups(dep_in_other_group.groups)}, configured to be ignored."
+ else
+ raise GemNotFound, gem_not_found_message(name, Bundler.definition.dependencies)
+ end
when 1
specs.first
else
@@ -49,6 +78,11 @@ module Bundler
raise GemNotFound, gem_not_found_message(name, Bundler.definition.dependencies)
end
+ def self.default_gem_spec(name)
+ gem_spec = Gem::Specification.find_all_by_name(name).last
+ gem_spec if gem_spec&.default_gem?
+ end
+
def self.ask_for_spec_from(specs)
specs.each_with_index do |spec, index|
Bundler.ui.info "#{index.succ} : #{spec.name}", true
@@ -60,15 +94,20 @@ module Bundler
end
def self.gem_not_found_message(missing_gem_name, alternatives)
- require_relative "../similarity_detector"
message = "Could not find gem '#{missing_gem_name}'."
alternate_names = alternatives.map {|a| a.respond_to?(:name) ? a.name : a }
- suggestions = SimilarityDetector.new(alternate_names).similar_word_list(missing_gem_name)
- message += "\nDid you mean #{suggestions}?" if suggestions
+ if alternate_names.include?(missing_gem_name.downcase)
+ message += "\nDid you mean '#{missing_gem_name.downcase}'?"
+ elsif defined?(DidYouMean::SpellChecker)
+ suggestions = DidYouMean::SpellChecker.new(dictionary: alternate_names).correct(missing_gem_name)
+ message += "\nDid you mean #{word_list(suggestions)}?" unless suggestions.empty?
+ end
message
end
def self.ensure_all_gems_in_lockfile!(names, locked_gems = Bundler.locked_gems)
+ return unless locked_gems
+
locked_names = locked_gems.specs.map(&:name).uniq
names.-(locked_names).each do |g|
raise GemNotFound, gem_not_found_message(g, locked_names)
@@ -82,7 +121,8 @@ module Bundler
definition.gem_version_promoter.tap do |gvp|
gvp.level = patch_level.first || :major
- gvp.strict = options[:strict] || options["update-strict"] || options["filter-strict"]
+ gvp.strict = options[:strict] || options["filter-strict"]
+ gvp.pre = options[:pre]
end
end
@@ -93,9 +133,23 @@ module Bundler
def self.clean_after_install?
clean = Bundler.settings[:clean]
return clean unless clean.nil?
- clean ||= Bundler.feature_flag.auto_clean_without_path? && Bundler.settings[:path].nil?
+ clean ||= Bundler.feature_flag.bundler_5_mode? && Bundler.settings[:path].nil?
clean &&= !Bundler.use_system_gems?
clean
end
+
+ def self.word_list(words)
+ if words.empty?
+ return ""
+ end
+
+ words = words.map {|word| "'#{word}'" }
+
+ if words.length == 1
+ return words[0]
+ end
+
+ [words[0..-2].join(", "), words[-1]].join(" or ")
+ end
end
end
diff --git a/lib/bundler/cli/config.rb b/lib/bundler/cli/config.rb
index 8d2aba0916..976cda7484 100644
--- a/lib/bundler/cli/config.rb
+++ b/lib/bundler/cli/config.rb
@@ -2,17 +2,17 @@
module Bundler
class CLI::Config < Thor
- class_option :parseable, :type => :boolean, :banner => "Use minimal formatting for more parseable output"
+ class_option :parseable, type: :boolean, banner: "Use minimal formatting for more parseable output"
def self.scope_options
- method_option :global, :type => :boolean, :banner => "Only change the global config"
- method_option :local, :type => :boolean, :banner => "Only change the local config"
+ method_option :global, type: :boolean, banner: "Only change the global config"
+ method_option :local, type: :boolean, banner: "Only change the local config"
end
private_class_method :scope_options
- desc "base NAME [VALUE]", "The Bundler 1 config interface", :hide => true
+ desc "base NAME [VALUE]", "The Bundler 1 config interface", hide: true
scope_options
- method_option :delete, :type => :boolean, :banner => "delete"
+ method_option :delete, type: :boolean, banner: "delete"
def base(name = nil, *value)
new_args =
if ARGV.size == 1
@@ -25,8 +25,8 @@ module Bundler
["config", "get", ARGV[1]]
end
- SharedHelpers.major_deprecation 3,
- "Using the `config` command without a subcommand [list, get, set, unset] is deprecated and will be removed in the future. Use `bundle #{new_args.join(" ")}` instead."
+ message = "Using the `config` command without a subcommand [list, get, set, unset] is deprecated and will be removed in the future. Use `bundle #{new_args.join(" ")}` instead."
+ SharedHelpers.feature_deprecated! message
Base.new(options, name, value, self).run
end
@@ -87,16 +87,21 @@ module Bundler
if value.nil?
warn_unused_scope "Ignoring --#{scope} since no value to set was given"
+ current_value = Bundler.settings[name]
if options[:parseable]
if value = Bundler.settings[name]
Bundler.ui.info("#{name}=#{value}")
end
- return
+ else
+ confirm(name)
end
- confirm(name)
- return
+ if current_value.nil?
+ exit 1
+ else
+ return
+ end
end
Bundler.ui.info(message) if message
@@ -180,7 +185,7 @@ module Bundler
scopes = %w[global local].select {|s| options[s] }
case scopes.size
when 0
- @scope = "global"
+ @scope = inside_app? ? "local" : "global"
@explicit_scope = false
when 1
@scope = scopes.first
@@ -189,6 +194,15 @@ module Bundler
"The options #{scopes.join " and "} were specified. Please only use one of the switches at a time."
end
end
+
+ private
+
+ def inside_app?
+ Bundler.root
+ true
+ rescue GemfileNotFound
+ false
+ end
end
end
end
diff --git a/lib/bundler/cli/console.rb b/lib/bundler/cli/console.rb
index 6e0dfe28af..2d1a2ce458 100644
--- a/lib/bundler/cli/console.rb
+++ b/lib/bundler/cli/console.rb
@@ -9,10 +9,7 @@ module Bundler
end
def run
- Bundler::SharedHelpers.major_deprecation 2, "bundle console will be replaced " \
- "by `bin/console` generated by `bundle gem <name>`"
-
- group ? Bundler.require(:default, *group.split.map!(&:to_sym)) : Bundler.require
+ group ? Bundler.require(:default, *group.split(" ").map!(&:to_sym)) : Bundler.require
ARGV.clear
console = get_console(Bundler.settings[:console] || "irb")
@@ -23,21 +20,28 @@ module Bundler
require name
get_constant(name)
rescue LoadError
- Bundler.ui.error "Couldn't load console #{name}, falling back to irb"
- require "irb"
- get_constant("irb")
+ if name == "irb"
+ if defined?(Gem::BUNDLED_GEMS) && Gem::BUNDLED_GEMS.respond_to?(:force_activate)
+ Gem::BUNDLED_GEMS.force_activate "irb"
+ require name
+ return get_constant(name)
+ end
+ Bundler.ui.error "#{name} is not available"
+ exit 1
+ else
+ Bundler.ui.error "Couldn't load console #{name}, falling back to irb"
+ name = "irb"
+ retry
+ end
end
def get_constant(name)
const_name = {
- "pry" => :Pry,
+ "pry" => :Pry,
"ripl" => :Ripl,
- "irb" => :IRB,
+ "irb" => :IRB,
}[name]
Object.const_get(const_name)
- rescue NameError
- Bundler.ui.error "Could not find constant #{const_name}"
- exit 1
end
end
end
diff --git a/lib/bundler/cli/doctor.rb b/lib/bundler/cli/doctor.rb
index fcf139ed1e..5fd6a73d91 100644
--- a/lib/bundler/cli/doctor.rb
+++ b/lib/bundler/cli/doctor.rb
@@ -1,140 +1,33 @@
# frozen_string_literal: true
-require "rbconfig"
-
module Bundler
- class CLI::Doctor
- DARWIN_REGEX = /\s+(.+) \(compatibility /.freeze
- LDD_REGEX = /\t\S+ => (\S+) \(\S+\)/.freeze
-
- attr_reader :options
-
- def initialize(options)
- @options = options
- end
-
- def otool_available?
- Bundler.which("otool")
- end
-
- def ldd_available?
- Bundler.which("ldd")
- end
-
- def dylibs_darwin(path)
- output = `/usr/bin/otool -L "#{path}"`.chomp
- dylibs = output.split("\n")[1..-1].map {|l| l.match(DARWIN_REGEX).captures[0] }.uniq
- # ignore @rpath and friends
- dylibs.reject {|dylib| dylib.start_with? "@" }
- end
-
- def dylibs_ldd(path)
- output = `/usr/bin/ldd "#{path}"`.chomp
- output.split("\n").map do |l|
- match = l.match(LDD_REGEX)
- next if match.nil?
- match.captures[0]
- end.compact
- end
-
- def dylibs(path)
- case RbConfig::CONFIG["host_os"]
- when /darwin/
- return [] unless otool_available?
- dylibs_darwin(path)
- when /(linux|solaris|bsd)/
- return [] unless ldd_available?
- dylibs_ldd(path)
- else # Windows, etc.
- Bundler.ui.warn("Dynamic library check not supported on this platform.")
- []
- end
- end
-
- def bundles_for_gem(spec)
- Dir.glob("#{spec.full_gem_path}/**/*.bundle")
- end
-
- def check!
- require_relative "check"
- Bundler::CLI::Check.new({}).run
- end
-
- def run
- Bundler.ui.level = "error" if options[:quiet]
- Bundler.settings.validate!
- check!
-
- definition = Bundler.definition
- broken_links = {}
-
- definition.specs.each do |spec|
- bundles_for_gem(spec).each do |bundle|
- bad_paths = dylibs(bundle).select {|f| !File.exist?(f) }
- if bad_paths.any?
- broken_links[spec] ||= []
- broken_links[spec].concat(bad_paths)
- end
- end
- end
-
- permissions_valid = check_home_permissions
-
- if broken_links.any?
- message = "The following gems are missing OS dependencies:"
- broken_links.map do |spec, paths|
- paths.uniq.map do |path|
- "\n * #{spec.name}: #{path}"
- end
- end.flatten.sort.each {|m| message += m }
- raise ProductionError, message
- elsif !permissions_valid
- Bundler.ui.info "No issues found with the installed bundle"
- end
- end
-
- private
-
- def check_home_permissions
- require "find"
- files_not_readable_or_writable = []
- files_not_rw_and_owned_by_different_user = []
- files_not_owned_by_current_user_but_still_rw = []
- Find.find(Bundler.bundle_path.to_s).each do |f|
- if !File.writable?(f) || !File.readable?(f)
- if File.stat(f).uid != Process.uid
- files_not_rw_and_owned_by_different_user << f
- else
- files_not_readable_or_writable << f
- end
- elsif File.stat(f).uid != Process.uid
- files_not_owned_by_current_user_but_still_rw << f
- end
- end
-
- ok = true
- if files_not_owned_by_current_user_but_still_rw.any?
- Bundler.ui.warn "Files exist in the Bundler home that are owned by another " \
- "user, but are still readable/writable. These files are:\n - #{files_not_owned_by_current_user_but_still_rw.join("\n - ")}"
-
- ok = false
- end
-
- if files_not_rw_and_owned_by_different_user.any?
- Bundler.ui.warn "Files exist in the Bundler home that are owned by another " \
- "user, and are not readable/writable. These files are:\n - #{files_not_rw_and_owned_by_different_user.join("\n - ")}"
-
- ok = false
- end
-
- if files_not_readable_or_writable.any?
- Bundler.ui.warn "Files exist in the Bundler home that are not " \
- "readable/writable by the current user. These files are:\n - #{files_not_readable_or_writable.join("\n - ")}"
-
- ok = false
- end
-
- ok
+ class CLI::Doctor < Thor
+ default_command(:diagnose)
+
+ desc "diagnose [OPTIONS]", "Checks the bundle for common problems"
+ long_desc <<-D
+ Doctor scans the OS dependencies of each of the gems requested in the Gemfile. If
+ missing dependencies are detected, Bundler prints them and exits status 1.
+ Otherwise, Bundler prints a success message and exits with a status of 0.
+ D
+ method_option "gemfile", type: :string, banner: "Use the specified gemfile instead of Gemfile"
+ method_option "quiet", type: :boolean, banner: "Only output warnings and errors."
+ method_option "ssl", type: :boolean, default: false, banner: "Diagnose SSL problems."
+ def diagnose
+ require_relative "doctor/diagnose"
+ Diagnose.new(options).run
+ end
+
+ desc "ssl [OPTIONS]", "Diagnose SSL problems"
+ long_desc <<-D
+ Diagnose SSL problems, especially related to certificates or TLS version while connecting to https://rubygems.org.
+ D
+ method_option "host", type: :string, banner: "The host to diagnose."
+ method_option "tls-version", type: :string, banner: "Specify the SSL/TLS version when running the diagnostic. Accepts either <1.1> or <1.2>"
+ method_option "verify-mode", type: :string, banner: "Specify the mode used for certification verification. Accepts either <peer> or <none>"
+ def ssl
+ require_relative "doctor/ssl"
+ SSL.new(options).run
end
end
end
diff --git a/lib/bundler/cli/doctor/diagnose.rb b/lib/bundler/cli/doctor/diagnose.rb
new file mode 100644
index 0000000000..a878025dda
--- /dev/null
+++ b/lib/bundler/cli/doctor/diagnose.rb
@@ -0,0 +1,167 @@
+# frozen_string_literal: true
+
+require "rbconfig"
+require "shellwords"
+
+module Bundler
+ class CLI::Doctor::Diagnose
+ DARWIN_REGEX = /\s+(.+) \(compatibility /
+ LDD_REGEX = /\t\S+ => (\S+) \(\S+\)/
+
+ attr_reader :options
+
+ def initialize(options)
+ @options = options
+ end
+
+ def otool_available?
+ Bundler.which("otool")
+ end
+
+ def ldd_available?
+ Bundler.which("ldd")
+ end
+
+ def dylibs_darwin(path)
+ output = `/usr/bin/otool -L #{path.shellescape}`.chomp
+ dylibs = output.split("\n")[1..-1].filter_map {|l| l.match(DARWIN_REGEX)&.match(1) }.uniq
+ # ignore @rpath and friends
+ dylibs.reject {|dylib| dylib.start_with? "@" }
+ end
+
+ def dylibs_ldd(path)
+ output = `/usr/bin/ldd #{path.shellescape}`.chomp
+ output.split("\n").filter_map do |l|
+ match = l.match(LDD_REGEX)
+ next if match.nil?
+ match.captures[0]
+ end
+ end
+
+ def dylibs(path)
+ case RbConfig::CONFIG["host_os"]
+ when /darwin/
+ return [] unless otool_available?
+ dylibs_darwin(path)
+ when /(linux|solaris|bsd)/
+ return [] unless ldd_available?
+ dylibs_ldd(path)
+ else # Windows, etc.
+ Bundler.ui.warn("Dynamic library check not supported on this platform.")
+ []
+ end
+ end
+
+ def bundles_for_gem(spec)
+ Dir.glob("#{spec.full_gem_path}/**/*.bundle")
+ end
+
+ def lookup_with_fiddle(path)
+ require "fiddle"
+ Fiddle.dlopen(path)
+ false
+ rescue Fiddle::DLError
+ true
+ end
+
+ def check!
+ require_relative "../check"
+ Bundler::CLI::Check.new({}).run
+ end
+
+ def diagnose_ssl
+ require_relative "ssl"
+ Bundler::CLI::Doctor::SSL.new({}).run
+ end
+
+ def run
+ Bundler.ui.level = "warn" if options[:quiet]
+ Bundler.settings.validate!
+ check!
+ diagnose_ssl if options[:ssl]
+
+ definition = Bundler.definition
+ broken_links = {}
+
+ definition.specs.each do |spec|
+ bundles_for_gem(spec).each do |bundle|
+ bad_paths = dylibs(bundle).select do |f|
+ lookup_with_fiddle(f)
+ end
+ if bad_paths.any?
+ broken_links[spec] ||= []
+ broken_links[spec].concat(bad_paths)
+ end
+ end
+ end
+
+ permissions_valid = check_home_permissions
+
+ if broken_links.any?
+ message = "The following gems are missing OS dependencies:"
+ broken_links.flat_map do |spec, paths|
+ paths.uniq.map do |path|
+ "\n * #{spec.name}: #{path}"
+ end
+ end.sort.each {|m| message += m }
+ raise ProductionError, message
+ elsif permissions_valid
+ Bundler.ui.info "No issues found with the installed bundle"
+ end
+ end
+
+ private
+
+ def check_home_permissions
+ require "find"
+ files_not_readable = []
+ files_not_readable_and_owned_by_different_user = []
+ files_not_owned_by_current_user_but_still_readable = []
+ broken_symlinks = []
+ Find.find(Bundler.bundle_path.to_s).each do |f|
+ if !File.exist?(f)
+ broken_symlinks << f
+ elsif !File.readable?(f)
+ if File.stat(f).uid != Process.uid
+ files_not_readable_and_owned_by_different_user << f
+ else
+ files_not_readable << f
+ end
+ elsif File.stat(f).uid != Process.uid
+ files_not_owned_by_current_user_but_still_readable << f
+ end
+ end
+
+ ok = true
+
+ if broken_symlinks.any?
+ Bundler.ui.warn "Broken links exist in the Bundler home. Please report them to the offending gem's upstream repo. These files are:\n - #{broken_symlinks.join("\n - ")}"
+
+ ok = false
+ end
+
+ if files_not_owned_by_current_user_but_still_readable.any?
+ Bundler.ui.warn "Files exist in the Bundler home that are owned by another " \
+ "user, but are still readable. These files are:\n - #{files_not_owned_by_current_user_but_still_readable.join("\n - ")}"
+
+ ok = false
+ end
+
+ if files_not_readable_and_owned_by_different_user.any?
+ Bundler.ui.warn "Files exist in the Bundler home that are owned by another " \
+ "user, and are not readable. These files are:\n - #{files_not_readable_and_owned_by_different_user.join("\n - ")}"
+
+ ok = false
+ end
+
+ if files_not_readable.any?
+ Bundler.ui.warn "Files exist in the Bundler home that are not " \
+ "readable by the current user. These files are:\n - #{files_not_readable.join("\n - ")}"
+
+ ok = false
+ end
+
+ ok
+ end
+ end
+end
diff --git a/lib/bundler/cli/doctor/ssl.rb b/lib/bundler/cli/doctor/ssl.rb
new file mode 100644
index 0000000000..21fc4edf2d
--- /dev/null
+++ b/lib/bundler/cli/doctor/ssl.rb
@@ -0,0 +1,249 @@
+# frozen_string_literal: true
+
+require "rubygems/remote_fetcher"
+require "uri"
+
+module Bundler
+ class CLI::Doctor::SSL
+ attr_reader :options
+
+ def initialize(options)
+ @options = options
+ end
+
+ def run
+ return unless openssl_installed?
+
+ output_ssl_environment
+ bundler_success = bundler_connection_successful?
+ rubygem_success = rubygem_connection_successful?
+
+ return unless net_http_connection_successful?
+
+ Explanation.summarize(bundler_success, rubygem_success, host)
+ end
+
+ private
+
+ def host
+ @options[:host] || "rubygems.org"
+ end
+
+ def tls_version
+ @options[:"tls-version"].then do |version|
+ "TLS#{version.sub(".", "_")}".to_sym if version
+ end
+ end
+
+ def verify_mode
+ mode = @options[:"verify-mode"] || :peer
+
+ @verify_mode ||= mode.then {|mod| OpenSSL::SSL.const_get("verify_#{mod}".upcase) }
+ end
+
+ def uri
+ @uri ||= URI("https://#{host}")
+ end
+
+ def openssl_installed?
+ require "openssl"
+
+ true
+ rescue LoadError
+ Bundler.ui.warn(<<~MSG)
+ Oh no! Your Ruby doesn't have OpenSSL, so it can't connect to #{host}.
+ You'll need to recompile or reinstall Ruby with OpenSSL support and try again.
+ MSG
+
+ false
+ end
+
+ def output_ssl_environment
+ Bundler.ui.info(<<~MESSAGE)
+ Here's your OpenSSL environment:
+
+ OpenSSL: #{OpenSSL::VERSION}
+ Compiled with: #{OpenSSL::OPENSSL_VERSION}
+ Loaded with: #{OpenSSL::OPENSSL_LIBRARY_VERSION}
+ MESSAGE
+ end
+
+ def bundler_connection_successful?
+ Bundler.ui.info("\nTrying connections to #{uri}:\n")
+
+ bundler_uri = Gem::URI(uri.to_s)
+ Bundler::Fetcher.new(
+ Bundler::Source::Rubygems::Remote.new(bundler_uri)
+ ).send(:connection).request(bundler_uri)
+
+ Bundler.ui.info("Bundler: success")
+
+ true
+ rescue StandardError => error
+ Bundler.ui.warn("Bundler: failed (#{Explanation.explain_bundler_or_rubygems_error(error)})")
+
+ false
+ end
+
+ def rubygem_connection_successful?
+ Gem::RemoteFetcher.fetcher.fetch_path(uri)
+ Bundler.ui.info("RubyGems: success")
+
+ true
+ rescue StandardError => error
+ Bundler.ui.warn("RubyGems: failed (#{Explanation.explain_bundler_or_rubygems_error(error)})")
+
+ false
+ end
+
+ def net_http_connection_successful?
+ ::Gem::Net::HTTP.new(uri.host, uri.port).tap do |http|
+ http.use_ssl = true
+ http.min_version = tls_version
+ http.max_version = tls_version
+ http.verify_mode = verify_mode
+ end.start
+
+ Bundler.ui.info("Ruby net/http: success")
+ warn_on_unsupported_tls12
+
+ true
+ rescue StandardError => error
+ Bundler.ui.warn(<<~MSG)
+ Ruby net/http: failed
+
+ Unfortunately, this Ruby can't connect to #{host}.
+
+ #{Explanation.explain_net_http_error(error, host, tls_version)}
+ MSG
+
+ false
+ end
+
+ def warn_on_unsupported_tls12
+ ctx = OpenSSL::SSL::SSLContext.new
+ supported = true
+
+ if ctx.respond_to?(:min_version=)
+ begin
+ ctx.min_version = ctx.max_version = OpenSSL::SSL::TLS1_2_VERSION
+ rescue OpenSSL::SSL::SSLError, NameError
+ supported = false
+ end
+ else
+ supported = OpenSSL::SSL::SSLContext::METHODS.include?(:TLSv1_2) # rubocop:disable Naming/VariableNumber
+ end
+
+ Bundler.ui.warn(<<~EOM) unless supported
+
+ WARNING: Although your Ruby can connect to #{host} today, your OpenSSL is very old!
+ WARNING: You will need to upgrade OpenSSL to use #{host}.
+
+ EOM
+ end
+
+ module Explanation
+ extend self
+
+ def explain_bundler_or_rubygems_error(error)
+ case error.message
+ when /certificate verify failed/
+ "certificate verification"
+ when /read server hello A/
+ "SSL/TLS protocol version mismatch"
+ when /tlsv1 alert protocol version/
+ "requested TLS version is too old"
+ else
+ error.message
+ end
+ end
+
+ def explain_net_http_error(error, host, tls_version)
+ case error.message
+ # Check for certificate errors
+ when /certificate verify failed/
+ <<~MSG
+ #{show_ssl_certs}
+ Your Ruby can't connect to #{host} because you are missing the certificate files OpenSSL needs to verify you are connecting to the genuine #{host} servers.
+ MSG
+ # Check for TLS version errors
+ when /read server hello A/, /tlsv1 alert protocol version/
+ if tls_version.to_s == "TLS1_3"
+ "Your Ruby can't connect to #{host} because #{tls_version} isn't supported yet.\n"
+ else
+ <<~MSG
+ Your Ruby can't connect to #{host} because your version of OpenSSL is too old.
+ You'll need to upgrade your OpenSSL install and/or recompile Ruby to use a newer OpenSSL.
+ MSG
+ end
+ # OpenSSL doesn't support TLS version specified by argument
+ when /unknown SSL method/
+ "Your Ruby can't connect because #{tls_version} isn't supported by your version of OpenSSL."
+ else
+ <<~MSG
+ Even worse, we're not sure why.
+
+ Here's the full error information:
+ #{error.class}: #{error.message}
+ #{error.backtrace.join("\n ")}
+
+ You might have more luck using Mislav's SSL doctor.rb script. You can get it here:
+ https://github.com/mislav/ssl-tools/blob/8b3dec4/doctor.rb
+
+ Read more about the script and how to use it in this blog post:
+ https://mislav.net/2013/07/ruby-openssl/
+ MSG
+ end
+ end
+
+ def summarize(bundler_success, rubygems_success, host)
+ guide_url = "http://ruby.to/ssl-check-failed"
+
+ message = if bundler_success && rubygems_success
+ <<~MSG
+ Hooray! This Ruby can connect to #{host}.
+ You are all set to use Bundler and RubyGems.
+
+ MSG
+ elsif !bundler_success && !rubygems_success
+ <<~MSG
+ For some reason, your Ruby installation can connect to #{host}, but neither RubyGems nor Bundler can.
+ The most likely fix is to manually upgrade RubyGems by following the instructions at #{guide_url}.
+ After you've done that, run `gem install bundler` to upgrade Bundler, and then run this script again to make sure everything worked. ❣
+
+ MSG
+ elsif !bundler_success
+ <<~MSG
+ Although your Ruby installation and RubyGems can both connect to #{host}, Bundler is having trouble.
+ The most likely way to fix this is to upgrade Bundler by running `gem install bundler`.
+ Run this script again after doing that to make sure everything is all set.
+ If you're still having trouble, check out the troubleshooting guide at #{guide_url}.
+
+ MSG
+ else
+ <<~MSG
+ It looks like Ruby and Bundler can connect to #{host}, but RubyGems itself cannot.
+ You can likely solve this by manually downloading and installing a RubyGems update.
+ Visit #{guide_url} for instructions on how to manually upgrade RubyGems.
+
+ MSG
+ end
+
+ Bundler.ui.info("\n#{message}")
+ end
+
+ private
+
+ def show_ssl_certs
+ ssl_cert_file = ENV["SSL_CERT_FILE"] || OpenSSL::X509::DEFAULT_CERT_FILE
+ ssl_cert_dir = ENV["SSL_CERT_DIR"] || OpenSSL::X509::DEFAULT_CERT_DIR
+
+ <<~MSG
+ Below affect only Ruby net/http connections:
+ SSL_CERT_FILE: #{File.exist?(ssl_cert_file) ? "exists #{ssl_cert_file}" : "is missing #{ssl_cert_file}"}
+ SSL_CERT_DIR: #{Dir.exist?(ssl_cert_dir) ? "exists #{ssl_cert_dir}" : "is missing #{ssl_cert_dir}"}
+ MSG
+ end
+ end
+ end
+end
diff --git a/lib/bundler/cli/exec.rb b/lib/bundler/cli/exec.rb
index 0a1edbdbbd..2fdc416286 100644
--- a/lib/bundler/cli/exec.rb
+++ b/lib/bundler/cli/exec.rb
@@ -12,29 +12,27 @@ module Bundler
@options = options
@cmd = args.shift
@args = args
-
- if !Bundler.current_ruby.jruby?
- @args << { :close_others => !options.keep_file_descriptors? }
- elsif options.keep_file_descriptors?
- Bundler.ui.warn "Ruby version #{RUBY_VERSION} defaults to keeping non-standard file descriptors on Kernel#exec."
- end
+ @args << { close_others: !options.keep_file_descriptors? } unless Bundler.current_ruby.jruby?
end
def run
validate_cmd!
SharedHelpers.set_bundle_environment
if bin_path = Bundler.which(cmd)
- if !Bundler.settings[:disable_exec_load] && ruby_shebang?(bin_path)
- return kernel_load(bin_path, *args)
+ if !Bundler.settings[:disable_exec_load] && directly_loadable?(bin_path)
+ bin_path.delete_suffix!(".bat") if Gem.win_platform?
+ kernel_load(bin_path, *args)
+ else
+ bin_path = "./" + bin_path unless File.absolute_path?(bin_path)
+ kernel_exec(bin_path, *args)
end
- kernel_exec(bin_path, *args)
else
# exec using the given command
kernel_exec(cmd, *args)
end
end
- private
+ private
def validate_cmd!
return unless cmd.nil?
@@ -63,16 +61,39 @@ module Bundler
Kernel.load(file)
rescue SystemExit, SignalException
raise
- rescue Exception => e # rubocop:disable Lint/RescueException
+ rescue Exception # rubocop:disable Lint/RescueException
Bundler.ui.error "bundler: failed to load command: #{cmd} (#{file})"
- backtrace = e.backtrace ? e.backtrace.take_while {|bt| !bt.start_with?(__FILE__) } : []
- abort "#{e.class}: #{e.message}\n #{backtrace.join("\n ")}"
+ Bundler::FriendlyErrors.disable!
+ raise
end
def process_title(file, args)
"#{file} #{args.join(" ")}".strip
end
+ def directly_loadable?(file)
+ if Gem.win_platform?
+ script_wrapper?(file)
+ else
+ ruby_shebang?(file)
+ end
+ end
+
+ def script_wrapper?(file)
+ script_file = file.delete_suffix(".bat")
+ return false unless File.exist?(script_file)
+
+ if File.zero?(script_file)
+ Bundler.ui.warn "#{script_file} is empty"
+ return false
+ end
+
+ header = File.open(file, "r") {|f| f.read(32) }
+ ruby_exe = "#{RbConfig::CONFIG["RUBY_INSTALL_NAME"]}#{RbConfig::CONFIG["EXEEXT"]}"
+ ruby_exe = "ruby.exe" if ruby_exe.empty?
+ header.include?(ruby_exe)
+ end
+
def ruby_shebang?(file)
possibilities = [
"#!/usr/bin/env ruby\n",
diff --git a/lib/bundler/cli/fund.rb b/lib/bundler/cli/fund.rb
new file mode 100644
index 0000000000..ad7f31f3d6
--- /dev/null
+++ b/lib/bundler/cli/fund.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module Bundler
+ class CLI::Fund
+ attr_reader :options
+
+ def initialize(options)
+ @options = options
+ end
+
+ def run
+ Bundler.definition.validate_runtime!
+
+ groups = Array(options[:group]).map(&:to_sym)
+
+ deps = if groups.any?
+ Bundler.definition.dependencies_for(groups)
+ else
+ Bundler.definition.requested_dependencies
+ end
+
+ fund_info = deps.each_with_object([]) do |dep, arr|
+ spec = Bundler.definition.specs[dep.name].first
+ if spec.metadata.key?("funding_uri")
+ arr << "* #{spec.name} (#{spec.version})\n Funding: #{spec.metadata["funding_uri"]}"
+ end
+ end
+
+ if fund_info.empty?
+ Bundler.ui.info "None of the installed gems you directly depend on are looking for funding."
+ else
+ Bundler.ui.info fund_info.join("\n")
+ end
+ end
+ end
+end
diff --git a/lib/bundler/cli/gem.rb b/lib/bundler/cli/gem.rb
index d3e5831759..c8c24c8e66 100644
--- a/lib/bundler/cli/gem.rb
+++ b/lib/bundler/cli/gem.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require "pathname"
-
module Bundler
class CLI
Bundler.require_thor_actions
@@ -9,12 +7,9 @@ module Bundler
end
class CLI::Gem
- TEST_FRAMEWORK_VERSIONS = {
- "rspec" => "3.0",
- "minitest" => "5.0",
- }.freeze
+ DEFAULT_GITHUB_USERNAME = "[USERNAME]"
- attr_reader :options, :gem_name, :thor, :name, :target
+ attr_reader :options, :gem_name, :thor, :name, :target, :extension
def initialize(options, gem_name, thor)
@options = options
@@ -25,9 +20,11 @@ module Bundler
thor.destination_root = nil
@name = @gem_name
- @target = SharedHelpers.pwd.join(gem_name)
+ @target = Pathname.new(SharedHelpers.pwd).join(gem_name)
+
+ @extension = options[:ext]
- validate_ext_name if options[:ext]
+ validate_ext_name if @extension
end
def run
@@ -37,34 +34,56 @@ module Bundler
namespaced_path = name.tr("-", "/")
constant_name = name.gsub(/-[_-]*(?![_-]|$)/) { "::" }.gsub(/([_-]+|(::)|^)(.|$)/) { $2.to_s + $3.upcase }
constant_array = constant_name.split("::")
-
- git_installed = Bundler.git_present?
-
- git_author_name = git_installed ? `git config user.name`.chomp : ""
- github_username = git_installed ? `git config github.user`.chomp : ""
- git_user_email = git_installed ? `git config user.email`.chomp : ""
+ minitest_constant_name = constant_array.clone.tap {|a| a[-1] = "Test#{a[-1]}" }.join("::") # Foo::Bar => Foo::TestBar
+
+ use_git = Bundler.git_present? && options[:git]
+
+ git_author_name = use_git ? `git config user.name`.chomp : ""
+ git_username = use_git ? `git config github.user`.chomp : ""
+ git_user_email = use_git ? `git config user.email`.chomp : ""
+ github_username = github_username(git_username)
+
+ if github_username.empty?
+ homepage_uri = "TODO: Put your gem's website or public repo URL here."
+ source_code_uri = "TODO: Put your gem's public repo URL here."
+ changelog_uri = "TODO: Put your gem's CHANGELOG.md URL here."
+ else
+ homepage_uri = "https://github.com/#{github_username}/#{name}"
+ source_code_uri = "https://github.com/#{github_username}/#{name}"
+ changelog_uri = "https://github.com/#{github_username}/#{name}/blob/main/CHANGELOG.md"
+ end
config = {
- :name => name,
- :underscored_name => underscored_name,
- :namespaced_path => namespaced_path,
- :makefile_path => "#{underscored_name}/#{underscored_name}",
- :constant_name => constant_name,
- :constant_array => constant_array,
- :author => git_author_name.empty? ? "TODO: Write your name" : git_author_name,
- :email => git_user_email.empty? ? "TODO: Write your email address" : git_user_email,
- :test => options[:test],
- :ext => options[:ext],
- :exe => options[:exe],
- :bundler_version => bundler_dependency_version,
- :github_username => github_username.empty? ? "[USERNAME]" : github_username,
+ name: name,
+ underscored_name: underscored_name,
+ namespaced_path: namespaced_path,
+ makefile_path: "#{underscored_name}/#{underscored_name}",
+ constant_name: constant_name,
+ constant_array: constant_array,
+ author: git_author_name.empty? ? "TODO: Write your name" : git_author_name,
+ email: git_user_email.empty? ? "TODO: Write your email address" : git_user_email,
+ test: options[:test],
+ ext: extension,
+ exe: options[:exe],
+ bundle: options[:bundle],
+ bundler_version: bundler_dependency_version,
+ git: use_git,
+ github_username: github_username.empty? ? DEFAULT_GITHUB_USERNAME : github_username,
+ required_ruby_version: required_ruby_version,
+ rust_builder_required_rubygems_version: rust_builder_required_rubygems_version,
+ minitest_constant_name: minitest_constant_name,
+ ignore_paths: %w[bin/],
+ homepage_uri: homepage_uri,
+ source_code_uri: source_code_uri,
+ changelog_uri: changelog_uri,
}
ensure_safe_gem_name(name, constant_array)
templates = {
- "Gemfile.tt" => "Gemfile",
+ "Gemfile.tt" => Bundler.preferred_gemfile_name,
"lib/newgem.rb.tt" => "lib/#{namespaced_path}.rb",
"lib/newgem/version.rb.tt" => "lib/#{namespaced_path}/version.rb",
+ "sig/newgem.rbs.tt" => "sig/#{namespaced_path}.rbs",
"newgem.gemspec.tt" => "#{name}.gemspec",
"Rakefile.tt" => "Rakefile",
"README.md.tt" => "README.md",
@@ -77,13 +96,21 @@ module Bundler
bin/setup
]
- templates.merge!("gitignore.tt" => ".gitignore") if Bundler.git_present?
+ case Bundler.preferred_gemfile_name
+ when "Gemfile"
+ config[:ignore_paths] << "Gemfile"
+ when "gems.rb"
+ config[:ignore_paths] << "gems.rb"
+ config[:ignore_paths] << "gems.locked"
+ end
+
+ if use_git
+ templates.merge!("gitignore.tt" => ".gitignore")
+ config[:ignore_paths] << ".gitignore"
+ end
if test_framework = ask_and_set_test_framework
config[:test] = test_framework
- config[:test_framework_version] = TEST_FRAMEWORK_VERSIONS[test_framework]
-
- templates.merge!("travis.yml.tt" => ".travis.yml")
case test_framework
when "rspec"
@@ -92,20 +119,54 @@ module Bundler
"spec/spec_helper.rb.tt" => "spec/spec_helper.rb",
"spec/newgem_spec.rb.tt" => "spec/#{namespaced_path}_spec.rb"
)
+ config[:test_task] = :spec
+ config[:ignore_paths] << ".rspec"
+ config[:ignore_paths] << "spec/"
when "minitest"
+ # Generate path for minitest target file (FileList["test/**/test_*.rb"])
+ # foo => test/test_foo.rb
+ # foo-bar => test/foo/test_bar.rb
+ # foo_bar => test/test_foo_bar.rb
+ paths = namespaced_path.rpartition("/")
+ paths[2] = "test_#{paths[2]}"
+ minitest_namespaced_path = paths.join("")
+
templates.merge!(
- "test/test_helper.rb.tt" => "test/test_helper.rb",
- "test/newgem_test.rb.tt" => "test/#{namespaced_path}_test.rb"
+ "test/minitest/test_helper.rb.tt" => "test/test_helper.rb",
+ "test/minitest/test_newgem.rb.tt" => "test/#{minitest_namespaced_path}.rb"
)
+ config[:test_task] = :test
+ config[:ignore_paths] << "test/"
+ when "test-unit"
+ templates.merge!(
+ "test/test-unit/test_helper.rb.tt" => "test/test_helper.rb",
+ "test/test-unit/newgem_test.rb.tt" => "test/#{namespaced_path}_test.rb"
+ )
+ config[:test_task] = :test
+ config[:ignore_paths] << "test/"
end
end
- config[:test_task] = config[:test] == "minitest" ? "test" : "spec"
+ config[:ci] = ask_and_set_ci
+ case config[:ci]
+ when "github"
+ templates.merge!("github/workflows/main.yml.tt" => ".github/workflows/main.yml")
+ if extension == "rust"
+ templates.merge!("github/workflows/build-gems.yml.tt" => ".github/workflows/build-gems.yml")
+ end
+ config[:ignore_paths] << ".github/"
+ when "gitlab"
+ templates.merge!("gitlab-ci.yml.tt" => ".gitlab-ci.yml")
+ config[:ignore_paths] << ".gitlab-ci.yml"
+ when "circle"
+ templates.merge!("circleci/config.yml.tt" => ".circleci/config.yml")
+ config[:ignore_paths] << ".circleci/"
+ end
if ask_and_set(:mit, "Do you want to license your code permissively under the MIT license?",
- "This means that any other developer or company will be legally allowed to use your code " \
- "for free as long as they admit you created it. You can read more about the MIT license " \
- "at https://choosealicense.com/licenses/mit.")
+ "Using a MIT license means that any other developer or company will be legally allowed " \
+ "to use your code for free as long as they admit you created it. You can read more about " \
+ "the MIT license at https://choosealicense.com/licenses/mit.")
config[:mit] = true
Bundler.ui.info "MIT License enabled in config"
templates.merge!("LICENSE.txt.tt" => "LICENSE.txt")
@@ -113,71 +174,127 @@ module Bundler
if ask_and_set(:coc, "Do you want to include a code of conduct in gems you generate?",
"Codes of conduct can increase contributions to your project by contributors who " \
- "prefer collaborative, safe spaces. You can read more about the code of conduct at " \
- "contributor-covenant.org. Having a code of conduct means agreeing to the responsibility " \
- "of enforcing it, so be sure that you are prepared to do that. Be sure that your email " \
- "address is specified as a contact in the generated code of conduct so that people know " \
- "who to contact in case of a violation. For suggestions about " \
- "how to enforce codes of conduct, see https://bit.ly/coc-enforcement.")
+ "prefer safe, respectful, productive, and collaborative spaces. \n" \
+ "See https://github.com/ruby/rubygems/blob/master/CODE_OF_CONDUCT.md")
config[:coc] = true
Bundler.ui.info "Code of conduct enabled in config"
templates.merge!("CODE_OF_CONDUCT.md.tt" => "CODE_OF_CONDUCT.md")
end
- templates.merge!("exe/newgem.tt" => "exe/#{name}") if config[:exe]
+ if ask_and_set(:changelog, "Do you want to include a changelog?",
+ "A changelog is a file which contains a curated, chronologically ordered list of notable " \
+ "changes for each version of a project. To make it easier for users and contributors to" \
+ " see precisely what notable changes have been made between each release (or version) of" \
+ " the project. Whether consumers or developers, the end users of software are" \
+ " human beings who care about what's in the software. When the software changes, people " \
+ "want to know why and how. see https://keepachangelog.com")
+ config[:changelog] = true
+ Bundler.ui.info "Changelog enabled in config"
+ templates.merge!("CHANGELOG.md.tt" => "CHANGELOG.md")
+ end
+
+ config[:linter] = ask_and_set_linter
+ case config[:linter]
+ when "rubocop"
+ Bundler.ui.info "RuboCop enabled in config"
+ templates.merge!("rubocop.yml.tt" => ".rubocop.yml")
+ config[:ignore_paths] << ".rubocop.yml"
+ when "standard"
+ Bundler.ui.info "Standard enabled in config"
+ templates.merge!("standard.yml.tt" => ".standard.yml")
+ config[:ignore_paths] << ".standard.yml"
+ end
- if options[:ext]
+ if config[:exe]
+ templates.merge!("exe/newgem.tt" => "exe/#{name}")
+ executables.push("exe/#{name}")
+ end
+
+ if extension == "c"
templates.merge!(
- "ext/newgem/extconf.rb.tt" => "ext/#{name}/extconf.rb",
+ "ext/newgem/extconf-c.rb.tt" => "ext/#{name}/extconf.rb",
"ext/newgem/newgem.h.tt" => "ext/#{name}/#{underscored_name}.h",
"ext/newgem/newgem.c.tt" => "ext/#{name}/#{underscored_name}.c"
)
end
+ if extension == "rust"
+ templates.merge!(
+ "Cargo.toml.tt" => "Cargo.toml",
+ "ext/newgem/Cargo.toml.tt" => "ext/#{name}/Cargo.toml",
+ "ext/newgem/build.rs.tt" => "ext/#{name}/build.rs",
+ "ext/newgem/extconf-rust.rb.tt" => "ext/#{name}/extconf.rb",
+ "ext/newgem/src/lib.rs.tt" => "ext/#{name}/src/lib.rs",
+ )
+ end
+
+ if extension == "go"
+ templates.merge!(
+ "ext/newgem/go.mod.tt" => "ext/#{name}/go.mod",
+ "ext/newgem/extconf-go.rb.tt" => "ext/#{name}/extconf.rb",
+ "ext/newgem/newgem.h.tt" => "ext/#{name}/#{underscored_name}.h",
+ "ext/newgem/newgem.go.tt" => "ext/#{name}/#{underscored_name}.go",
+ "ext/newgem/newgem-go.c.tt" => "ext/#{name}/#{underscored_name}.c",
+ )
+
+ config[:go_module_username] = config[:github_username] == DEFAULT_GITHUB_USERNAME ? "username" : config[:github_username]
+ end
+
+ if target.exist? && !target.directory?
+ Bundler.ui.error "Couldn't create a new gem named `#{gem_name}` because there's an existing file named `#{gem_name}`."
+ exit Bundler::BundlerError.all_errors[Bundler::GenericSystemCallError]
+ end
+
+ if use_git
+ Bundler.ui.info "\nInitializing git repo in #{target}"
+ require "shellwords"
+ `git init #{target.to_s.shellescape}`
+
+ config[:git_default_branch] = File.read("#{target}/.git/HEAD").split("/").last.chomp
+ end
+
templates.each do |src, dst|
destination = target.join(dst)
- SharedHelpers.filesystem_access(destination) do
- thor.template("newgem/#{src}", destination, config)
- end
+ thor.template("newgem/#{src}", destination, config)
end
executables.each do |file|
- SharedHelpers.filesystem_access(target.join(file)) do |path|
- executable = (path.stat.mode | 0o111)
- path.chmod(executable)
- end
+ path = target.join(file)
+ executable = (path.stat.mode | 0o111)
+ path.chmod(executable)
+ end
+
+ if use_git
+ IO.popen(%w[git add .], { chdir: target }, &:read)
end
- if Bundler.git_present? && options[:git]
- Bundler.ui.info "Initializing git repo in #{target}"
+ if config[:bundle]
+ Bundler.ui.info "Running bundle install in the new gem directory."
Dir.chdir(target) do
- `git init`
- `git add .`
+ system("bundle install")
end
end
# Open gemspec in editor
open_editor(options["edit"], target.join("#{name}.gemspec")) if options[:edit]
- Bundler.ui.info "Gem '#{name}' was successfully created. " \
- "For more information on making a RubyGem visit https://bundler.io/guides/creating_gem.html"
- rescue Errno::EEXIST => e
- raise GenericSystemCallError.new(e, "There was a conflict while creating the new gem.")
+ Bundler.ui.info "\nGem '#{name}' was successfully created. " \
+ "For more information on making a RubyGem visit https://guides.rubygems.org/make-your-own-gem/"
end
- private
+ private
def resolve_name(name)
- SharedHelpers.pwd.join(name).basename.to_s
+ Pathname.new(SharedHelpers.pwd).join(name).basename.to_s
end
- def ask_and_set(key, header, message)
+ def ask_and_set(key, prompt, explanation)
choice = options[key]
choice = Bundler.settings["gem.#{key}"] if choice.nil?
if choice.nil?
- Bundler.ui.confirm header
- choice = Bundler.ui.yes? "#{message} y/(n):"
+ Bundler.ui.info "\n#{explanation}"
+ choice = Bundler.ui.yes? "#{prompt} y/(n):"
Bundler.settings.set_global("gem.#{key}", choice)
end
@@ -195,13 +312,15 @@ module Bundler
end
def ask_and_set_test_framework
+ return if skip?(:test)
test_framework = options[:test] || Bundler.settings["gem.test"]
- if test_framework.nil?
- Bundler.ui.confirm "Do you want to generate tests with your gem?"
- result = Bundler.ui.ask "Type 'rspec' or 'minitest' to generate those test files now and " \
- "in the future. rspec/minitest/(none):"
- if result =~ /rspec|minitest/
+ if test_framework.to_s.empty?
+ Bundler.ui.info "\nDo you want to generate tests with your gem?"
+ Bundler.ui.info hint_text("test")
+
+ result = Bundler.ui.ask "Enter a test framework. rspec/minitest/test-unit/(none):"
+ if /rspec|minitest|test-unit/.match?(result)
test_framework = result
else
test_framework = false
@@ -212,9 +331,92 @@ module Bundler
Bundler.settings.set_global("gem.test", test_framework)
end
+ if options[:test] == Bundler.settings["gem.test"]
+ Bundler.ui.info "#{options[:test]} is already configured, ignoring --test flag."
+ end
+
test_framework
end
+ def skip?(option)
+ options.key?(option) && options[option].nil?
+ end
+
+ def hint_text(setting)
+ if Bundler.settings["gem.#{setting}"] == false
+ "Your choice will only be applied to this gem."
+ else
+ "Future `bundle gem` calls will use your choice. " \
+ "This setting can be changed anytime with `bundle config gem.#{setting}`."
+ end
+ end
+
+ def ask_and_set_ci
+ return if skip?(:ci)
+ ci_template = options[:ci] || Bundler.settings["gem.ci"]
+
+ if ci_template.to_s.empty?
+ Bundler.ui.info "\nDo you want to set up continuous integration for your gem? " \
+ "Supported services:\n" \
+ "* CircleCI: https://circleci.com/\n" \
+ "* GitHub Actions: https://github.com/features/actions\n" \
+ "* GitLab CI: https://docs.gitlab.com/ee/ci/\n"
+ Bundler.ui.info hint_text("ci")
+
+ result = Bundler.ui.ask "Enter a CI service. github/gitlab/circle/(none):"
+ if /github|gitlab|circle/.match?(result)
+ ci_template = result
+ else
+ ci_template = false
+ end
+ end
+
+ if Bundler.settings["gem.ci"].nil?
+ Bundler.settings.set_global("gem.ci", ci_template)
+ end
+
+ if options[:ci] == Bundler.settings["gem.ci"]
+ Bundler.ui.info "#{options[:ci]} is already configured, ignoring --ci flag."
+ end
+
+ ci_template
+ end
+
+ def ask_and_set_linter
+ return if skip?(:linter)
+ linter_template = options[:linter] || Bundler.settings["gem.linter"]
+
+ if linter_template.to_s.empty?
+ Bundler.ui.info "\nDo you want to add a code linter and formatter to your gem? " \
+ "Supported Linters:\n" \
+ "* RuboCop: https://rubocop.org\n" \
+ "* Standard: https://github.com/standardrb/standard\n"
+ Bundler.ui.info hint_text("linter")
+
+ result = Bundler.ui.ask "Enter a linter. rubocop/standard/(none):"
+ if /rubocop|standard/.match?(result)
+ linter_template = result
+ else
+ linter_template = false
+ end
+ end
+
+ if Bundler.settings["gem.linter"].nil?
+ Bundler.settings.set_global("gem.linter", linter_template)
+ end
+
+ # Once gem.linter safely set, unset the deprecated gem.rubocop
+ unless Bundler.settings["gem.rubocop"].nil?
+ Bundler.settings.set_global("gem.rubocop", nil)
+ end
+
+ if options[:linter] == Bundler.settings["gem.linter"]
+ Bundler.ui.info "#{options[:linter]} is already configured, ignoring --linter flag."
+ end
+
+ linter_template
+ end
+
def bundler_dependency_version
v = Gem::Version.new(Bundler::VERSION)
req = v.segments[0..1]
@@ -223,11 +425,15 @@ module Bundler
end
def ensure_safe_gem_name(name, constant_array)
- if name =~ /^\d/
+ if /^\d/.match?(name)
Bundler.ui.error "Invalid gem name #{name} Please give a name which does not start with numbers."
exit 1
end
+ if /[A-Z]/.match?(name)
+ Bundler.ui.warn "Gem names with capital letters are not recommended. Please use only lowercase letters, numbers, and hyphens."
+ end
+
constant_name = constant_array.join("::")
existing_constant = constant_array.inject(Object) do |c, s|
@@ -248,5 +454,23 @@ module Bundler
def open_editor(editor, file)
thor.run(%(#{editor} "#{file}"))
end
+
+ def rust_builder_required_rubygems_version
+ "3.3.11"
+ end
+
+ def required_ruby_version
+ "3.2.0"
+ end
+
+ def github_username(git_username)
+ if options[:github_username].nil?
+ git_username
+ elsif options[:github_username] == false
+ ""
+ else
+ options[:github_username]
+ end
+ end
end
end
diff --git a/lib/bundler/cli/info.rb b/lib/bundler/cli/info.rb
index 4733675e8c..cd01d4949b 100644
--- a/lib/bundler/cli/info.rb
+++ b/lib/bundler/cli/info.rb
@@ -18,45 +18,66 @@ module Bundler
if spec
return print_gem_path(spec) if @options[:path]
+ return print_gem_version(spec) if @options[:version]
print_gem_info(spec)
end
end
- private
+ private
- def spec_for_gem(gem_name)
- spec = Bundler.definition.specs.find {|s| s.name == gem_name }
- spec || default_gem_spec(gem_name) || Bundler::CLI::Common.select_spec(gem_name, :regex_match)
+ def spec_for_gem(name)
+ Bundler::CLI::Common.select_spec(name, :regex_match)
end
- def default_gem_spec(gem_name)
- return unless Gem::Specification.respond_to?(:find_all_by_name)
- gem_spec = Gem::Specification.find_all_by_name(gem_name).last
- return gem_spec if gem_spec && gem_spec.respond_to?(:default_gem?) && gem_spec.default_gem?
- end
-
- def spec_not_found(gem_name)
- raise GemNotFound, Bundler::CLI::Common.gem_not_found_message(gem_name, Bundler.definition.dependencies)
+ def print_gem_version(spec)
+ Bundler.ui.info spec.version.to_s
end
def print_gem_path(spec)
- path = if spec.name == "bundler"
- File.expand_path("../../../..", __FILE__)
+ name = spec.name
+ if name == "bundler"
+ path = File.expand_path("../../..", __dir__)
else
- spec.full_gem_path
+ path = spec.full_gem_path
+ if spec.installation_missing?
+ return Bundler.ui.warn "The gem #{name} is missing. It should be installed at #{path}, but was not found"
+ end
end
Bundler.ui.info path
end
def print_gem_info(spec)
+ metadata = spec.metadata
+ name = spec.name
gem_info = String.new
- gem_info << " * #{spec.name} (#{spec.version}#{spec.git_version})\n"
+ gem_info << " * #{name} (#{spec.version}#{spec.git_version})\n"
gem_info << "\tSummary: #{spec.summary}\n" if spec.summary
gem_info << "\tHomepage: #{spec.homepage}\n" if spec.homepage
+ gem_info << "\tDocumentation: #{metadata["documentation_uri"]}\n" if metadata.key?("documentation_uri")
+ gem_info << "\tSource Code: #{metadata["source_code_uri"]}\n" if metadata.key?("source_code_uri")
+ gem_info << "\tFunding: #{metadata["funding_uri"]}\n" if metadata.key?("funding_uri")
+ gem_info << "\tWiki: #{metadata["wiki_uri"]}\n" if metadata.key?("wiki_uri")
+ gem_info << "\tChangelog: #{metadata["changelog_uri"]}\n" if metadata.key?("changelog_uri")
+ gem_info << "\tBug Tracker: #{metadata["bug_tracker_uri"]}\n" if metadata.key?("bug_tracker_uri")
+ gem_info << "\tMailing List: #{metadata["mailing_list_uri"]}\n" if metadata.key?("mailing_list_uri")
gem_info << "\tPath: #{spec.full_gem_path}\n"
- gem_info << "\tDefault Gem: yes" if spec.respond_to?(:default_gem?) && spec.default_gem?
+ gem_info << "\tDefault Gem: yes\n" if spec.respond_to?(:default_gem?) && spec.default_gem?
+ gem_info << "\tReverse Dependencies: \n\t\t#{gem_dependencies.join("\n\t\t")}" if gem_dependencies.any?
+
+ if name != "bundler" && spec.installation_missing?
+ return Bundler.ui.warn "The gem #{name} is missing. Gemspec information is still available though:\n#{gem_info}"
+ end
+
Bundler.ui.info gem_info
end
+
+ def gem_dependencies
+ @gem_dependencies ||= Bundler.definition.specs.filter_map do |spec|
+ dependency = spec.dependencies.find {|dep| dep.name == gem_name }
+ next unless dependency
+ "#{spec.name} (#{spec.version}) depends on #{gem_name} (#{dependency.requirements_list.join(", ")})"
+ end.sort
+ end
end
end
diff --git a/lib/bundler/cli/init.rb b/lib/bundler/cli/init.rb
index 65dd08dfe9..246b9d6460 100644
--- a/lib/bundler/cli/init.rb
+++ b/lib/bundler/cli/init.rb
@@ -32,16 +32,20 @@ module Bundler
file << spec.to_gemfile
end
else
- FileUtils.cp(File.expand_path("../../templates/#{gemfile}", __FILE__), gemfile)
+ File.open(File.expand_path("../templates/Gemfile", __dir__), "r") do |template|
+ File.open(gemfile, "wb") do |destination|
+ IO.copy_stream(template, destination)
+ end
+ end
end
puts "Writing new #{gemfile} to #{SharedHelpers.pwd}/#{gemfile}"
end
- private
+ private
def gemfile
- @gemfile ||= Bundler.settings[:init_gems_rb] ? "gems.rb" : "Gemfile"
+ @gemfile ||= options[:gemfile] || Bundler.preferred_gemfile_name
end
end
end
diff --git a/lib/bundler/cli/inject.rb b/lib/bundler/cli/inject.rb
deleted file mode 100644
index b00675d348..0000000000
--- a/lib/bundler/cli/inject.rb
+++ /dev/null
@@ -1,60 +0,0 @@
-# frozen_string_literal: true
-
-module Bundler
- class CLI::Inject
- attr_reader :options, :name, :version, :group, :source, :gems
- def initialize(options, name, version)
- @options = options
- @name = name
- @version = version || last_version_number
- @group = options[:group].split(",") unless options[:group].nil?
- @source = options[:source]
- @gems = []
- end
-
- def run
- # The required arguments allow Thor to give useful feedback when the arguments
- # are incorrect. This adds those first two arguments onto the list as a whole.
- gems.unshift(source).unshift(group).unshift(version).unshift(name)
-
- # Build an array of Dependency objects out of the arguments
- deps = []
- # when `inject` support addition of more than one gem, then this loop will
- # help. Currently this loop is running once.
- gems.each_slice(4) do |gem_name, gem_version, gem_group, gem_source|
- ops = Gem::Requirement::OPS.map {|key, _val| key }
- has_op = ops.any? {|op| gem_version.start_with? op }
- gem_version = "~> #{gem_version}" unless has_op
- deps << Bundler::Dependency.new(gem_name, gem_version, "group" => gem_group, "source" => gem_source)
- end
-
- added = Injector.inject(deps, options)
-
- if added.any?
- Bundler.ui.confirm "Added to Gemfile:"
- Bundler.ui.confirm(added.map do |d|
- name = "'#{d.name}'"
- requirement = ", '#{d.requirement}'"
- group = ", :group => #{d.groups.inspect}" if d.groups != Array(:default)
- source = ", :source => '#{d.source}'" unless d.source.nil?
- %(gem #{name}#{requirement}#{group}#{source})
- end.join("\n"))
- else
- Bundler.ui.confirm "All gems were already present in the Gemfile"
- end
- end
-
- private
-
- def last_version_number
- definition = Bundler.definition(true)
- definition.resolve_remotely!
- specs = definition.index[name].sort_by(&:version)
- unless options[:pre]
- specs.delete_if {|b| b.respond_to?(:version) && b.version.prerelease? }
- end
- spec = specs.last
- spec.version.to_s
- end
- end
-end
diff --git a/lib/bundler/cli/install.rb b/lib/bundler/cli/install.rb
index d823fb632f..67feba84bd 100644
--- a/lib/bundler/cli/install.rb
+++ b/lib/bundler/cli/install.rb
@@ -8,62 +8,50 @@ module Bundler
end
def run
- Bundler.ui.level = "error" if options[:quiet]
+ Bundler.ui.level = "warn" if options[:quiet]
warn_if_root
- normalize_groups
-
- Bundler::SharedHelpers.set_env "RB_USER_INSTALL", "1" if Bundler::FREEBSD
+ if options[:local]
+ Bundler.self_manager.restart_with_locked_bundler_if_needed
+ else
+ Bundler.self_manager.install_locked_bundler_and_restart_with_it_if_needed
+ end
- # Disable color in deployment mode
- Bundler.ui.shell = Thor::Shell::Basic.new if options[:deployment]
+ Bundler::SharedHelpers.set_env "RB_USER_INSTALL", "1" if Gem.freebsd_platform?
- check_for_options_conflicts
+ if target_rbconfig_path = options[:"target-rbconfig"]
+ Bundler.rubygems.set_target_rbconfig(target_rbconfig_path)
+ end
check_trust_policy
- if options[:deployment] || options[:frozen] || Bundler.frozen_bundle?
- unless Bundler.default_lockfile.exist?
- flag = "--deployment flag" if options[:deployment]
- flag ||= "--frozen flag" if options[:frozen]
- flag ||= "deployment setting"
- raise ProductionError, "The #{flag} requires a #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)}. Please make " \
- "sure you have checked your #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)} into version control " \
- "before deploying."
- end
-
- options[:local] = true if Bundler.app_cache.exist?
-
- if Bundler.feature_flag.deployment_means_frozen?
- Bundler.settings.set_command_option :deployment, true
- else
- Bundler.settings.set_command_option :frozen, true
- end
- end
-
- # When install is called with --no-deployment, disable deployment mode
- if options[:deployment] == false
- Bundler.settings.set_command_option :frozen, nil
- options[:system] = true
+ if Bundler.frozen_bundle? && !Bundler.default_lockfile.exist?
+ flag = "deployment setting" if Bundler.settings[:deployment]
+ flag = "frozen setting" if Bundler.settings[:frozen]
+ raise ProductionError, "The #{flag} requires a lockfile. Please make " \
+ "sure you have checked your #{SharedHelpers.relative_lockfile_path} into version control " \
+ "before deploying."
end
normalize_settings
Bundler::Fetcher.disable_endpoint = options["full-index"]
- if options["binstubs"]
- Bundler::SharedHelpers.major_deprecation 2,
- "The --binstubs option will be removed in favor of `bundle binstubs`"
- end
-
- Plugin.gemfile_install(Bundler.default_gemfile) if Bundler.feature_flag.plugins?
+ Plugin.gemfile_install(Bundler.default_gemfile) if Bundler.settings[:plugins]
- definition = Bundler.definition
+ # For install we want to enable strict validation
+ # (rather than some optimizations we perform at app runtime).
+ definition = Bundler.definition(strict: true)
definition.validate_runtime!
+ definition.lockfile = options["lockfile"] if options["lockfile"]
+ definition.lockfile = false if options["no-lock"]
installer = Installer.install(Bundler.root, definition, options)
- Bundler.load.cache if Bundler.app_cache.exist? && !options["no-cache"] && !Bundler.frozen_bundle?
+
+ Bundler.settings.temporary(cache_all_platforms: options[:local] ? false : Bundler.settings[:cache_all_platforms]) do
+ Bundler.load.cache(nil, options[:local]) if Bundler.app_cache.exist? && !options["no-cache"] && !Bundler.frozen_bundle?
+ end
Bundler.ui.confirm "Bundle complete! #{dependencies_count_for(definition)}, #{gems_installed_for(definition)}."
Bundler::CLI::Common.output_without_groups_message(:install)
@@ -77,37 +65,23 @@ module Bundler
Bundler::CLI::Common.output_post_install_messages installer.post_install_messages
- warn_ambiguous_gems
-
if CLI::Common.clean_after_install?
require_relative "clean"
Bundler::CLI::Clean.new(options).run
end
- rescue GemNotFound, VersionConflict => e
- if options[:local] && Bundler.app_cache.exist?
- Bundler.ui.warn "Some gems seem to be missing from your #{Bundler.settings.app_cache_path} directory."
- end
- unless Bundler.definition.has_rubygems_remotes?
- Bundler.ui.warn <<-WARN, :wrap => true
- Your Gemfile has no gem server sources. If you need gems that are \
- not already on your machine, add a line like this to your Gemfile:
- source 'https://rubygems.org'
- WARN
- end
- raise e
- rescue Gem::InvalidSpecificationException => e
+ Bundler::CLI::Common.output_fund_metadata_summary
+ rescue Gem::InvalidSpecificationException
Bundler.ui.warn "You have one or more invalid gemspecs that need to be fixed."
- raise e
+ raise
end
- private
+ private
def warn_if_root
- return if Bundler.settings[:silence_root_warning] || Bundler::WINDOWS || !Process.uid.zero?
- Bundler.ui.warn "Don't run Bundler as root. Bundler can ask for sudo " \
- "if it is needed, and installing your bundle as root will break this " \
- "application for all non-root users on this machine.", :wrap => true
+ return if Bundler.settings[:silence_root_warning] || Gem.win_platform? || !Process.uid.zero?
+ Bundler.ui.warn "Don't run Bundler as root. Installing your bundle as root " \
+ "will break this application for all non-root users on this machine.", wrap: true
end
def dependencies_count_for(definition)
@@ -116,26 +90,10 @@ module Bundler
end
def gems_installed_for(definition)
- count = definition.specs.count
+ count = definition.specs.count {|spec| spec.name != "bundler" }
"#{count} #{count == 1 ? "gem" : "gems"} now installed"
end
- def check_for_group_conflicts_in_cli_options
- conflicting_groups = Array(options[:without]) & Array(options[:with])
- return if conflicting_groups.empty?
- raise InvalidOption, "You can't list a group in both with and without." \
- " The offending groups are: #{conflicting_groups.join(", ")}."
- end
-
- def check_for_options_conflicts
- if (options[:path] || options[:deployment]) && options[:system]
- error_message = String.new
- error_message << "You have specified both --path as well as --system. Please choose only one option.\n" if options[:path]
- error_message << "You have specified both --deployment as well as --system. Please choose only one option.\n" if options[:deployment]
- raise InvalidOption.new(error_message)
- end
- end
-
def check_trust_policy
trust_policy = options["trust-policy"]
unless Bundler.rubygems.security_policies.keys.unshift(nil).include?(trust_policy)
@@ -145,41 +103,11 @@ module Bundler
Bundler.settings.set_command_option_if_given :"trust-policy", trust_policy
end
- def normalize_groups
- options[:with] &&= options[:with].join(":").tr(" ", ":").split(":")
- options[:without] &&= options[:without].join(":").tr(" ", ":").split(":")
-
- check_for_group_conflicts_in_cli_options
-
- Bundler.settings.set_command_option :with, nil if options[:with] == []
- Bundler.settings.set_command_option :without, nil if options[:without] == []
-
- with = options.fetch(:with, [])
- with |= Bundler.settings[:with].map(&:to_s)
- with -= options[:without] if options[:without]
-
- without = options.fetch(:without, [])
- without |= Bundler.settings[:without].map(&:to_s)
- without -= options[:with] if options[:with]
-
- options[:with] = with
- options[:without] = without
- end
-
def normalize_settings
- Bundler.settings.set_command_option :path, nil if options[:system]
- Bundler.settings.temporary(:path_relative_to_cwd => false) do
- Bundler.settings.set_command_option :path, "vendor/bundle" if options[:deployment]
- end
- Bundler.settings.set_command_option_if_given :path, options[:path]
- Bundler.settings.temporary(:path_relative_to_cwd => false) do
- Bundler.settings.set_command_option :path, "bundle" if options["standalone"] && Bundler.settings[:path].nil?
+ if options["standalone"] && Bundler.settings[:path].nil? && !options["local"]
+ Bundler.settings.set_command_option :path, "bundle"
end
- bin_option = options["binstubs"]
- bin_option = nil if bin_option && bin_option.empty?
- Bundler.settings.set_command_option :bin, bin_option if options["binstubs"]
-
Bundler.settings.set_command_option_if_given :shebang, options["shebang"]
Bundler.settings.set_command_option_if_given :jobs, options["jobs"]
@@ -190,29 +118,7 @@ module Bundler
Bundler.settings.set_command_option_if_given :clean, options["clean"]
- unless Bundler.settings[:without] == options[:without] && Bundler.settings[:with] == options[:with]
- # need to nil them out first to get around validation for backwards compatibility
- Bundler.settings.set_command_option :without, nil
- Bundler.settings.set_command_option :with, nil
- Bundler.settings.set_command_option :without, options[:without] - options[:with]
- Bundler.settings.set_command_option :with, options[:with]
- end
-
- options[:force] = options[:redownload]
- end
-
- def warn_ambiguous_gems
- # TODO: remove this when we drop Bundler 1.x support
- Installer.ambiguous_gems.to_a.each do |name, installed_from_uri, *also_found_in_uris|
- Bundler.ui.warn "Warning: the gem '#{name}' was found in multiple sources."
- Bundler.ui.warn "Installed from: #{installed_from_uri}"
- Bundler.ui.warn "Also found in:"
- also_found_in_uris.each {|uri| Bundler.ui.warn " * #{uri}" }
- Bundler.ui.warn "You should add a source requirement to restrict this gem to your preferred source."
- Bundler.ui.warn "For example:"
- Bundler.ui.warn " gem '#{name}', :source => '#{installed_from_uri}'"
- Bundler.ui.warn "Then uninstall the gem '#{name}' (or delete all bundled gems) and then install again."
- end
+ options[:force] = options[:redownload] if options[:redownload]
end
end
end
diff --git a/lib/bundler/cli/issue.rb b/lib/bundler/cli/issue.rb
index 054ce76315..cbfb7da2d8 100644
--- a/lib/bundler/cli/issue.rb
+++ b/lib/bundler/cli/issue.rb
@@ -5,12 +5,12 @@ require "rbconfig"
module Bundler
class CLI::Issue
def run
- Bundler.ui.info <<-EOS.gsub(/^ {8}/, "")
+ Bundler.ui.info <<~EOS
Did you find an issue with Bundler? Before filing a new issue,
be sure to check out these resources:
1. Check out our troubleshooting guide for quick fixes to common issues:
- https://github.com/bundler/bundler/blob/master/doc/TROUBLESHOOTING.md
+ https://github.com/ruby/rubygems/blob/master/doc/bundler/TROUBLESHOOTING.md
2. Instructions for common Bundler uses can be found on the documentation
site: https://bundler.io/
@@ -20,9 +20,10 @@ module Bundler
Hopefully the troubleshooting steps above resolved your problem! If things
still aren't working the way you expect them to, please let us know so
- that we can diagnose and help fix the problem you're having. Please
- view the Filing Issues guide for more information:
- https://github.com/bundler/bundler/blob/master/doc/contributing/ISSUES.md
+ that we can diagnose and help fix the problem you're having, by filling
+ in the new issue form located at
+ https://github.com/ruby/rubygems/issues/new?labels=Bundler&template=bundler-related-issue.md,
+ and copy and pasting the information below.
EOS
@@ -33,8 +34,8 @@ module Bundler
end
def doctor
- require_relative "doctor"
- Bundler::CLI::Doctor.new({}).run
+ require_relative "doctor/diagnose"
+ Bundler::CLI::Doctor::Diagnose.new({}).run
end
end
end
diff --git a/lib/bundler/cli/list.rb b/lib/bundler/cli/list.rb
index d1799196e7..6a467f45a9 100644
--- a/lib/bundler/cli/list.rb
+++ b/lib/bundler/cli/list.rb
@@ -1,22 +1,63 @@
# frozen_string_literal: true
+require "json"
+
module Bundler
class CLI::List
def initialize(options)
@options = options
+ @without_group = options["without-group"].map(&:to_sym)
+ @only_group = options["only-group"].map(&:to_sym)
+ @format = options["format"]
end
def run
- raise InvalidOption, "The `--only-group` and `--without-group` options cannot be used together" if @options["only-group"] && @options["without-group"]
+ raise InvalidOption, "The `--only-group` and `--without-group` options cannot be used together" if @only_group.any? && @without_group.any?
raise InvalidOption, "The `--name-only` and `--paths` options cannot be used together" if @options["name-only"] && @options[:paths]
- specs = if @options["only-group"] || @options["without-group"]
+ specs = if @only_group.any? || @without_group.any?
filtered_specs_by_groups
else
- Bundler.load.specs
+ begin
+ Bundler.load.specs
+ rescue GemNotFound => e
+ Bundler.ui.error e.message
+ Bundler.ui.warn "Install missing gems with `bundle install`."
+ exit 1
+ end
end.reject {|s| s.name == "bundler" }.sort_by(&:name)
+ case @format
+ when "json"
+ print_json(specs: specs)
+ when nil
+ print_human(specs: specs)
+ else
+ raise InvalidOption, "Unknown option`--format=#{@format}`. Supported formats: `json`"
+ end
+ end
+
+ private
+
+ def print_json(specs:)
+ gems = if @options["name-only"]
+ specs.map {|s| { name: s.name } }
+ else
+ specs.map do |s|
+ {
+ name: s.name,
+ version: s.version.to_s,
+ git_version: s.git_version&.strip,
+ }.tap do |h|
+ h[:path] = s.full_gem_path if @options["paths"]
+ end
+ end
+ end
+ Bundler.ui.info({ gems: gems }.to_json)
+ end
+
+ def print_human(specs:)
return Bundler.ui.info "No gems in the Gemfile" if specs.empty?
return specs.each {|s| Bundler.ui.info s.name } if @options["name-only"]
@@ -29,12 +70,10 @@ module Bundler
Bundler.ui.info "Use `bundle info` to print more detailed information about a gem"
end
- private
-
def verify_group_exists(groups)
- raise InvalidOption, "`#{@options["without-group"]}` group could not be found." if @options["without-group"] && !groups.include?(@options["without-group"].to_sym)
-
- raise InvalidOption, "`#{@options["only-group"]}` group could not be found." if @options["only-group"] && !groups.include?(@options["only-group"].to_sym)
+ (@without_group + @only_group).each do |group|
+ raise InvalidOption, "`#{group}` group could not be found." unless groups.include?(group)
+ end
end
def filtered_specs_by_groups
@@ -44,10 +83,10 @@ module Bundler
verify_group_exists(groups)
show_groups =
- if @options["without-group"]
- groups.reject {|g| g == @options["without-group"].to_sym }
- elsif @options["only-group"]
- groups.select {|g| g == @options["only-group"].to_sym }
+ if @without_group.any?
+ groups.reject {|g| @without_group.include?(g) }
+ elsif @only_group.any?
+ groups.select {|g| @only_group.include?(g) }
else
groups
end.map(&:to_sym)
diff --git a/lib/bundler/cli/lock.rb b/lib/bundler/cli/lock.rb
index 7dd078b1ef..2f78868936 100644
--- a/lib/bundler/cli/lock.rb
+++ b/lib/bundler/cli/lock.rb
@@ -14,50 +14,81 @@ module Bundler
exit 1
end
+ check_for_conflicting_options
+
print = options[:print]
- ui = Bundler.ui
- Bundler.ui = UI::Silent.new if print
+ previous_output_stream = Bundler.ui.output_stream
+ Bundler.ui.output_stream = :stderr if print
Bundler::Fetcher.disable_endpoint = options["full-index"]
update = options[:update]
+ conservative = options[:conservative]
+ bundler = options[:bundler]
+
if update.is_a?(Array) # unlocking specific gems
Bundler::CLI::Common.ensure_all_gems_in_lockfile!(update)
- update = { :gems => update, :lock_shared_dependencies => options[:conservative] }
+ update = { gems: update, conservative: conservative }
+ elsif update && conservative
+ update = { conservative: conservative }
+ elsif update && bundler
+ update = { bundler: bundler }
end
- definition = Bundler.definition(update)
- Bundler::CLI::Common.configure_gem_version_promoter(Bundler.definition, options) if options[:update]
+ Bundler.settings.temporary(frozen: false) do
+ definition = Bundler.definition(update, Bundler.default_lockfile)
+ definition.add_checksums if options["add-checksums"]
- options["remove-platform"].each do |platform|
- definition.remove_platform(platform)
- end
+ Bundler::CLI::Common.configure_gem_version_promoter(definition, options) if options[:update]
- options["add-platform"].each do |platform_string|
- platform = Gem::Platform.new(platform_string)
- if platform.to_s == "unknown"
- Bundler.ui.warn "The platform `#{platform_string}` is unknown to RubyGems " \
- "and adding it will likely lead to resolution errors"
+ options["remove-platform"].each do |platform_string|
+ platform = Gem::Platform.new(platform_string)
+ definition.remove_platform(platform)
+ end
+
+ options["add-platform"].each do |platform_string|
+ platform = Gem::Platform.new(platform_string)
+ if platform.to_s == "unknown"
+ Bundler.ui.error "The platform `#{platform_string}` is unknown to RubyGems and can't be added to the lockfile."
+ exit 1
+ end
+ definition.add_platform(platform)
+ end
+
+ if definition.platforms.empty?
+ raise InvalidOption, "Removing all platforms from the bundle is not allowed"
end
- definition.add_platform(platform)
- end
- if definition.platforms.empty?
- raise InvalidOption, "Removing all platforms from the bundle is not allowed"
+ definition.remotely! unless options[:local]
+
+ if options["normalize-platforms"]
+ definition.normalize_platforms
+ end
+
+ if print
+ puts definition.to_lock
+ else
+ file = options[:lockfile]
+ file = file ? Pathname.new(file).expand_path : Bundler.default_lockfile
+
+ puts "Writing lockfile to #{file}"
+ definition.write_lock(file, false)
+ end
end
- definition.resolve_remotely! unless options[:local]
+ Bundler.ui.output_stream = previous_output_stream
+ end
+
+ private
- if print
- puts definition.to_lock
- else
- file = options[:lockfile]
- file = file ? File.expand_path(file) : Bundler.default_lockfile
- puts "Writing lockfile to #{file}"
- definition.lock(file)
+ def check_for_conflicting_options
+ if options["normalize-platforms"] && options["add-platform"].any?
+ raise InvalidOption, "--normalize-platforms can't be used with --add-platform"
end
- Bundler.ui = ui
+ if options["normalize-platforms"] && options["remove-platform"].any?
+ raise InvalidOption, "--normalize-platforms can't be used with --remove-platform"
+ end
end
end
end
diff --git a/lib/bundler/cli/open.rb b/lib/bundler/cli/open.rb
index df32e2f38b..f24693b843 100644
--- a/lib/bundler/cli/open.rb
+++ b/lib/bundler/cli/open.rb
@@ -1,29 +1,28 @@
# frozen_string_literal: true
-require "shellwords"
-
module Bundler
class CLI::Open
- attr_reader :options, :name
+ attr_reader :options, :name, :path
def initialize(options, name)
@options = options
@name = name
+ @path = options[:path] unless options[:path].nil?
end
def run
+ raise InvalidOption, "Cannot specify `--path` option without a value" if !@path.nil? && @path.empty?
editor = [ENV["BUNDLER_EDITOR"], ENV["VISUAL"], ENV["EDITOR"]].find {|e| !e.nil? && !e.empty? }
return Bundler.ui.info("To open a bundled gem, set $EDITOR or $BUNDLER_EDITOR") unless editor
return unless spec = Bundler::CLI::Common.select_spec(name, :regex_match)
if spec.default_gem?
Bundler.ui.info "Unable to open #{name} because it's a default gem, so the directory it would normally be installed to does not exist."
else
- path = spec.full_gem_path
- Dir.chdir(path) do
- command = Shellwords.split(editor) + [path]
- Bundler.with_original_env do
- system(*command)
- end || Bundler.ui.info("Could not run '#{command.join(" ")}'")
- end
+ root_path = spec.full_gem_path
+ require "shellwords"
+ command = Shellwords.split(editor) << File.join([root_path, path].compact)
+ Bundler.with_original_env do
+ system(*command, { chdir: root_path })
+ end || Bundler.ui.info("Could not run '#{command.join(" ")}'")
end
end
end
diff --git a/lib/bundler/cli/outdated.rb b/lib/bundler/cli/outdated.rb
index 0b710e9782..ae827dbb4b 100644
--- a/lib/bundler/cli/outdated.rb
+++ b/lib/bundler/cli/outdated.rb
@@ -3,18 +3,16 @@
module Bundler
class CLI::Outdated
attr_reader :options, :gems, :options_include_groups, :filter_options_patch, :sources, :strict
- attr_accessor :outdated_gems_by_groups, :outdated_gems_list
+ attr_accessor :outdated_gems
def initialize(options, gems)
@options = options
@gems = gems
@sources = Array(options[:source])
- @filter_options_patch = options.keys &
- %w[filter-major filter-minor filter-patch]
+ @filter_options_patch = options.keys & %w[filter-major filter-minor filter-patch]
- @outdated_gems_by_groups = {}
- @outdated_gems_list = []
+ @outdated_gems = []
@options_include_groups = [:group, :groups].any? do |v|
options.keys.include?(v.to_s)
@@ -22,20 +20,21 @@ module Bundler
# the patch level options imply strict is also true. It wouldn't make
# sense otherwise.
- @strict = options["filter-strict"] ||
- Bundler::CLI::Common.patch_level_options(options).any?
+ @strict = options["filter-strict"] || Bundler::CLI::Common.patch_level_options(options).any?
end
def run
check_for_deployment_mode!
- gems.each do |gem_name|
- Bundler::CLI::Common.select_spec(gem_name)
- end
-
Bundler.definition.validate_runtime!
current_specs = Bundler.ui.silence { Bundler.definition.resolve }
+ gems.each do |gem_name|
+ if current_specs[gem_name].empty?
+ raise GemNotFound, "Could not find gem '#{gem_name}'."
+ end
+ end
+
current_dependencies = Bundler.ui.silence do
Bundler.load.dependencies.map {|dep| [dep.name, dep] }.to_h
end
@@ -44,12 +43,12 @@ module Bundler
# We're doing a full update
Bundler.definition(true)
else
- Bundler.definition(:gems => gems, :sources => sources)
+ Bundler.definition(gems: gems, sources: sources)
end
Bundler::CLI::Common.configure_gem_version_promoter(
Bundler.definition,
- options
+ options.merge(strict: @strict)
)
definition_resolution = proc do
@@ -57,7 +56,7 @@ module Bundler
end
if options[:parseable]
- Bundler.ui.silence(&definition_resolution)
+ Bundler.ui.progress(&definition_resolution)
else
definition_resolution.call
end
@@ -75,85 +74,67 @@ module Bundler
gemfile_specs + dependency_specs
end
- specs.sort_by(&:name).each do |current_spec|
- next if !gems.empty? && !gems.include?(current_spec.name)
+ specs.sort_by(&:name).uniq(&:name).each do |current_spec|
+ next unless gems.empty? || gems.include?(current_spec.name)
- dependency = current_dependencies[current_spec.name]
active_spec = retrieve_active_spec(definition, current_spec)
+ next unless active_spec
- next if active_spec.nil?
- next if filter_options_patch.any? &&
- !update_present_via_semver_portions(current_spec, active_spec, options)
+ next unless filter_options_patch.empty? || update_present_via_semver_portions(current_spec, active_spec, options)
gem_outdated = Gem::Version.new(active_spec.version) > Gem::Version.new(current_spec.version)
next unless gem_outdated || (current_spec.git_version != active_spec.git_version)
- groups = nil
+
+ dependency = current_dependencies[current_spec.name]
+ groups = ""
if dependency && !options[:parseable]
groups = dependency.groups.join(", ")
end
- outdated_gems_list << { :active_spec => active_spec,
- :current_spec => current_spec,
- :dependency => dependency,
- :groups => groups }
-
- outdated_gems_by_groups[groups] ||= []
- outdated_gems_by_groups[groups] << outdated_gems_list[-1]
+ outdated_gems << {
+ active_spec: active_spec,
+ current_spec: current_spec,
+ dependency: dependency,
+ groups: groups,
+ }
end
- if outdated_gems_list.empty?
- display_nothing_outdated_message
+ relevant_outdated_gems = if options_include_groups
+ outdated_gems.group_by {|g| g[:groups] }.sort.flat_map do |groups, gems|
+ contains_group = groups.split(", ").include?(options[:group])
+ next unless options[:groups] || contains_group
+
+ gems
+ end.compact
else
+ outdated_gems
+ end
+
+ if relevant_outdated_gems.empty?
unless options[:parseable]
- Bundler.ui.info(header_outdated_message)
+ Bundler.ui.info(nothing_outdated_message)
end
-
- if options_include_groups
- ordered_groups = outdated_gems_by_groups.keys.compact.sort
- ordered_groups.insert(0, nil).each do |groups|
- gems = outdated_gems_by_groups[groups]
- contains_group = if groups
- groups.split(", ").include?(options[:group])
- else
- options[:group] == "group"
- end
-
- next if (!options[:groups] && !contains_group) || gems.nil?
-
- unless options[:parseable]
- Bundler.ui.info(header_group_message(groups))
- end
-
- print_gems(gems)
- end
+ else
+ if options[:parseable]
+ print_gems(relevant_outdated_gems)
else
- print_gems(outdated_gems_list)
+ print_gems_table(relevant_outdated_gems)
end
exit 1
end
end
- private
+ private
- def groups_text(group_text, groups)
- "#{group_text}#{groups.split(",").size > 1 ? "s" : ""} \"#{groups}\""
- end
+ def loaded_from_for(spec)
+ return unless spec.respond_to?(:loaded_from)
- def header_outdated_message
- if options[:pre]
- "Outdated gems included in the bundle (including pre-releases):"
- else
- "Outdated gems included in the bundle:"
- end
+ spec.loaded_from
end
- def header_group_message(groups)
- if groups
- "===== #{groups_text("Group", groups)} ====="
- else
- "===== Without group ====="
- end
+ def groups_text(group_text, groups)
+ "#{group_text}#{groups.split(",").size > 1 ? "s" : ""} \"#{groups}\""
end
def nothing_outdated_message
@@ -169,23 +150,16 @@ module Bundler
end
def retrieve_active_spec(definition, current_spec)
- if strict
- active_spec = definition.find_resolved_spec(current_spec)
- else
- active_specs = definition.find_indexed_specs(current_spec)
- if !current_spec.version.prerelease? && !options[:pre] && active_specs.size > 1
- active_specs.delete_if {|b| b.respond_to?(:version) && b.version.prerelease? }
- end
- active_spec = active_specs.last
- end
+ active_spec = definition.resolve.find_by_name_and_platform(current_spec.name, current_spec.platform)
+ return unless active_spec
- active_spec
- end
+ return active_spec if strict
- def display_nothing_outdated_message
- unless options[:parseable]
- Bundler.ui.info(nothing_outdated_message)
+ active_specs = active_spec.source.specs.search(current_spec.name).select {|spec| spec.installable_on_platform?(current_spec.platform) }.sort_by(&:version)
+ if !current_spec.version.prerelease? && !options[:pre] && active_specs.size > 1
+ active_specs.delete_if {|b| b.respond_to?(:version) && b.version.prerelease? }
end
+ active_specs.last
end
def print_gems(gems_list)
@@ -199,21 +173,41 @@ module Bundler
end
end
+ def print_gems_table(gems_list)
+ data = gems_list.map do |gem|
+ gem_column_for(
+ gem[:current_spec],
+ gem[:active_spec],
+ gem[:dependency],
+ gem[:groups],
+ )
+ end
+
+ print_indented([table_header] + data)
+ end
+
def print_gem(current_spec, active_spec, dependency, groups)
spec_version = "#{active_spec.version}#{active_spec.git_version}"
- spec_version += " (from #{active_spec.loaded_from})" if Bundler.ui.debug? && active_spec.loaded_from
+ if Bundler.ui.debug?
+ loaded_from = loaded_from_for(active_spec)
+ spec_version += " (from #{loaded_from})" if loaded_from
+ end
current_version = "#{current_spec.version}#{current_spec.git_version}"
- if dependency && dependency.specific?
+ if dependency&.specific?
dependency_version = %(, requested #{dependency.requirement})
end
spec_outdated_info = "#{active_spec.name} (newest #{spec_version}, " \
- "installed #{current_version}#{dependency_version})"
+ "installed #{current_version}#{dependency_version}"
+
+ release_date = release_date_for(active_spec)
+ spec_outdated_info += ", released #{release_date}" unless release_date.empty?
+ spec_outdated_info += ")"
output_message = if options[:parseable]
spec_outdated_info.to_s
- elsif options_include_groups || !groups
+ elsif options_include_groups || groups.empty?
" * #{spec_outdated_info}"
else
" * #{spec_outdated_info} in #{groups_text("group", groups)}"
@@ -222,14 +216,23 @@ module Bundler
Bundler.ui.info output_message.rstrip
end
+ def gem_column_for(current_spec, active_spec, dependency, groups)
+ current_version = "#{current_spec.version}#{current_spec.git_version}"
+ spec_version = "#{active_spec.version}#{active_spec.git_version}"
+ dependency = dependency.requirement if dependency
+
+ ret_val = [active_spec.name, current_version, spec_version, dependency.to_s, groups.to_s]
+ ret_val << release_date_for(active_spec)
+ ret_val << loaded_from_for(active_spec).to_s if Bundler.ui.debug?
+ ret_val
+ end
+
def check_for_deployment_mode!
return unless Bundler.frozen_bundle?
- suggested_command = if Bundler.settings.locations("frozen")[:global]
+ suggested_command = if Bundler.settings.locations("frozen").keys.&([:global, :local]).any?
"bundle config unset frozen"
elsif Bundler.settings.locations("deployment").keys.&([:global, :local]).any?
"bundle config unset deployment"
- else
- "bundle install --no-deployment"
end
raise ProductionError, "You are trying to check outdated gems in " \
"deployment mode. Run `bundle outdated` elsewhere.\n" \
@@ -266,5 +269,51 @@ module Bundler
version_section = spec.version.segments[version_portion_index, 1]
version_section.to_a[0].to_i
end
+
+ def print_indented(matrix)
+ header = matrix[0]
+ data = matrix[1..-1]
+
+ column_sizes = Array.new(header.size) do |index|
+ matrix.max_by {|row| row[index].length }[index].length
+ end
+
+ Bundler.ui.info justify(header, column_sizes)
+
+ data.sort_by! {|row| row[0] }
+
+ data.each do |row|
+ Bundler.ui.info justify(row, column_sizes)
+ end
+ end
+
+ def table_header
+ header = ["Gem", "Current", "Latest", "Requested", "Groups", "Release Date"]
+ header << "Path" if Bundler.ui.debug?
+ header
+ end
+
+ def release_date_for(spec)
+ return "" unless spec.respond_to?(:date)
+
+ date = spec.date
+ return "" unless date
+
+ return "" unless Gem.const_defined?(:DEFAULT_SOURCE_DATE_EPOCH)
+ default_date = Time.at(Gem::DEFAULT_SOURCE_DATE_EPOCH).utc
+ default_date = Time.utc(default_date.year, default_date.month, default_date.day)
+
+ date = date.utc if date.respond_to?(:utc)
+
+ return "" if date == default_date
+
+ date.strftime("%Y-%m-%d")
+ end
+
+ def justify(row, sizes)
+ row.each_with_index.map do |element, index|
+ element.ljust(sizes[index])
+ end.join(" ").strip + "\n"
+ end
end
end
diff --git a/lib/bundler/cli/package.rb b/lib/bundler/cli/package.rb
deleted file mode 100644
index b31b67776d..0000000000
--- a/lib/bundler/cli/package.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-# frozen_string_literal: true
-
-module Bundler
- class CLI::Package
- attr_reader :options
-
- def initialize(options)
- @options = options
- end
-
- def run
- Bundler.ui.level = "error" if options[:quiet]
- Bundler.settings.set_command_option_if_given :path, options[:path]
- Bundler.settings.set_command_option_if_given :cache_path, options["cache-path"]
-
- setup_cache_all
- install
-
- # TODO: move cache contents here now that all bundles are locked
- custom_path = Bundler.settings[:path] if options[:path]
-
- Bundler.settings.temporary(:cache_all_platforms => options["all-platforms"]) do
- Bundler.load.cache(custom_path)
- end
- end
-
- private
-
- def install
- require_relative "install"
- options = self.options.dup
- options["local"] = false if Bundler.settings[:cache_all_platforms]
- Bundler::CLI::Install.new(options).run
- end
-
- def setup_cache_all
- all = options.fetch(:all, Bundler.feature_flag.cache_all? || nil)
-
- Bundler.settings.set_command_option_if_given :cache_all, all
-
- if Bundler.definition.has_local_dependencies? && !Bundler.feature_flag.cache_all?
- Bundler.ui.warn "Your Gemfile contains path and git dependencies. If you want " \
- "to package them as well, please pass the --all flag. This will be the default " \
- "on Bundler 3.0."
- end
- end
- end
-end
diff --git a/lib/bundler/cli/platform.rb b/lib/bundler/cli/platform.rb
index e97cad49a4..32d68abbb1 100644
--- a/lib/bundler/cli/platform.rb
+++ b/lib/bundler/cli/platform.rb
@@ -8,12 +8,12 @@ module Bundler
end
def run
- platforms, ruby_version = Bundler.ui.silence do
- locked_ruby_version = Bundler.locked_gems && Bundler.locked_gems.ruby_version
- gemfile_ruby_version = Bundler.definition.ruby_version && Bundler.definition.ruby_version.single_version_string
- [Bundler.definition.platforms.map {|p| "* #{p}" },
- locked_ruby_version || gemfile_ruby_version]
+ ruby_version = if Bundler.locked_gems
+ Bundler.locked_gems.ruby_version&.gsub(/p\d+\Z/, "")
+ else
+ Bundler.definition.ruby_version&.single_version_string
end
+
output = []
if options[:ruby]
@@ -23,7 +23,9 @@ module Bundler
output << "No ruby version specified"
end
else
- output << "Your platform is: #{RUBY_PLATFORM}"
+ platforms = Bundler.definition.platforms.map {|p| "* #{p}" }
+
+ output << "Your platform is: #{Gem::Platform.local}"
output << "Your app has gems that work on these platforms:\n#{platforms.join("\n")}"
if ruby_version
diff --git a/lib/bundler/cli/plugin.rb b/lib/bundler/cli/plugin.rb
index 1155c4ec9b..32fa660fe0 100644
--- a/lib/bundler/cli/plugin.rb
+++ b/lib/bundler/cli/plugin.rb
@@ -5,24 +5,32 @@ module Bundler
class CLI::Plugin < Thor
desc "install PLUGINS", "Install the plugin from the source"
long_desc <<-D
- Install plugins either from the rubygems source provided (with --source option) or from a git source provided with --git (for remote repos) or --local_git (for local repos). If no sources are provided, it uses Gem.sources
+ Install plugins either from the rubygems source provided (with --source option), from a git source provided with --git, or a local path provided with --path. If no sources are provided, it uses Gem.sources
D
- method_option "source", :type => :string, :default => nil, :banner =>
- "URL of the RubyGems source to fetch the plugin from"
- method_option "version", :type => :string, :default => nil, :banner =>
- "The version of the plugin to fetch"
- method_option "git", :type => :string, :default => nil, :banner =>
- "URL of the git repo to fetch from"
- method_option "local_git", :type => :string, :default => nil, :banner =>
- "Path of the local git repo to fetch from"
- method_option "branch", :type => :string, :default => nil, :banner =>
- "The git branch to checkout"
- method_option "ref", :type => :string, :default => nil, :banner =>
- "The git revision to check out"
+ method_option "source", type: :string, default: nil, banner: "URL of the RubyGems source to fetch the plugin from"
+ method_option "version", type: :string, default: nil, banner: "The version of the plugin to fetch"
+ method_option "git", type: :string, default: nil, banner: "URL of the git repo to fetch from"
+ method_option "local_git", type: :string, default: nil, banner: "Path of the local git repo to fetch from (removed)"
+ method_option "branch", type: :string, default: nil, banner: "The git branch to checkout"
+ method_option "ref", type: :string, default: nil, banner: "The git revision to check out"
+ method_option "path", type: :string, default: nil, banner: "Path of a local gem to directly use"
def install(*plugins)
+ if options.key?(:local_git)
+ raise InvalidOption, "--local_git has been removed, use --git"
+ end
+
Bundler::Plugin.install(plugins, options)
end
+ desc "uninstall PLUGINS", "Uninstall the plugins"
+ long_desc <<-D
+ Uninstall given list of plugins. To uninstall all the plugins, use -all option.
+ D
+ method_option "all", type: :boolean, default: nil, banner: "Uninstall all the installed plugins. If no plugin is installed, then it does nothing."
+ def uninstall(*plugins)
+ Bundler::Plugin.uninstall(plugins, options)
+ end
+
desc "list", "List the installed plugins and available commands"
def list
Bundler::Plugin.list
diff --git a/lib/bundler/cli/pristine.rb b/lib/bundler/cli/pristine.rb
index 532b3e0b5b..f463f0bce8 100644
--- a/lib/bundler/cli/pristine.rb
+++ b/lib/bundler/cli/pristine.rb
@@ -11,36 +11,53 @@ module Bundler
definition = Bundler.definition
definition.validate_runtime!
installer = Bundler::Installer.new(Bundler.root, definition)
+ git_sources = []
- Bundler.load.specs.each do |spec|
- next if spec.name == "bundler" # Source::Rubygems doesn't install bundler
- next if !@gems.empty? && !@gems.include?(spec.name)
+ ProcessLock.lock do
+ installed_specs = definition.specs.reject do |spec|
+ next if spec.name == "bundler" # Source::Rubygems doesn't install bundler
+ next if !@gems.empty? && !@gems.include?(spec.name)
- gem_name = "#{spec.name} (#{spec.version}#{spec.git_version})"
- gem_name += " (#{spec.platform})" if !spec.platform.nil? && spec.platform != Gem::Platform::RUBY
+ gem_name = "#{spec.name} (#{spec.version}#{spec.git_version})"
+ gem_name += " (#{spec.platform})" if !spec.platform.nil? && spec.platform != Gem::Platform::RUBY
- case source = spec.source
- when Source::Rubygems
- cached_gem = spec.cache_file
- unless File.exist?(cached_gem)
- Bundler.ui.error("Failed to pristine #{gem_name}. Cached gem #{cached_gem} does not exist.")
+ case source = spec.source
+ when Source::Rubygems
+ cached_gem = spec.cache_file
+ unless File.exist?(cached_gem)
+ Bundler.ui.error("Failed to pristine #{gem_name}. Cached gem #{cached_gem} does not exist.")
+ next
+ end
+
+ FileUtils.rm_rf spec.full_gem_path
+ when Source::Git
+ if source.local?
+ Bundler.ui.warn("Cannot pristine #{gem_name}. Gem is locally overridden.")
+ next
+ end
+
+ source.remote!
+ if extension_cache_path = source.extension_cache_path(spec)
+ FileUtils.rm_rf extension_cache_path
+ end
+ FileUtils.rm_rf spec.extension_dir
+ FileUtils.rm_rf spec.full_gem_path
+
+ next if git_sources.include?(source)
+ git_sources << source
+ else
+ Bundler.ui.warn("Cannot pristine #{gem_name}. Gem is sourced from local path.")
next
end
- FileUtils.rm_rf spec.full_gem_path
- when Source::Git
- source.remote!
- if extension_cache_path = source.extension_cache_path(spec)
- FileUtils.rm_rf extension_cache_path
- end
- FileUtils.rm_rf spec.extension_dir
- FileUtils.rm_rf spec.full_gem_path
- else
- Bundler.ui.warn("Cannot pristine #{gem_name}. Gem is sourced from local path.")
- next
- end
-
- Bundler::GemInstaller.new(spec, installer, false, 0, true).install_from_spec
+ true
+ end.map(&:name)
+
+ jobs = Bundler.settings.installation_parallelization
+ pristine_count = definition.specs.count - installed_specs.count
+ # allow a pristining a single gem to skip the parallel worker
+ jobs = [jobs, pristine_count].min
+ ParallelInstaller.call(installer, definition.specs, jobs, false, true, skip: installed_specs)
end
end
end
diff --git a/lib/bundler/cli/remove.rb b/lib/bundler/cli/remove.rb
index cd6a2cec28..44a4d891dd 100644
--- a/lib/bundler/cli/remove.rb
+++ b/lib/bundler/cli/remove.rb
@@ -11,8 +11,7 @@ module Bundler
raise InvalidOption, "Please specify gems to remove." if @gems.empty?
Injector.remove(@gems, {})
-
- Installer.install(Bundler.root, Bundler.definition) if @options["install"]
+ Installer.install(Bundler.root, Bundler.definition)
end
end
end
diff --git a/lib/bundler/cli/show.rb b/lib/bundler/cli/show.rb
index 3748c25b89..67fdcc797e 100644
--- a/lib/bundler/cli/show.rb
+++ b/lib/bundler/cli/show.rb
@@ -6,7 +6,7 @@ module Bundler
def initialize(options, gem_name)
@options = options
@gem_name = gem_name
- @verbose = options[:verbose] || options[:outdated]
+ @verbose = options[:verbose]
@latest_specs = fetch_latest_specs if @verbose
end
@@ -18,13 +18,13 @@ module Bundler
if gem_name
if gem_name == "bundler"
- path = File.expand_path("../../../..", __FILE__)
+ path = File.expand_path("../../..", __dir__)
else
spec = Bundler::CLI::Common.select_spec(gem_name, :regex_match)
return unless spec
path = spec.full_gem_path
unless File.directory?(path)
- return Bundler.ui.warn "The gem #{gem_name} has been deleted. It was installed at: #{path}"
+ return Bundler.ui.warn "The gem #{gem_name} is missing. It should be installed at #{path}, but was not found"
end
end
return Bundler.ui.info(path)
@@ -40,8 +40,8 @@ module Bundler
desc = " * #{s.name} (#{s.version}#{s.git_version})"
if @verbose
latest = latest_specs.find {|l| l.name == s.name }
- Bundler.ui.info <<-END.gsub(/^ +/, "")
- #{desc}
+ Bundler.ui.info <<~END
+ #{desc.lstrip}
\tSummary: #{s.summary || "No description available."}
\tHomepage: #{s.homepage || "No website available."}
\tStatus: #{outdated?(s, latest) ? "Outdated - #{s.version} < #{latest.version}" : "Up to date"}
@@ -53,16 +53,12 @@ module Bundler
end
end
- private
+ private
def fetch_latest_specs
definition = Bundler.definition(true)
- if options[:outdated]
- Bundler.ui.info "Fetching remote specs for outdated check...\n\n"
- Bundler.ui.silence { definition.resolve_remotely! }
- else
- definition.resolve_with_cache!
- end
+ Bundler.ui.info "Fetching remote specs for outdated check...\n\n"
+ Bundler.ui.silence { definition.remotely! }
Bundler.reset!
definition.specs
end
diff --git a/lib/bundler/cli/update.rb b/lib/bundler/cli/update.rb
index 529dd9c94d..9cc90acc58 100644
--- a/lib/bundler/cli/update.rb
+++ b/lib/bundler/cli/update.rb
@@ -9,27 +9,36 @@ module Bundler
end
def run
- Bundler.ui.level = "error" if options[:quiet]
+ Bundler.ui.level = "warn" if options[:quiet]
- Plugin.gemfile_install(Bundler.default_gemfile) if Bundler.feature_flag.plugins?
+ update_bundler = options[:bundler]
+
+ Bundler.self_manager.update_bundler_and_restart_with_it_if_needed(update_bundler) if update_bundler
+
+ Plugin.gemfile_install(Bundler.default_gemfile) if Bundler.settings[:plugins]
sources = Array(options[:source])
groups = Array(options[:group]).map(&:to_sym)
- full_update = gems.empty? && sources.empty? && groups.empty? && !options[:ruby] && !options[:bundler]
+ full_update = gems.empty? && sources.empty? && groups.empty? && !options[:ruby] && !update_bundler
if full_update && !options[:all]
- if Bundler.feature_flag.update_requires_all_flag?
+ if Bundler.settings[:update_requires_all_flag]
raise InvalidOption, "To update everything, pass the `--all` flag."
end
- SharedHelpers.major_deprecation 3, "Pass --all to `bundle update` to update everything"
+ SharedHelpers.feature_deprecated! "Pass --all to `bundle update` to update everything"
elsif !full_update && options[:all]
raise InvalidOption, "Cannot specify --all along with specific options."
end
+ conservative = options[:conservative]
+
if full_update
- # We're doing a full update
- Bundler.definition(true)
+ if conservative
+ Bundler.definition(conservative: conservative)
+ else
+ Bundler.definition(true)
+ end
else
unless Bundler.default_lockfile.exist?
raise GemfileLockNotFound, "This Bundle hasn't been installed yet. " \
@@ -42,9 +51,9 @@ module Bundler
gems.concat(deps.map(&:name))
end
- Bundler.definition(:gems => gems, :sources => sources, :ruby => options[:ruby],
- :lock_shared_dependencies => options[:conservative],
- :bundler => options[:bundler])
+ Bundler.definition(gems: gems, sources: sources, ruby: options[:ruby],
+ conservative: conservative,
+ bundler: update_bundler)
end
Bundler::CLI::Common.configure_gem_version_promoter(Bundler.definition, options)
@@ -54,6 +63,7 @@ module Bundler
opts = options.dup
opts["update"] = true
opts["local"] = options[:local]
+ opts["force"] = options[:redownload] if options[:redownload]
Bundler.settings.set_command_option_if_given :jobs, opts["jobs"]
@@ -61,7 +71,7 @@ module Bundler
if locked_gems = Bundler.definition.locked_gems
previous_locked_info = locked_gems.specs.reduce({}) do |h, s|
- h[s.name] = { :spec => s, :version => s.version, :source => s.source.to_s }
+ h[s.name] = { spec: s, version: s.version, source: s.source.identifier }
h
end
end
@@ -82,7 +92,7 @@ module Bundler
locked_spec = locked_info[:spec]
new_spec = Bundler.definition.specs[name].first
unless new_spec
- if Bundler.rubygems.platforms.none? {|p| locked_spec.match_platform(p) }
+ unless locked_spec.installable_on_platform?(Bundler.local_platform)
Bundler.ui.warn "Bundler attempted to update #{name} but it was not considered because it is for a different platform from the current one"
end
@@ -90,7 +100,7 @@ module Bundler
end
locked_source = locked_info[:source]
- new_source = new_spec.source.to_s
+ new_source = new_spec.source.identifier
next if locked_source != new_source
new_version = new_spec.version
@@ -106,6 +116,8 @@ module Bundler
Bundler.ui.confirm "Bundle updated!"
Bundler::CLI::Common.output_without_groups_message(:update)
Bundler::CLI::Common.output_post_install_messages installer.post_install_messages
+
+ Bundler::CLI::Common.output_fund_metadata_summary
end
end
end
diff --git a/lib/bundler/cli/viz.rb b/lib/bundler/cli/viz.rb
deleted file mode 100644
index 644f9b25cf..0000000000
--- a/lib/bundler/cli/viz.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-# frozen_string_literal: true
-
-module Bundler
- class CLI::Viz
- attr_reader :options, :gem_name
- def initialize(options)
- @options = options
- end
-
- def run
- # make sure we get the right `graphviz`. There is also a `graphviz`
- # gem we're not built to support
- gem "ruby-graphviz"
- require "graphviz"
-
- options[:without] = options[:without].join(":").tr(" ", ":").split(":")
- output_file = File.expand_path(options[:file])
-
- graph = Graph.new(Bundler.load, output_file, options[:version], options[:requirements], options[:format], options[:without])
- graph.viz
- rescue LoadError => e
- Bundler.ui.error e.inspect
- Bundler.ui.warn "Make sure you have the graphviz ruby gem. You can install it with:"
- Bundler.ui.warn "`gem install ruby-graphviz`"
- rescue StandardError => e
- raise unless e.message =~ /GraphViz not installed or dot not in PATH/
- Bundler.ui.error e.message
- Bundler.ui.warn "Please install GraphViz. On a Mac with Homebrew, you can run `brew install graphviz`."
- end
- end
-end