summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/base64.gemspec2
-rw-r--r--lib/benchmark/version.rb2
-rw-r--r--lib/bundler.rb1
-rw-r--r--lib/bundler/cli.rb3
-rw-r--r--lib/bundler/cli/doctor.rb5
-rw-r--r--lib/bundler/cli/gem.rb32
-rw-r--r--lib/bundler/cli/info.rb20
-rw-r--r--lib/bundler/cli/issue.rb7
-rw-r--r--lib/bundler/cli/update.rb4
-rw-r--r--lib/bundler/compact_index_client/updater.rb5
-rw-r--r--lib/bundler/definition.rb186
-rw-r--r--lib/bundler/digest.rb71
-rw-r--r--lib/bundler/dsl.rb21
-rw-r--r--lib/bundler/environment_preserver.rb5
-rw-r--r--lib/bundler/errors.rb20
-rw-r--r--lib/bundler/fetcher.rb3
-rw-r--r--lib/bundler/friendly_errors.rb35
-rw-r--r--lib/bundler/gem_helper.rb21
-rw-r--r--lib/bundler/installer/gem_installer.rb7
-rw-r--r--lib/bundler/lazy_specification.rb18
-rw-r--r--lib/bundler/lockfile_parser.rb1
-rw-r--r--lib/bundler/man/bundle-add.12
-rw-r--r--lib/bundler/man/bundle-binstubs.12
-rw-r--r--lib/bundler/man/bundle-cache.12
-rw-r--r--lib/bundler/man/bundle-check.12
-rw-r--r--lib/bundler/man/bundle-clean.12
-rw-r--r--lib/bundler/man/bundle-config.16
-rw-r--r--lib/bundler/man/bundle-config.1.ronn4
-rw-r--r--lib/bundler/man/bundle-doctor.12
-rw-r--r--lib/bundler/man/bundle-exec.12
-rw-r--r--lib/bundler/man/bundle-gem.12
-rw-r--r--lib/bundler/man/bundle-info.12
-rw-r--r--lib/bundler/man/bundle-init.12
-rw-r--r--lib/bundler/man/bundle-inject.12
-rw-r--r--lib/bundler/man/bundle-install.12
-rw-r--r--lib/bundler/man/bundle-list.12
-rw-r--r--lib/bundler/man/bundle-lock.12
-rw-r--r--lib/bundler/man/bundle-open.12
-rw-r--r--lib/bundler/man/bundle-outdated.12
-rw-r--r--lib/bundler/man/bundle-platform.12
-rw-r--r--lib/bundler/man/bundle-pristine.12
-rw-r--r--lib/bundler/man/bundle-remove.12
-rw-r--r--lib/bundler/man/bundle-show.12
-rw-r--r--lib/bundler/man/bundle-update.12
-rw-r--r--lib/bundler/man/bundle-viz.12
-rw-r--r--lib/bundler/man/bundle.12
-rw-r--r--lib/bundler/man/gemfile.528
-rw-r--r--lib/bundler/man/gemfile.5.ronn8
-rw-r--r--lib/bundler/plugin/api/source.rb1
-rw-r--r--lib/bundler/resolver.rb6
-rw-r--r--lib/bundler/rubygems_ext.rb4
-rw-r--r--lib/bundler/rubygems_gem_installer.rb24
-rw-r--r--lib/bundler/rubygems_integration.rb51
-rw-r--r--lib/bundler/runtime.rb4
-rw-r--r--lib/bundler/source.rb2
-rw-r--r--lib/bundler/source/git.rb26
-rw-r--r--lib/bundler/source/git/git_proxy.rb7
-rw-r--r--lib/bundler/source/rubygems.rb136
-rw-r--r--lib/bundler/source/rubygems_aggregate.rb2
-rw-r--r--lib/bundler/source_list.rb36
-rw-r--r--lib/bundler/spec_set.rb2
-rw-r--r--lib/bundler/templates/newgem/github/workflows/main.yml.tt4
-rw-r--r--lib/bundler/templates/newgem/sig/newgem.rbs.tt8
-rw-r--r--lib/bundler/templates/newgem/standard.yml.tt2
-rw-r--r--lib/bundler/vendor/.document1
-rw-r--r--lib/bundler/vendor/connection_pool/lib/connection_pool/wrapper.rb4
-rw-r--r--lib/bundler/vendor/molinillo/lib/molinillo/dependency_graph.rb4
-rw-r--r--lib/bundler/vendor/tsort/lib/tsort.rb453
-rw-r--r--lib/bundler/vendored_tsort.rb4
-rw-r--r--lib/cgi.rb2
-rw-r--r--lib/cgi/cgi.gemspec4
-rw-r--r--lib/cgi/cookie.rb1
-rw-r--r--lib/csv.rb46
-rw-r--r--lib/csv/csv.gemspec2
-rw-r--r--lib/csv/fields_converter.rb8
-rw-r--r--lib/csv/input_record_separator.rb31
-rw-r--r--lib/csv/parser.rb22
-rw-r--r--lib/csv/version.rb2
-rw-r--r--lib/csv/writer.rb3
-rw-r--r--lib/debug.gemspec22
-rw-r--r--lib/debug.rb1106
-rw-r--r--lib/delegate/delegate.gemspec2
-rw-r--r--lib/did_you_mean.rb10
-rw-r--r--lib/did_you_mean/formatter.rb35
-rw-r--r--lib/did_you_mean/formatters/plain_formatter.rb35
-rw-r--r--lib/did_you_mean/formatters/verbose_formatter.rb52
-rw-r--r--lib/did_you_mean/spell_checker.rb18
-rw-r--r--lib/did_you_mean/spell_checkers/pattern_key_name_checker.rb20
-rw-r--r--lib/did_you_mean/verbose.rb6
-rw-r--r--lib/drb/version.rb2
-rw-r--r--lib/error_highlight/core_ext.rb2
-rw-r--r--lib/error_highlight/formatter.rb8
-rw-r--r--lib/fileutils.rb14
-rw-r--r--lib/find.gemspec2
-rw-r--r--lib/ipaddr.gemspec2
-rw-r--r--lib/ipaddr.rb132
-rw-r--r--lib/irb.rb4
-rw-r--r--lib/irb/cmd/show_source.rb7
-rw-r--r--lib/irb/completion.rb2
-rw-r--r--lib/irb/context.rb24
-rw-r--r--lib/irb/init.rb4
-rw-r--r--lib/irb/input-method.rb42
-rw-r--r--lib/irb/irb.gemspec2
-rw-r--r--lib/irb/lc/help-message1
-rw-r--r--lib/irb/ruby-lex.rb160
-rw-r--r--lib/irb/version.rb4
-rw-r--r--lib/logger/version.rb2
-rw-r--r--lib/mkmf.rb76
-rw-r--r--lib/mutex_m.rb1
-rw-r--r--lib/net/http.rb11
-rw-r--r--lib/net/http/backward.rb38
-rw-r--r--lib/net/http/generic_request.rb4
-rw-r--r--lib/net/http/net-http.gemspec1
-rw-r--r--lib/net/net-protocol.gemspec2
-rw-r--r--lib/net/protocol.rb2
-rw-r--r--lib/open-uri.gemspec2
-rw-r--r--lib/optparse.rb2
-rw-r--r--lib/ostruct.rb14
-rw-r--r--lib/pp.gemspec2
-rw-r--r--lib/pp.rb11
-rw-r--r--lib/prettyprint.gemspec2
-rw-r--r--lib/racc/grammar.rb6
-rw-r--r--lib/racc/grammarfileparser.rb4
-rw-r--r--lib/racc/info.rb2
-rw-r--r--lib/rdoc/any_method.rb5
-rw-r--r--lib/rdoc/cross_reference.rb2
-rw-r--r--lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Bold.ttfbin71200 -> 138268 bytes
-rw-r--r--lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Regular.ttfbin71692 -> 138680 bytes
-rw-r--r--lib/rdoc/markup/pre_process.rb2
-rw-r--r--lib/rdoc/parser/c.rb30
-rw-r--r--lib/readline.rb1
-rw-r--r--lib/reline.rb24
-rw-r--r--lib/reline/ansi.rb64
-rw-r--r--lib/reline/line_editor.rb168
-rw-r--r--lib/reline/terminfo.rb14
-rw-r--r--lib/reline/version.rb2
-rw-r--r--lib/reline/windows.rb55
-rw-r--r--lib/rinda/rinda.gemspec2
-rw-r--r--lib/rubygems.rb40
-rw-r--r--lib/rubygems/command.rb8
-rw-r--r--lib/rubygems/command_manager.rb4
-rw-r--r--lib/rubygems/commands/cert_command.rb29
-rw-r--r--lib/rubygems/commands/fetch_command.rb2
-rw-r--r--lib/rubygems/commands/pristine_command.rb10
-rw-r--r--lib/rubygems/commands/server_command.rb91
-rw-r--r--lib/rubygems/commands/setup_command.rb144
-rw-r--r--lib/rubygems/commands/uninstall_command.rb2
-rw-r--r--lib/rubygems/commands/update_command.rb2
-rw-r--r--lib/rubygems/defaults.rb2
-rw-r--r--lib/rubygems/dependency_list.rb4
-rw-r--r--lib/rubygems/exceptions.rb1
-rw-r--r--lib/rubygems/ext/builder.rb11
-rw-r--r--lib/rubygems/ext/cmake_builder.rb2
-rw-r--r--lib/rubygems/install_update_options.rb4
-rw-r--r--lib/rubygems/installer.rb61
-rw-r--r--lib/rubygems/local_remote_options.rb6
-rw-r--r--lib/rubygems/optparse.rb3
-rw-r--r--lib/rubygems/optparse/.document1
-rw-r--r--lib/rubygems/optparse/lib/optionparser.rb2
-rw-r--r--lib/rubygems/optparse/lib/optparse.rb2230
-rw-r--r--lib/rubygems/optparse/lib/optparse/ac.rb54
-rw-r--r--lib/rubygems/optparse/lib/optparse/date.rb18
-rw-r--r--lib/rubygems/optparse/lib/optparse/kwargs.rb22
-rw-r--r--lib/rubygems/optparse/lib/optparse/shellwords.rb7
-rw-r--r--lib/rubygems/optparse/lib/optparse/time.rb11
-rw-r--r--lib/rubygems/optparse/lib/optparse/uri.rb7
-rw-r--r--lib/rubygems/optparse/lib/optparse/version.rb71
-rw-r--r--lib/rubygems/package.rb58
-rw-r--r--lib/rubygems/query_utils.rb8
-rw-r--r--lib/rubygems/remote_fetcher.rb2
-rw-r--r--lib/rubygems/request.rb2
-rw-r--r--lib/rubygems/request_set.rb4
-rw-r--r--lib/rubygems/resolver/molinillo/lib/molinillo/dependency_graph.rb4
-rw-r--r--lib/rubygems/s3_uri_signer.rb9
-rw-r--r--lib/rubygems/security.rb71
-rw-r--r--lib/rubygems/security/policy.rb8
-rw-r--r--lib/rubygems/security/signer.rb7
-rw-r--r--lib/rubygems/security_option.rb6
-rw-r--r--lib/rubygems/server.rb882
-rw-r--r--lib/rubygems/source.rb2
-rw-r--r--lib/rubygems/source/git.rb4
-rw-r--r--lib/rubygems/specification.rb92
-rw-r--r--lib/rubygems/tsort.rb3
-rw-r--r--lib/rubygems/tsort/.document1
-rw-r--r--lib/rubygems/tsort/lib/tsort.rb454
-rw-r--r--lib/rubygems/util.rb2
-rw-r--r--lib/rubygems/util/licenses.rb2
-rw-r--r--lib/rubygems/version.rb9
-rw-r--r--lib/rubygems/version_option.rb4
-rw-r--r--lib/securerandom.gemspec2
-rw-r--r--lib/set/set.gemspec2
-rw-r--r--lib/tempfile.gemspec2
-rw-r--r--lib/time.gemspec2
-rw-r--r--lib/timeout.rb2
-rw-r--r--lib/tmpdir.rb4
-rw-r--r--lib/uri/http.rb39
-rw-r--r--lib/uri/version.rb2
-rw-r--r--lib/yaml/yaml.gemspec2
198 files changed, 5029 insertions, 3243 deletions
diff --git a/lib/base64.gemspec b/lib/base64.gemspec
index 1863a3fd3d3..daa0b7fa148 100644
--- a/lib/base64.gemspec
+++ b/lib/base64.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |spec|
spec.name = "base64"
- spec.version = "0.1.0"
+ spec.version = "0.1.1"
spec.authors = ["Yusuke Endoh"]
spec.email = ["mame@ruby-lang.org"]
diff --git a/lib/benchmark/version.rb b/lib/benchmark/version.rb
index 90d1a3900c5..90ae2754e43 100644
--- a/lib/benchmark/version.rb
+++ b/lib/benchmark/version.rb
@@ -1,3 +1,3 @@
module Benchmark
- VERSION = "0.1.1"
+ VERSION = "0.2.0"
end
diff --git a/lib/bundler.rb b/lib/bundler.rb
index f2d874bdf3f..81dfd05d26d 100644
--- a/lib/bundler.rb
+++ b/lib/bundler.rb
@@ -43,6 +43,7 @@ module Bundler
autoload :Dependency, File.expand_path("bundler/dependency", __dir__)
autoload :DepProxy, File.expand_path("bundler/dep_proxy", __dir__)
autoload :Deprecate, File.expand_path("bundler/deprecate", __dir__)
+ autoload :Digest, File.expand_path("bundler/digest", __dir__)
autoload :Dsl, File.expand_path("bundler/dsl", __dir__)
autoload :EndpointSpecification, File.expand_path("bundler/endpoint_specification", __dir__)
autoload :Env, File.expand_path("bundler/env", __dir__)
diff --git a/lib/bundler/cli.rb b/lib/bundler/cli.rb
index d5de72e5d4c..d271086b254 100644
--- a/lib/bundler/cli.rb
+++ b/lib/bundler/cli.rb
@@ -331,6 +331,7 @@ module Bundler
desc "info GEM [OPTIONS]", "Show information for the given gem"
method_option "path", :type => :boolean, :banner => "Print full path to gem"
+ method_option "version", :type => :boolean, :banner => "Print gem version"
def info(gem_name)
require_relative "cli/info"
Info.new(options, gem_name).run
@@ -552,7 +553,7 @@ module Bundler
method_option :version, :type => :boolean, :default => false, :aliases => "-v", :desc => "Set to show each gem version."
method_option :without, :type => :array, :default => [], :aliases => "-W", :banner => "GROUP[ GROUP...]", :desc => "Exclude gems that are part of the specified named group."
def viz
- SharedHelpers.major_deprecation 2, "The `viz` command has been moved to the `bundle-viz` gem, see https://github.com/bundler/bundler-viz"
+ SharedHelpers.major_deprecation 2, "The `viz` command has been renamed to `graph` and moved to a plugin. See https://github.com/rubygems/bundler-graph"
require_relative "cli/viz"
Viz.new(options.dup).run
end
diff --git a/lib/bundler/cli/doctor.rb b/lib/bundler/cli/doctor.rb
index c28997bc7dd..43f1ca92e2d 100644
--- a/lib/bundler/cli/doctor.rb
+++ b/lib/bundler/cli/doctor.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true
require "rbconfig"
+require "shellwords"
module Bundler
class CLI::Doctor
@@ -22,14 +23,14 @@ module Bundler
end
def dylibs_darwin(path)
- output = `/usr/bin/otool -L "#{path}"`.chomp
+ output = `/usr/bin/otool -L #{path.shellescape}`.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 = `/usr/bin/ldd #{path.shellescape}`.chomp
output.split("\n").map do |l|
match = l.match(LDD_REGEX)
next if match.nil?
diff --git a/lib/bundler/cli/gem.rb b/lib/bundler/cli/gem.rb
index a034aea3241..31e3af55806 100644
--- a/lib/bundler/cli/gem.rb
+++ b/lib/bundler/cli/gem.rb
@@ -68,7 +68,7 @@ module Bundler
:bundler_version => bundler_dependency_version,
:git => use_git,
:github_username => github_username.empty? ? "[USERNAME]" : github_username,
- :required_ruby_version => Gem.ruby_version < Gem::Version.new("2.4.a") ? "2.3.0" : "2.4.0",
+ :required_ruby_version => required_ruby_version,
}
ensure_safe_gem_name(name, constant_array)
@@ -76,6 +76,7 @@ module Bundler
"#{Bundler.preferred_gemfile_name}.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",
@@ -166,11 +167,11 @@ module Bundler
config[:linter] = ask_and_set_linter
case config[:linter]
when "rubocop"
- config[:linter_version] = Gem.ruby_version < Gem::Version.new("2.4.a") ? "0.81.0" : "1.7"
+ config[:linter_version] = rubocop_version
Bundler.ui.info "RuboCop enabled in config"
templates.merge!("rubocop.yml.tt" => ".rubocop.yml")
when "standard"
- config[:linter_version] = Gem.ruby_version < Gem::Version.new("2.4.a") ? "0.2.5" : "1.0"
+ config[:linter_version] = standard_version
Bundler.ui.info "Standard enabled in config"
templates.merge!("standard.yml.tt" => ".standard.yml")
end
@@ -403,5 +404,30 @@ module Bundler
def open_editor(editor, file)
thor.run(%(#{editor} "#{file}"))
end
+
+ def required_ruby_version
+ if Gem.ruby_version < Gem::Version.new("2.4.a") then "2.3.0"
+ elsif Gem.ruby_version < Gem::Version.new("2.5.a") then "2.4.0"
+ elsif Gem.ruby_version < Gem::Version.new("2.6.a") then "2.5.0"
+ else
+ "2.6.0"
+ end
+ end
+
+ def rubocop_version
+ if Gem.ruby_version < Gem::Version.new("2.4.a") then "0.81.0"
+ elsif Gem.ruby_version < Gem::Version.new("2.5.a") then "1.12"
+ else
+ "1.21"
+ end
+ end
+
+ def standard_version
+ if Gem.ruby_version < Gem::Version.new("2.4.a") then "0.2.5"
+ elsif Gem.ruby_version < Gem::Version.new("2.5.a") then "1.0"
+ else
+ "1.3"
+ end
+ end
end
end
diff --git a/lib/bundler/cli/info.rb b/lib/bundler/cli/info.rb
index 3111b64a33a..76c8cf60c01 100644
--- a/lib/bundler/cli/info.rb
+++ b/lib/bundler/cli/info.rb
@@ -18,6 +18,7 @@ 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
@@ -39,13 +40,18 @@ module Bundler
raise GemNotFound, Bundler::CLI::Common.gem_not_found_message(gem_name, Bundler.definition.dependencies)
end
+ def print_gem_version(spec)
+ Bundler.ui.info spec.version.to_s
+ end
+
def print_gem_path(spec)
- if spec.name == "bundler"
+ name = spec.name
+ if name == "bundler"
path = File.expand_path("../../../..", __FILE__)
else
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}"
+ if spec.deleted_gem?
+ return Bundler.ui.warn "The gem #{name} has been deleted. It was installed at: #{path}"
end
end
@@ -54,8 +60,9 @@ module Bundler
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")
@@ -67,6 +74,11 @@ module Bundler
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?
+
+ if name != "bundler" && spec.deleted_gem?
+ return Bundler.ui.warn "The gem #{name} has been deleted. Gemspec information is still available though:\n#{gem_info}"
+ end
+
Bundler.ui.info gem_info
end
end
diff --git a/lib/bundler/cli/issue.rb b/lib/bundler/cli/issue.rb
index f4cd5ac4df6..b891ecb1d2b 100644
--- a/lib/bundler/cli/issue.rb
+++ b/lib/bundler/cli/issue.rb
@@ -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/rubygems/rubygems/blob/master/bundler/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/rubygems/rubygems/issues/new?labels=Bundler&template=bundler-related-issue.md,
+ and copy and pasting the information below.
EOS
diff --git a/lib/bundler/cli/update.rb b/lib/bundler/cli/update.rb
index 1adcaef67cf..95a8886ea5c 100644
--- a/lib/bundler/cli/update.rb
+++ b/lib/bundler/cli/update.rb
@@ -66,7 +66,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
@@ -95,7 +95,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
diff --git a/lib/bundler/compact_index_client/updater.rb b/lib/bundler/compact_index_client/updater.rb
index 06486f98cb7..d9b9cec0d45 100644
--- a/lib/bundler/compact_index_client/updater.rb
+++ b/lib/bundler/compact_index_client/updater.rb
@@ -76,11 +76,6 @@ module Bundler
update(local_path, remote_path, :retrying)
end
- rescue Errno::EACCES
- raise Bundler::PermissionError,
- "Bundler does not have write access to create a temp directory " \
- "within #{Dir.tmpdir}. Bundler must have write access to your " \
- "systems temp directory to function properly. "
rescue Zlib::GzipFile::Error
raise Bundler::HTTPError
end
diff --git a/lib/bundler/definition.rb b/lib/bundler/definition.rb
index 2bd1290cddd..c2a8e2ba42f 100644
--- a/lib/bundler/definition.rb
+++ b/lib/bundler/definition.rb
@@ -78,7 +78,6 @@ module Bundler
@lockfile_contents = String.new
@locked_bundler_version = nil
@locked_ruby_version = nil
- @locked_specs_incomplete_for_platform = false
@new_platform = nil
if lockfile && File.exist?(lockfile)
@@ -144,6 +143,8 @@ module Bundler
@dependency_changes = converge_dependencies
@local_changes = converge_locals
+ @locked_specs_incomplete_for_platform = !@locked_specs.for(requested_dependencies & expand_dependencies(locked_dependencies), true, true)
+
@requires = compute_requires
end
@@ -162,10 +163,6 @@ module Bundler
end
end
- def multisource_allowed?
- @multisource_allowed
- end
-
def resolve_only_locally!
@remote = false
sources.local_only!
@@ -233,17 +230,22 @@ module Bundler
end
end
+ def locked_dependencies
+ @locked_deps.values
+ end
+
def specs_for(groups)
- groups = requested_groups if groups.empty?
+ return specs if groups.empty?
deps = dependencies_for(groups)
- materialize(expand_dependencies(deps))
+ materialize(deps)
end
def dependencies_for(groups)
groups.map!(&:to_sym)
- current_dependencies.reject do |d|
+ deps = current_dependencies.reject do |d|
(d.groups & groups).empty?
end
+ expand_dependencies(deps)
end
# Resolve all the dependencies specified in Gemfile. It ensures that
@@ -369,44 +371,26 @@ module Bundler
added.concat new_platforms.map {|p| "* platform: #{p}" }
deleted.concat deleted_platforms.map {|p| "* platform: #{p}" }
- gemfile_sources = sources.lock_sources
-
- new_sources = gemfile_sources - @locked_sources
- deleted_sources = @locked_sources - gemfile_sources
-
- new_deps = @dependencies - @locked_deps.values
- deleted_deps = @locked_deps.values - @dependencies
-
- # Check if it is possible that the source is only changed thing
- if (new_deps.empty? && deleted_deps.empty?) && (!new_sources.empty? && !deleted_sources.empty?)
- new_sources.reject! {|source| (source.path? && source.path.exist?) || equivalent_rubygems_remotes?(source) }
- deleted_sources.reject! {|source| (source.path? && source.path.exist?) || equivalent_rubygems_remotes?(source) }
- end
-
- if @locked_sources != gemfile_sources
- if new_sources.any?
- added.concat new_sources.map {|source| "* source: #{source}" }
- end
-
- if deleted_sources.any?
- deleted.concat deleted_sources.map {|source| "* source: #{source}" }
- end
- end
+ new_deps = @dependencies - locked_dependencies
+ deleted_deps = locked_dependencies - @dependencies
added.concat new_deps.map {|d| "* #{pretty_dep(d)}" } if new_deps.any?
- if deleted_deps.any?
- deleted.concat deleted_deps.map {|d| "* #{pretty_dep(d)}" }
- end
+ deleted.concat deleted_deps.map {|d| "* #{pretty_dep(d)}" } if deleted_deps.any?
both_sources = Hash.new {|h, k| h[k] = [] }
@dependencies.each {|d| both_sources[d.name][0] = d }
- @locked_deps.each {|name, d| both_sources[name][1] = d.source }
+ locked_dependencies.each {|d| both_sources[d.name][1] = d }
+
+ both_sources.each do |name, (dep, lock_dep)|
+ next if dep.nil? || lock_dep.nil?
- both_sources.each do |name, (dep, lock_source)|
- next if lock_source.nil? || (dep && lock_source.can_lock?(dep))
- gemfile_source_name = (dep && dep.source) || "no specified source"
- lockfile_source_name = lock_source
- changed << "* #{name} from `#{gemfile_source_name}` to `#{lockfile_source_name}`"
+ gemfile_source = dep.source || sources.default_source
+ lock_source = lock_dep.source || sources.default_source
+ next if lock_source.include?(gemfile_source)
+
+ gemfile_source_name = dep.source ? gemfile_source.identifier : "no specified source"
+ lockfile_source_name = lock_dep.source ? lock_source.identifier : "no specified source"
+ changed << "* #{name} from `#{lockfile_source_name}` to `#{gemfile_source_name}`"
end
reason = change_reason
@@ -567,7 +551,7 @@ module Bundler
def dependencies_for_source_changed?(source, locked_source = source)
deps_for_source = @dependencies.select {|s| s.source == source }
- locked_deps_for_source = @locked_deps.values.select {|dep| dep.source == locked_source }
+ locked_deps_for_source = locked_dependencies.select {|dep| dep.source == locked_source }
deps_for_source.uniq.sort != locked_deps_for_source.sort
end
@@ -650,25 +634,14 @@ module Bundler
end
def converge_dependencies
- frozen = Bundler.frozen_bundle?
- (@dependencies + @locked_deps.values).each do |dep|
- locked_source = @locked_deps[dep.name]
- # This is to make sure that if bundler is installing in deployment mode and
- # after locked_source and sources don't match, we still use locked_source.
- if frozen && !locked_source.nil? &&
- locked_source.respond_to?(:source) && locked_source.source.instance_of?(Source::Path) && locked_source.source.path.exist?
- dep.source = locked_source.source
- elsif dep.source
+ changes = false
+
+ @dependencies.each do |dep|
+ if dep.source
dep.source = sources.get(dep.source)
end
- end
- changes = false
- # We want to know if all match, but don't want to check all entries
- # This means we need to return false if any dependency doesn't match
- # the lock or doesn't exist in the lock.
- @dependencies.each do |dependency|
- unless locked_dep = @locked_deps[dependency.name]
+ unless locked_dep = @locked_deps[dep.name]
changes = true
next
end
@@ -679,11 +652,11 @@ module Bundler
# directive, the lockfile dependencies and resolved dependencies end up
# with a mismatch on #type. Work around that by setting the type on the
# dep from the lockfile.
- locked_dep.instance_variable_set(:@type, dependency.type)
+ locked_dep.instance_variable_set(:@type, dep.type)
# We already know the name matches from the hash lookup
# so we only need to check the requirement now
- changes ||= dependency.requirement != locked_dep.requirement
+ changes ||= dep.requirement != locked_dep.requirement
end
changes
@@ -693,39 +666,36 @@ module Bundler
# commonly happen if the Gemfile has changed since the lockfile was last
# generated
def converge_locked_specs
- deps = []
-
- # Build a list of dependencies that are the same in the Gemfile
- # and Gemfile.lock. If the Gemfile modified a dependency, but
- # the gem in the Gemfile.lock still satisfies it, this is fine
- # too.
- @dependencies.each do |dep|
- locked_dep = @locked_deps[dep.name]
+ resolve = converge_specs(@locked_specs)
- # If the locked_dep doesn't match the dependency we're looking for then we ignore the locked_dep
- locked_dep = nil unless locked_dep == dep
+ diff = nil
- if in_locked_deps?(dep, locked_dep) || satisfies_locked_spec?(dep)
- deps << dep
- elsif dep.source.is_a?(Source::Path) && dep.current_platform? && (!locked_dep || dep.source != locked_dep.source)
- @locked_specs.each do |s|
- @unlock[:gems] << s.name if s.source == dep.source
- end
+ # Now, we unlock any sources that do not have anymore gems pinned to it
+ sources.all_sources.each do |source|
+ next unless source.respond_to?(:unlock!)
- dep.source.unlock! if dep.source.respond_to?(:unlock!)
- dep.source.specs.each {|s| @unlock[:gems] << s.name }
+ unless resolve.any? {|s| s.source == source }
+ diff ||= @locked_specs.to_a - resolve.to_a
+ source.unlock! if diff.any? {|s| s.source == source }
end
end
+ resolve
+ end
+
+ def converge_specs(specs)
+ deps = []
converged = []
- @locked_specs.each do |s|
+ specs.each do |s|
# Replace the locked dependency's source with the equivalent source from the Gemfile
dep = @dependencies.find {|d| s.satisfies?(d) }
- s.source = (dep && dep.source) || sources.get(s.source) unless multisource_allowed?
- # Don't add a spec to the list if its source is expired. For example,
- # if you change a Git gem to RubyGems.
- next if s.source.nil?
+ if dep && (!dep.source || s.source.include?(dep.source))
+ deps << dep
+ end
+
+ s.source = (dep && dep.source) || sources.get(s.source) || sources.default_source unless Bundler.frozen_bundle?
+
next if @unlock[:sources].include?(s.source.name)
# If the spec is from a path source and it doesn't exist anymore
@@ -738,7 +708,7 @@ module Bundler
rescue PathError, GitError
# if we won't need the source (according to the lockfile),
# don't error if the path/git source isn't available
- next if @locked_specs.
+ next if specs.
for(requested_dependencies, false, true).
none? {|locked_spec| locked_spec.source == s.source }
@@ -754,36 +724,15 @@ module Bundler
s.dependencies.replace(new_spec.dependencies)
end
- converged << s
- end
-
- resolve = SpecSet.new(converged)
- @locked_specs_incomplete_for_platform = !resolve.for(expand_dependencies(requested_dependencies & deps), true, true)
- resolve = SpecSet.new(resolve.for(expand_dependencies(deps, true), false, false).reject{|s| @unlock[:gems].include?(s.name) })
- diff = nil
-
- # Now, we unlock any sources that do not have anymore gems pinned to it
- sources.all_sources.each do |source|
- next unless source.respond_to?(:unlock!)
-
- unless resolve.any? {|s| s.source == source }
- diff ||= @locked_specs.to_a - resolve.to_a
- source.unlock! if diff.any? {|s| s.source == source }
+ if dep.nil? && requested_dependencies.find {|d| s.name == d.name }
+ @unlock[:gems] << s.name
+ else
+ converged << s
end
end
- resolve
- end
-
- def in_locked_deps?(dep, locked_dep)
- # Because the lockfile can't link a dep to a specific remote, we need to
- # treat sources as equivalent anytime the locked dep has all the remotes
- # that the Gemfile dep does.
- locked_dep && locked_dep.source && dep.source && locked_dep.source.include?(dep.source)
- end
-
- def satisfies_locked_spec?(dep)
- @locked_specs[dep].any? {|s| s.satisfies?(dep) && (!dep.source || s.source.include?(dep.source)) }
+ resolve = SpecSet.new(converged)
+ SpecSet.new(resolve.for(expand_dependencies(deps, true), false, false).reject{|s| @unlock[:gems].include?(s.name) })
end
def metadata_dependencies
@@ -876,22 +825,11 @@ module Bundler
def additional_base_requirements_for_resolve
return [] unless @locked_gems && unlocking? && !sources.expired_sources?(@locked_gems.sources)
- dependencies_by_name = dependencies.inject({}) {|memo, dep| memo.update(dep.name => dep) }
- @locked_gems.specs.reduce({}) do |requirements, locked_spec|
+ converge_specs(@locked_gems.specs).map do |locked_spec|
name = locked_spec.name
- dependency = dependencies_by_name[name]
- next requirements if @locked_gems.dependencies[name] != dependency
- next requirements if dependency && dependency.source.is_a?(Source::Path)
dep = Gem::Dependency.new(name, ">= #{locked_spec.version}")
- requirements[name] = DepProxy.get_proxy(dep, locked_spec.platform)
- requirements
- end.values
- end
-
- def equivalent_rubygems_remotes?(source)
- return false unless source.is_a?(Source::Rubygems)
-
- Bundler.settings[:allow_deployment_source_credential_changes] && source.equivalent_remotes?(sources.rubygems_remotes)
+ DepProxy.get_proxy(dep, locked_spec.platform)
+ end
end
def source_map
diff --git a/lib/bundler/digest.rb b/lib/bundler/digest.rb
new file mode 100644
index 00000000000..759f6094165
--- /dev/null
+++ b/lib/bundler/digest.rb
@@ -0,0 +1,71 @@
+# frozen_string_literal: true
+
+# This code was extracted from https://github.com/Solistra/ruby-digest which is under public domain
+module Bundler
+ module Digest
+ # The initial constant values for the 32-bit constant words A, B, C, D, and
+ # E, respectively.
+ SHA1_WORDS = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0].freeze
+
+ # The 8-bit field used for bitwise `AND` masking. Defaults to `0xFFFFFFFF`.
+ SHA1_MASK = 0xFFFFFFFF
+
+ class << self
+ def sha1(string)
+ unless string.is_a?(String)
+ raise TypeError, "can't convert #{string.class.inspect} into String"
+ end
+
+ buffer = string.b
+
+ words = SHA1_WORDS.dup
+ generate_split_buffer(buffer) do |chunk|
+ w = []
+ chunk.each_slice(4) do |a, b, c, d|
+ w << (((a << 8 | b) << 8 | c) << 8 | d)
+ end
+ a, b, c, d, e = *words
+ (16..79).each do |i|
+ w[i] = SHA1_MASK & rotate((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1)
+ end
+ 0.upto(79) do |i|
+ case i
+ when 0..19
+ f = ((b & c) | (~b & d))
+ k = 0x5A827999
+ when 20..39
+ f = (b ^ c ^ d)
+ k = 0x6ED9EBA1
+ when 40..59
+ f = ((b & c) | (b & d) | (c & d))
+ k = 0x8F1BBCDC
+ when 60..79
+ f = (b ^ c ^ d)
+ k = 0xCA62C1D6
+ end
+ t = SHA1_MASK & (SHA1_MASK & rotate(a, 5) + f + e + k + w[i])
+ a, b, c, d, e = t, a, SHA1_MASK & rotate(b, 30), c, d # rubocop:disable Style/ParallelAssignment
+ end
+ mutated = [a, b, c, d, e]
+ words.map!.with_index {|word, index| SHA1_MASK & (word + mutated[index]) }
+ end
+
+ words.pack("N*").unpack("H*").first
+ end
+
+ private
+
+ def generate_split_buffer(string, &block)
+ size = string.bytesize * 8
+ buffer = string.bytes << 128
+ buffer << 0 while buffer.size % 64 != 56
+ buffer.concat([size].pack("Q>").bytes)
+ buffer.each_slice(64, &block)
+ end
+
+ def rotate(value, spaces)
+ value << spaces | value >> (32 - spaces)
+ end
+ end
+ end
+end
diff --git a/lib/bundler/dsl.rb b/lib/bundler/dsl.rb
index ed7b3e2d6b7..1108fc3b781 100644
--- a/lib/bundler/dsl.rb
+++ b/lib/bundler/dsl.rb
@@ -18,6 +18,8 @@ module Bundler
VALID_KEYS = %w[group groups git path glob name branch ref tag require submodules
platform platforms type source install_if gemfile].freeze
+ GITHUB_PULL_REQUEST_URL = %r{\Ahttps://github\.com/([A-Za-z0-9_\-\.]+/[A-Za-z0-9_\-\.]+)/pull/(\d+)\z}.freeze
+
attr_reader :gemspecs
attr_accessor :dependencies
@@ -278,8 +280,17 @@ module Bundler
warn_deprecated_git_source(:github, <<-'RUBY'.strip, 'Change any "reponame" :github sources to "username/reponame".')
"https://github.com/#{repo_name}.git"
RUBY
- repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
- "https://github.com/#{repo_name}.git"
+ if repo_name =~ GITHUB_PULL_REQUEST_URL
+ {
+ "git" => "https://github.com/#{$1}.git",
+ "branch" => "refs/pull/#{$2}/head",
+ "ref" => nil,
+ "tag" => nil,
+ }
+ else
+ repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
+ "https://github.com/#{repo_name}.git"
+ end
end
git_source(:gist) do |repo_name|
@@ -365,7 +376,11 @@ repo_name ||= user_name
git_name = (git_names & opts.keys).last
if @git_sources[git_name]
- opts["git"] = @git_sources[git_name].call(opts[git_name])
+ git_opts = @git_sources[git_name].call(opts[git_name])
+ git_opts = { "git" => git_opts } if git_opts.is_a?(String)
+ opts.merge!(git_opts) do |key, _gemfile_value, _git_source_value|
+ raise GemfileError, %(The :#{key} option can't be used with `#{git_name}: #{opts[git_name].inspect}`)
+ end
end
%w[git path].each do |type|
diff --git a/lib/bundler/environment_preserver.rb b/lib/bundler/environment_preserver.rb
index a77f7e0816b..0f08e049d8d 100644
--- a/lib/bundler/environment_preserver.rb
+++ b/lib/bundler/environment_preserver.rb
@@ -38,7 +38,10 @@ module Bundler
# Replaces `ENV` with the bundler environment variables backed up
def replace_with_backup
- ENV.replace(backup) unless Gem.win_platform?
+ unless Gem.win_platform?
+ ENV.replace(backup)
+ return
+ end
# Fallback logic for Windows below to workaround
# https://bugs.ruby-lang.org/issues/16798. Can be dropped once all
diff --git a/lib/bundler/errors.rb b/lib/bundler/errors.rb
index 565aaeeb9d9..9ad7460e585 100644
--- a/lib/bundler/errors.rb
+++ b/lib/bundler/errors.rb
@@ -75,10 +75,26 @@ module Bundler
end
end
+ def permission_type
+ case @permission_type
+ when :create
+ "executable permissions for all parent directories and write permissions for `#{parent_folder}`"
+ when :delete
+ permissions = "executable permissions for all parent directories and write permissions for `#{parent_folder}`"
+ permissions += ", and the same thing for all subdirectories inside #{@path}" if File.directory?(@path)
+ permissions
+ else
+ "#{@permission_type} permissions for that path"
+ end
+ end
+
+ def parent_folder
+ File.dirname(@path)
+ end
+
def message
"There was an error while trying to #{action} `#{@path}`. " \
- "It is likely that you need to grant #{@permission_type} permissions " \
- "for that path."
+ "It is likely that you need to grant #{permission_type}."
end
status_code(23)
diff --git a/lib/bundler/fetcher.rb b/lib/bundler/fetcher.rb
index d237837948a..6dd6d089eb0 100644
--- a/lib/bundler/fetcher.rb
+++ b/lib/bundler/fetcher.rb
@@ -28,7 +28,8 @@ module Bundler
" is a chance you are experiencing a man-in-the-middle attack, but" \
" most likely your system doesn't have the CA certificates needed" \
" for verification. For information about OpenSSL certificates, see" \
- " http://bit.ly/ruby-ssl. To connect without using SSL, edit your Gemfile" \
+ " https://railsapps.github.io/openssl-certificate-verify-failed.html." \
+ " To connect without using SSL, edit your Gemfile" \
" sources and change 'https' to 'http'."
end
end
diff --git a/lib/bundler/friendly_errors.rb b/lib/bundler/friendly_errors.rb
index db43e0f6549..cc615db60ca 100644
--- a/lib/bundler/friendly_errors.rb
+++ b/lib/bundler/friendly_errors.rb
@@ -63,34 +63,6 @@ module Bundler
def request_issue_report_for(e)
Bundler.ui.error <<-EOS.gsub(/^ {8}/, ""), nil, nil
--- ERROR REPORT TEMPLATE -------------------------------------------------------
- # Error Report
-
- ## Questions
-
- Please fill out answers to these questions, it'll help us figure out
- why things are going wrong.
-
- - **What did you do?**
-
- I ran the command `#{$PROGRAM_NAME} #{ARGV.join(" ")}`
-
- - **What did you expect to happen?**
-
- I expected Bundler to...
-
- - **What happened instead?**
-
- Instead, what happened was...
-
- - **Have you tried any solutions posted on similar issues in our issue tracker, stack overflow, or google?**
-
- I tried...
-
- - **Have you read our issues document, https://github.com/rubygems/rubygems/blob/master/bundler/doc/contributing/ISSUES.md?**
-
- ...
-
- ## Backtrace
```
#{e.class}: #{e.message}
@@ -109,8 +81,7 @@ module Bundler
First, try this link to see if there are any existing issue reports for this error:
#{issues_url(e)}
- If there aren't any reports for this error yet, please copy and paste the report template above into a new issue. Don't forget to anonymize any private data! The new issue form is located at:
- https://github.com/rubygems/rubygems/issues/new?labels=Bundler&template=bundler-related-issue.md
+ If there aren't any reports for this error yet, please fill in the new issue form located at #{new_issue_url}, and copy and paste the report template above in there.
EOS
end
@@ -121,6 +92,10 @@ module Bundler
"https://github.com/rubygems/rubygems/search?q=" \
"#{CGI.escape(message)}&type=Issues"
end
+
+ def new_issue_url
+ "https://github.com/rubygems/rubygems/issues/new?labels=Bundler&template=bundler-related-issue.md"
+ end
end
def self.with_friendly_errors
diff --git a/lib/bundler/gem_helper.rb b/lib/bundler/gem_helper.rb
index 8e1dd7c4f2b..034f2e59602 100644
--- a/lib/bundler/gem_helper.rb
+++ b/lib/bundler/gem_helper.rb
@@ -98,10 +98,7 @@ module Bundler
built_gem_path ||= build_gem
cmd = [*gem_command, "install", built_gem_path.to_s]
cmd << "--local" if local
- _, status = sh_with_status(cmd)
- unless status.success?
- raise "Couldn't install gem, run `gem install #{built_gem_path}' for more detailed output"
- end
+ sh(cmd)
Bundler.ui.confirm "#{name} (#{version}) installed."
end
@@ -110,7 +107,7 @@ module Bundler
SharedHelpers.filesystem_access(File.join(base, "checksums")) {|p| FileUtils.mkdir_p(p) }
file_name = "#{File.basename(built_gem_path)}.sha512"
require "digest/sha2"
- checksum = Digest::SHA512.new.hexdigest(built_gem_path.to_s)
+ checksum = ::Digest::SHA512.new.hexdigest(built_gem_path.to_s)
target = File.join(base, "checksums", file_name)
File.write(target, checksum)
Bundler.ui.confirm "#{name} #{version} checksum written to checksums/#{file_name}."
@@ -132,8 +129,8 @@ module Bundler
def git_push(remote = nil)
remote ||= default_remote
- perform_git_push "#{remote} refs/heads/#{current_branch}"
- perform_git_push "#{remote} refs/tags/#{version_tag}"
+ sh("git push #{remote} refs/heads/#{current_branch}".shellsplit)
+ sh("git push #{remote} refs/tags/#{version_tag}".shellsplit)
Bundler.ui.confirm "Pushed git commits and release tag."
end
@@ -161,13 +158,6 @@ module Bundler
allowed_push_host || env_rubygems_host || "rubygems.org"
end
- def perform_git_push(options = "")
- cmd = "git push #{options}"
- out, status = sh_with_status(cmd.shellsplit)
- return if status.success?
- raise "Couldn't git push. `#{cmd}' failed with the following output:\n\n#{out}\n"
- end
-
def already_tagged?
return false unless sh(%w[git tag]).split(/\n/).include?(version_tag)
Bundler.ui.confirm "Tag #{version_tag} has already been created."
@@ -218,8 +208,7 @@ module Bundler
def sh(cmd, &block)
out, status = sh_with_status(cmd, &block)
unless status.success?
- cmd = cmd.shelljoin if cmd.respond_to?(:shelljoin)
- raise(out.empty? ? "Running `#{cmd}` failed. Run this command directly for more detailed output." : out)
+ raise("Running `#{cmd.shelljoin}` failed with the following output:\n\n#{out}\n")
end
out
end
diff --git a/lib/bundler/installer/gem_installer.rb b/lib/bundler/installer/gem_installer.rb
index 1df86ccfbc8..13a1356f56d 100644
--- a/lib/bundler/installer/gem_installer.rb
+++ b/lib/bundler/installer/gem_installer.rb
@@ -13,7 +13,7 @@ module Bundler
end
def install_from_spec
- post_install_message = spec_settings ? install_with_settings : install
+ post_install_message = install
Bundler.ui.debug "#{worker}: #{spec.name} (#{spec.version}) from #{spec.loaded_from}"
generate_executable_stubs
return true, post_install_message
@@ -54,11 +54,6 @@ module Bundler
spec.source.install(spec, :force => force, :ensure_builtin_gems_cached => standalone, :build_args => Array(spec_settings))
end
- def install_with_settings
- # Build arguments are global, so this is mutexed
- Bundler.rubygems.install_with_build_args([spec_settings]) { install }
- end
-
def out_of_space_message
"#{install_error_message}\nYour disk is out of space. Free some space to be able to install your bundle."
end
diff --git a/lib/bundler/lazy_specification.rb b/lib/bundler/lazy_specification.rb
index 6760edba42c..4eb228f3145 100644
--- a/lib/bundler/lazy_specification.rb
+++ b/lib/bundler/lazy_specification.rb
@@ -38,8 +38,24 @@ module Bundler
identifier.hash
end
+ ##
+ # Does this locked specification satisfy +dependency+?
+ #
+ # NOTE: Rubygems default requirement is ">= 0", which doesn't match
+ # prereleases of 0 versions, like "0.0.0.dev" or "0.0.0.SNAPSHOT". However,
+ # bundler users expect those to work. We need to make sure that Gemfile
+ # dependencies without explicit requirements (which use ">= 0" under the
+ # hood by default) are still valid for locked specs using this kind of
+ # versions. The method implements an ad-hoc fix for that. A better solution
+ # might be to change default rubygems requirement of dependencies to be ">=
+ # 0.A" but that's a major refactoring likely to break things. Hopefully we
+ # can attempt it in the future.
+ #
+
def satisfies?(dependency)
- @name == dependency.name && dependency.requirement.satisfied_by?(Gem::Version.new(@version))
+ effective_requirement = dependency.requirement == Gem::Requirement.default ? Gem::Requirement.new(">= 0.A") : dependency.requirement
+
+ @name == dependency.name && effective_requirement.satisfied_by?(Gem::Version.new(@version))
end
def to_lock
diff --git a/lib/bundler/lockfile_parser.rb b/lib/bundler/lockfile_parser.rb
index 8d0e44d0aea..6ff4910a36a 100644
--- a/lib/bundler/lockfile_parser.rb
+++ b/lib/bundler/lockfile_parser.rb
@@ -86,6 +86,7 @@ module Bundler
def warn_for_outdated_bundler_version
return unless bundler_version
+ return if bundler_version.segments.last == "dev"
prerelease_text = bundler_version.prerelease? ? " --pre" : ""
current_version = Gem::Version.create(Bundler::VERSION)
return unless current_version < bundler_version
diff --git a/lib/bundler/man/bundle-add.1 b/lib/bundler/man/bundle-add.1
index 0cac84bbe82..a94467e25f3 100644
--- a/lib/bundler/man/bundle-add.1
+++ b/lib/bundler/man/bundle-add.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-ADD" "1" "August 2021" "" ""
+.TH "BUNDLE\-ADD" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-add\fR \- Add gem to the Gemfile and run bundle install
diff --git a/lib/bundler/man/bundle-binstubs.1 b/lib/bundler/man/bundle-binstubs.1
index 017e302fec7..6d1b1d4247d 100644
--- a/lib/bundler/man/bundle-binstubs.1
+++ b/lib/bundler/man/bundle-binstubs.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-BINSTUBS" "1" "August 2021" "" ""
+.TH "BUNDLE\-BINSTUBS" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-binstubs\fR \- Install the binstubs of the listed gems
diff --git a/lib/bundler/man/bundle-cache.1 b/lib/bundler/man/bundle-cache.1
index cfb4b847201..acbdae0df2f 100644
--- a/lib/bundler/man/bundle-cache.1
+++ b/lib/bundler/man/bundle-cache.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-CACHE" "1" "August 2021" "" ""
+.TH "BUNDLE\-CACHE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-cache\fR \- Package your needed \fB\.gem\fR files into your application
diff --git a/lib/bundler/man/bundle-check.1 b/lib/bundler/man/bundle-check.1
index bc8f4772f65..e555c9b3996 100644
--- a/lib/bundler/man/bundle-check.1
+++ b/lib/bundler/man/bundle-check.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-CHECK" "1" "August 2021" "" ""
+.TH "BUNDLE\-CHECK" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-check\fR \- Verifies if dependencies are satisfied by installed gems
diff --git a/lib/bundler/man/bundle-clean.1 b/lib/bundler/man/bundle-clean.1
index 814d28e4541..d4032475240 100644
--- a/lib/bundler/man/bundle-clean.1
+++ b/lib/bundler/man/bundle-clean.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-CLEAN" "1" "August 2021" "" ""
+.TH "BUNDLE\-CLEAN" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-clean\fR \- Cleans up unused gems in your bundler directory
diff --git a/lib/bundler/man/bundle-config.1 b/lib/bundler/man/bundle-config.1
index 06f2a7bb73a..5c07e227fdd 100644
--- a/lib/bundler/man/bundle-config.1
+++ b/lib/bundler/man/bundle-config.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-CONFIG" "1" "August 2021" "" ""
+.TH "BUNDLE\-CONFIG" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-config\fR \- Set bundler configuration options
@@ -462,13 +462,13 @@ export BUNDLE_GITHUB__COM=abcd0123generatedtoken:x\-oauth\-basic
.IP "" 0
.
.P
-Note that any configured credentials will be redacted by informative commands such as \fBbundle config list\fR or \fBbundle config get\fR, unless you use the \fB\-\-parseable\fR flag\. This is to avoid unintentially leaking credentials when copy\-pasting bundler output\.
+Note that any configured credentials will be redacted by informative commands such as \fBbundle config list\fR or \fBbundle config get\fR, unless you use the \fB\-\-parseable\fR flag\. This is to avoid unintentionally leaking credentials when copy\-pasting bundler output\.
.
.P
Also note that to guarantee a sane mapping between valid environment variable names and valid host names, bundler makes the following transformations:
.
.IP "\(bu" 4
-Any \fB\-\fR characters in a host name are mapped to a triple dash (\fB___\fR) in the corresponding enviroment variable\.
+Any \fB\-\fR characters in a host name are mapped to a triple dash (\fB___\fR) in the corresponding environment variable\.
.
.IP "\(bu" 4
Any \fB\.\fR characters in a host name are mapped to a double dash (\fB__\fR) in the corresponding environment variable\.
diff --git a/lib/bundler/man/bundle-config.1.ronn b/lib/bundler/man/bundle-config.1.ronn
index 96374d9f2ba..a21aa027ad2 100644
--- a/lib/bundler/man/bundle-config.1.ronn
+++ b/lib/bundler/man/bundle-config.1.ronn
@@ -367,14 +367,14 @@ where you can use personal OAuth tokens:
Note that any configured credentials will be redacted by informative commands
such as `bundle config list` or `bundle config get`, unless you use the
-`--parseable` flag. This is to avoid unintentially leaking credentials when
+`--parseable` flag. This is to avoid unintentionally leaking credentials when
copy-pasting bundler output.
Also note that to guarantee a sane mapping between valid environment variable
names and valid host names, bundler makes the following transformations:
* Any `-` characters in a host name are mapped to a triple dash (`___`) in the
- corresponding enviroment variable.
+ corresponding environment variable.
* Any `.` characters in a host name are mapped to a double dash (`__`) in the
corresponding environment variable.
diff --git a/lib/bundler/man/bundle-doctor.1 b/lib/bundler/man/bundle-doctor.1
index 5509d315c0e..87a7fe5f2f6 100644
--- a/lib/bundler/man/bundle-doctor.1
+++ b/lib/bundler/man/bundle-doctor.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-DOCTOR" "1" "August 2021" "" ""
+.TH "BUNDLE\-DOCTOR" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-doctor\fR \- Checks the bundle for common problems
diff --git a/lib/bundler/man/bundle-exec.1 b/lib/bundler/man/bundle-exec.1
index 627ba57ec45..69adfa7c92c 100644
--- a/lib/bundler/man/bundle-exec.1
+++ b/lib/bundler/man/bundle-exec.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-EXEC" "1" "August 2021" "" ""
+.TH "BUNDLE\-EXEC" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-exec\fR \- Execute a command in the context of the bundle
diff --git a/lib/bundler/man/bundle-gem.1 b/lib/bundler/man/bundle-gem.1
index 0190cefa3b4..fae5c34e7e9 100644
--- a/lib/bundler/man/bundle-gem.1
+++ b/lib/bundler/man/bundle-gem.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-GEM" "1" "August 2021" "" ""
+.TH "BUNDLE\-GEM" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-gem\fR \- Generate a project skeleton for creating a rubygem
diff --git a/lib/bundler/man/bundle-info.1 b/lib/bundler/man/bundle-info.1
index 5a1ff7757d9..9e1400ec56c 100644
--- a/lib/bundler/man/bundle-info.1
+++ b/lib/bundler/man/bundle-info.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-INFO" "1" "August 2021" "" ""
+.TH "BUNDLE\-INFO" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-info\fR \- Show information for the given gem in your bundle
diff --git a/lib/bundler/man/bundle-init.1 b/lib/bundler/man/bundle-init.1
index 7c729479575..612d16031c6 100644
--- a/lib/bundler/man/bundle-init.1
+++ b/lib/bundler/man/bundle-init.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-INIT" "1" "August 2021" "" ""
+.TH "BUNDLE\-INIT" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-init\fR \- Generates a Gemfile into the current working directory
diff --git a/lib/bundler/man/bundle-inject.1 b/lib/bundler/man/bundle-inject.1
index c281f212ba7..ded4d6d64bf 100644
--- a/lib/bundler/man/bundle-inject.1
+++ b/lib/bundler/man/bundle-inject.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-INJECT" "1" "August 2021" "" ""
+.TH "BUNDLE\-INJECT" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-inject\fR \- Add named gem(s) with version requirements to Gemfile
diff --git a/lib/bundler/man/bundle-install.1 b/lib/bundler/man/bundle-install.1
index 8b86954996a..6824dea3b0b 100644
--- a/lib/bundler/man/bundle-install.1
+++ b/lib/bundler/man/bundle-install.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-INSTALL" "1" "August 2021" "" ""
+.TH "BUNDLE\-INSTALL" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-install\fR \- Install the dependencies specified in your Gemfile
diff --git a/lib/bundler/man/bundle-list.1 b/lib/bundler/man/bundle-list.1
index 48f817ed736..a697173af9c 100644
--- a/lib/bundler/man/bundle-list.1
+++ b/lib/bundler/man/bundle-list.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-LIST" "1" "August 2021" "" ""
+.TH "BUNDLE\-LIST" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-list\fR \- List all the gems in the bundle
diff --git a/lib/bundler/man/bundle-lock.1 b/lib/bundler/man/bundle-lock.1
index 623e76406bc..ef515b03373 100644
--- a/lib/bundler/man/bundle-lock.1
+++ b/lib/bundler/man/bundle-lock.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-LOCK" "1" "August 2021" "" ""
+.TH "BUNDLE\-LOCK" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-lock\fR \- Creates / Updates a lockfile without installing
diff --git a/lib/bundler/man/bundle-open.1 b/lib/bundler/man/bundle-open.1
index d1c5314ed41..dd28566bdb0 100644
--- a/lib/bundler/man/bundle-open.1
+++ b/lib/bundler/man/bundle-open.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-OPEN" "1" "August 2021" "" ""
+.TH "BUNDLE\-OPEN" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-open\fR \- Opens the source directory for a gem in your bundle
diff --git a/lib/bundler/man/bundle-outdated.1 b/lib/bundler/man/bundle-outdated.1
index d327de4ba63..b9d50a1c710 100644
--- a/lib/bundler/man/bundle-outdated.1
+++ b/lib/bundler/man/bundle-outdated.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-OUTDATED" "1" "August 2021" "" ""
+.TH "BUNDLE\-OUTDATED" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-outdated\fR \- List installed gems with newer versions available
diff --git a/lib/bundler/man/bundle-platform.1 b/lib/bundler/man/bundle-platform.1
index 872afb6d58b..b1c859f64b2 100644
--- a/lib/bundler/man/bundle-platform.1
+++ b/lib/bundler/man/bundle-platform.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-PLATFORM" "1" "August 2021" "" ""
+.TH "BUNDLE\-PLATFORM" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-platform\fR \- Displays platform compatibility information
diff --git a/lib/bundler/man/bundle-pristine.1 b/lib/bundler/man/bundle-pristine.1
index 8361597f7de..6e4a0286660 100644
--- a/lib/bundler/man/bundle-pristine.1
+++ b/lib/bundler/man/bundle-pristine.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-PRISTINE" "1" "August 2021" "" ""
+.TH "BUNDLE\-PRISTINE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-pristine\fR \- Restores installed gems to their pristine condition
diff --git a/lib/bundler/man/bundle-remove.1 b/lib/bundler/man/bundle-remove.1
index 548c208403b..0b4edd14149 100644
--- a/lib/bundler/man/bundle-remove.1
+++ b/lib/bundler/man/bundle-remove.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-REMOVE" "1" "August 2021" "" ""
+.TH "BUNDLE\-REMOVE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-remove\fR \- Removes gems from the Gemfile
diff --git a/lib/bundler/man/bundle-show.1 b/lib/bundler/man/bundle-show.1
index 8669a8add0a..375699ddf08 100644
--- a/lib/bundler/man/bundle-show.1
+++ b/lib/bundler/man/bundle-show.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-SHOW" "1" "August 2021" "" ""
+.TH "BUNDLE\-SHOW" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-show\fR \- Shows all the gems in your bundle, or the path to a gem
diff --git a/lib/bundler/man/bundle-update.1 b/lib/bundler/man/bundle-update.1
index 9df9c05ea70..f5a79fe24ea 100644
--- a/lib/bundler/man/bundle-update.1
+++ b/lib/bundler/man/bundle-update.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-UPDATE" "1" "August 2021" "" ""
+.TH "BUNDLE\-UPDATE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-update\fR \- Update your gems to the latest available versions
diff --git a/lib/bundler/man/bundle-viz.1 b/lib/bundler/man/bundle-viz.1
index 6603fad30d9..f792aa63460 100644
--- a/lib/bundler/man/bundle-viz.1
+++ b/lib/bundler/man/bundle-viz.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE\-VIZ" "1" "August 2021" "" ""
+.TH "BUNDLE\-VIZ" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-viz\fR \- Generates a visual dependency graph for your Gemfile
diff --git a/lib/bundler/man/bundle.1 b/lib/bundler/man/bundle.1
index 2fe30724e6d..b1458bf57b9 100644
--- a/lib/bundler/man/bundle.1
+++ b/lib/bundler/man/bundle.1
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "BUNDLE" "1" "August 2021" "" ""
+.TH "BUNDLE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\fR \- Ruby Dependency Management
diff --git a/lib/bundler/man/gemfile.5 b/lib/bundler/man/gemfile.5
index 5ef91541b06..1ac003a7800 100644
--- a/lib/bundler/man/gemfile.5
+++ b/lib/bundler/man/gemfile.5
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
-.TH "GEMFILE" "5" "August 2021" "" ""
+.TH "GEMFILE" "5" "December 2021" "" ""
.
.SH "NAME"
\fBGemfile\fR \- A format for describing gem dependencies for Ruby programs
@@ -506,6 +506,32 @@ gem "rails", :git => "git://github\.com/rails/rails\.git"
.P
Since the \fBgithub\fR method is a specialization of \fBgit_source\fR, it accepts a \fB:branch\fR named argument\.
.
+.P
+You can also directly pass a pull request URL:
+.
+.IP "" 4
+.
+.nf
+
+gem "rails", :github => "https://github\.com/rails/rails/pull/43753"
+.
+.fi
+.
+.IP "" 0
+.
+.P
+Which is equivalent to:
+.
+.IP "" 4
+.
+.nf
+
+gem "rails", :github => "rails/rails", branch: "refs/pull/43753/head"
+.
+.fi
+.
+.IP "" 0
+.
.SS "GIST"
If the git repository you want to use is hosted as a GitHub Gist and is public, you can use the :gist shorthand to specify the gist identifier (without the trailing "\.git")\.
.
diff --git a/lib/bundler/man/gemfile.5.ronn b/lib/bundler/man/gemfile.5.ronn
index ea7cf40e63c..0feaf582463 100644
--- a/lib/bundler/man/gemfile.5.ronn
+++ b/lib/bundler/man/gemfile.5.ronn
@@ -372,6 +372,14 @@ Are both equivalent to
Since the `github` method is a specialization of `git_source`, it accepts a `:branch` named argument.
+You can also directly pass a pull request URL:
+
+ gem "rails", :github => "https://github.com/rails/rails/pull/43753"
+
+Which is equivalent to:
+
+ gem "rails", :github => "rails/rails", branch: "refs/pull/43753/head"
+
### GIST
If the git repository you want to use is hosted as a GitHub Gist and is public, you can use
diff --git a/lib/bundler/plugin/api/source.rb b/lib/bundler/plugin/api/source.rb
index f6f4ac4f0a2..32b1d0ee381 100644
--- a/lib/bundler/plugin/api/source.rb
+++ b/lib/bundler/plugin/api/source.rb
@@ -283,6 +283,7 @@ module Bundler
def to_s
"plugin source for #{@type} with uri #{@uri}"
end
+ alias_method :identifier, :to_s
# Note: Do not override if you don't know what you are doing.
def include?(other)
diff --git a/lib/bundler/resolver.rb b/lib/bundler/resolver.rb
index d26e2feb109..5eb17a3921a 100644
--- a/lib/bundler/resolver.rb
+++ b/lib/bundler/resolver.rb
@@ -30,10 +30,8 @@ module Bundler
@resolver = Molinillo::Resolver.new(self, self)
@search_for = {}
@base_dg = Molinillo::DependencyGraph.new
- aggregate_global_source = @source_requirements[:default].is_a?(Source::RubygemsAggregate)
@base.each do |ls|
dep = Dependency.new(ls.name, ls.version)
- ls.source = source_for(ls.name) unless aggregate_global_source
@base_dg.add_vertex(ls.name, DepProxy.get_proxy(dep, ls.platform), true)
end
additional_base_requirements.each {|d| @base_dg.add_vertex(d.name, d) }
@@ -272,7 +270,7 @@ module Bundler
rescue GemfileNotFound
nil
end
- message = String.new("Could not find gem '#{SharedHelpers.pretty_dependency(requirement)}' in #{source.to_err}#{cache_message}.\n")
+ message = String.new("Could not find gem '#{SharedHelpers.pretty_dependency(requirement)}' in #{source}#{cache_message}.\n")
message << "The source contains the following versions of '#{name}': #{formatted_versions_with_platforms(versions_with_platforms)}" if versions_with_platforms.any?
end
raise GemNotFound, message
@@ -371,7 +369,7 @@ module Bundler
o << if metadata_requirement
"is not available in #{relevant_source}"
else
- "in #{relevant_source.to_err}.\n"
+ "in #{relevant_source}.\n"
end
end
end,
diff --git a/lib/bundler/rubygems_ext.rb b/lib/bundler/rubygems_ext.rb
index 26132078268..5d572aa73d6 100644
--- a/lib/bundler/rubygems_ext.rb
+++ b/lib/bundler/rubygems_ext.rb
@@ -85,6 +85,10 @@ module Gem
dependencies - development_dependencies
end
+ def deleted_gem?
+ !default_gem? && !File.directory?(full_gem_path)
+ end
+
private
def dependencies_to_gemfile(dependencies, group = nil)
diff --git a/lib/bundler/rubygems_gem_installer.rb b/lib/bundler/rubygems_gem_installer.rb
index 88905823180..bb9f1cb3f5c 100644
--- a/lib/bundler/rubygems_gem_installer.rb
+++ b/lib/bundler/rubygems_gem_installer.rb
@@ -16,10 +16,12 @@ module Bundler
spec.loaded_from = spec_file
# Completely remove any previous gem files
- FileUtils.rm_rf gem_dir
- FileUtils.rm_rf spec.extension_dir
+ strict_rm_rf gem_dir
+ strict_rm_rf spec.extension_dir
- FileUtils.mkdir_p gem_dir, :mode => 0o755
+ SharedHelpers.filesystem_access(gem_dir, :create) do
+ FileUtils.mkdir_p gem_dir, :mode => 0o755
+ end
extract_files
@@ -31,7 +33,10 @@ module Bundler
generate_plugins
write_spec
- write_cache_file
+
+ SharedHelpers.filesystem_access("#{gem_home}/cache", :write) do
+ write_cache_file
+ end
say spec.post_install_message unless spec.post_install_message.nil?
@@ -87,6 +92,17 @@ module Bundler
private
+ def strict_rm_rf(dir)
+ # FileUtils.rm_rf should probably rise in case of permission issues like
+ # `rm -rf` does. However, it fails to delete the folder silently due to
+ # https://github.com/ruby/fileutils/issues/57. It should probably be fixed
+ # inside `fileutils` but for now I`m checking whether the folder was
+ # removed after it completes, and raising otherwise.
+ FileUtils.rm_rf dir
+
+ raise PermissionError.new(dir, :delete) if File.directory?(dir)
+ end
+
def validate_bundler_checksum(checksum)
return true if Bundler.settings[:disable_checksum_validation]
return true unless checksum
diff --git a/lib/bundler/rubygems_integration.rb b/lib/bundler/rubygems_integration.rb
index 789797d8d00..effb88c1cd0 100644
--- a/lib/bundler/rubygems_integration.rb
+++ b/lib/bundler/rubygems_integration.rb
@@ -86,16 +86,12 @@ module Bundler
def spec_missing_extensions?(spec, default = true)
return spec.missing_extensions? if spec.respond_to?(:missing_extensions?)
- return false if spec_default_gem?(spec)
+ return false if spec.default_gem?
return false if spec.extensions.empty?
default
end
- def spec_default_gem?(spec)
- spec.respond_to?(:default_gem?) && spec.default_gem?
- end
-
def spec_matches_for_glob(spec, glob)
return spec.matches_for_glob(glob) if spec.respond_to?(:matches_for_glob)
@@ -236,18 +232,6 @@ module Bundler
EXT_LOCK
end
- def with_build_args(args)
- ext_lock.synchronize do
- old_args = build_args
- begin
- self.build_args = args
- yield
- ensure
- self.build_args = old_args
- end
- end
- end
-
def spec_from_gem(path, policy = nil)
require "rubygems/security"
require_relative "psyched_yaml"
@@ -504,14 +488,15 @@ module Bundler
end
def fetch_specs(remote, name)
+ require "rubygems/remote_fetcher"
path = remote.uri.to_s + "#{name}.#{Gem.marshal_version}.gz"
fetcher = gem_remote_fetcher
fetcher.headers = { "X-Gemfile-Source" => remote.original_uri.to_s } if remote.original_uri
string = fetcher.fetch_path(path)
Bundler.load_marshal(string)
- rescue Gem::RemoteFetcher::FetchError => e
+ rescue Gem::RemoteFetcher::FetchError
# it's okay for prerelease to fail
- raise e unless name == "prerelease_specs"
+ raise unless name == "prerelease_specs"
end
def fetch_all_remote_specs(remote)
@@ -521,12 +506,32 @@ module Bundler
specs.concat(pres)
end
- def download_gem(spec, uri, path)
+ def download_gem(spec, uri, cache_dir)
+ require "rubygems/remote_fetcher"
uri = Bundler.settings.mirror_for(uri)
fetcher = gem_remote_fetcher
fetcher.headers = { "X-Gemfile-Source" => spec.remote.original_uri.to_s } if spec.remote.original_uri
Bundler::Retry.new("download gem from #{uri}").attempts do
- fetcher.download(spec, uri, path)
+ gem_file_name = spec.file_name
+ local_gem_path = File.join cache_dir, gem_file_name
+ return if File.exist? local_gem_path
+
+ begin
+ remote_gem_path = uri + "gems/#{gem_file_name}"
+ remote_gem_path = remote_gem_path.to_s if provides?("< 3.2.0.rc.1")
+
+ SharedHelpers.filesystem_access(local_gem_path) do
+ fetcher.cache_update_path remote_gem_path, local_gem_path
+ end
+ rescue Gem::RemoteFetcher::FetchError
+ raise if spec.original_platform == spec.platform
+
+ original_gem_file_name = "#{spec.original_name}.gem"
+ raise if gem_file_name == original_gem_file_name
+
+ gem_file_name = original_gem_file_name
+ retry
+ end
end
rescue Gem::RemoteFetcher::FetchError => e
raise Bundler::HTTPError, "Could not download gem from #{uri} due to underlying error <#{e.message}>"
@@ -554,10 +559,6 @@ module Bundler
Gem::REPOSITORY_SUBDIRECTORIES
end
- def install_with_build_args(args)
- yield
- end
-
def path_separator
Gem.path_separator
end
diff --git a/lib/bundler/runtime.rb b/lib/bundler/runtime.rb
index fbb8833cfbc..c7276b0e251 100644
--- a/lib/bundler/runtime.rb
+++ b/lib/bundler/runtime.rb
@@ -265,7 +265,7 @@ module Bundler
return if manuals.empty?
Bundler::SharedHelpers.set_env "MANPATH", manuals.concat(
- ENV["MANPATH"].to_s.split(File::PATH_SEPARATOR)
+ ENV["MANPATH"] ? ENV["MANPATH"].to_s.split(File::PATH_SEPARATOR) : [""]
).uniq.join(File::PATH_SEPARATOR)
end
@@ -291,7 +291,7 @@ module Bundler
return unless activated_spec = Bundler.rubygems.loaded_specs(spec.name)
return if activated_spec.version == spec.version
- suggestion = if Bundler.rubygems.spec_default_gem?(activated_spec)
+ suggestion = if activated_spec.default_gem?
"Since #{spec.name} is a default gem, you can either remove your dependency on it" \
" or try updating to a newer version of bundler that supports #{spec.name} as a default gem."
else
diff --git a/lib/bundler/source.rb b/lib/bundler/source.rb
index 434112ac8a9..2a2b332cff7 100644
--- a/lib/bundler/source.rb
+++ b/lib/bundler/source.rb
@@ -67,7 +67,7 @@ module Bundler
"#<#{self.class}:0x#{object_id} #{self}>"
end
- def to_err
+ def identifier
to_s
end
diff --git a/lib/bundler/source/git.rb b/lib/bundler/source/git.rb
index fb13ca05786..a41a2f23e96 100644
--- a/lib/bundler/source/git.rb
+++ b/lib/bundler/source/git.rb
@@ -42,7 +42,7 @@ module Bundler
%w[ref branch tag submodules].each do |opt|
out << " #{opt}: #{options[opt]}\n" if options[opt]
end
- out << " glob: #{@glob}\n" unless @glob == DEFAULT_GLOB
+ out << " glob: #{@glob}\n" unless default_glob?
out << " specs:\n"
end
@@ -75,12 +75,20 @@ module Bundler
git_proxy.branch
end
- rev = " (at #{at}@#{shortref_for_display(revision)})"
+ rev = "at #{at}@#{shortref_for_display(revision)}"
rescue GitError
""
end
- "#{@safe_uri}#{rev}"
+ specifiers = [rev, glob_for_display].compact
+ suffix =
+ if specifiers.any?
+ " (#{specifiers.join(", ")})"
+ else
+ ""
+ end
+
+ "#{@safe_uri}#{suffix}"
end
def name
@@ -282,6 +290,14 @@ module Bundler
ref[0..11]
end
+ def glob_for_display
+ default_glob? ? nil : "glob: #{@glob}"
+ end
+
+ def default_glob?
+ @glob == DEFAULT_GLOB
+ end
+
def uri_hash
if uri =~ %r{^\w+://(\w+@)?}
# Downcase the domain component of the URI
@@ -291,7 +307,9 @@ module Bundler
# If there is no URI scheme, assume it is an ssh/git URI
input = uri
end
- SharedHelpers.digest(:SHA1).hexdigest(input)
+ # We use SHA1 here for historical reason and to preserve backward compatibility.
+ # But a transition to a simpler mangling algorithm would be welcome.
+ Bundler::Digest.sha1(input)
end
def cached_revision
diff --git a/lib/bundler/source/git/git_proxy.rb b/lib/bundler/source/git/git_proxy.rb
index 7555561edd5..e37ff8724a3 100644
--- a/lib/bundler/source/git/git_proxy.rb
+++ b/lib/bundler/source/git/git_proxy.rb
@@ -56,7 +56,6 @@ module Bundler
@ref = ref
@revision = revision
@git = git
- raise GitNotInstalledError.new if allow? && !Bundler.git_present?
end
def revision
@@ -208,7 +207,11 @@ module Bundler
end
def allow?
- @git ? @git.allow_git_ops? : true
+ allowed = @git ? @git.allow_git_ops? : true
+
+ raise GitNotInstalledError.new if allowed && !Bundler.git_present?
+
+ allowed
end
def with_path(&blk)
diff --git a/lib/bundler/source/rubygems.rb b/lib/bundler/source/rubygems.rb
index 7f8699b91c1..8bc3aa17e98 100644
--- a/lib/bundler/source/rubygems.rb
+++ b/lib/bundler/source/rubygems.rb
@@ -98,26 +98,30 @@ module Bundler
out << " specs:\n"
end
- def to_err
+ def to_s
if remotes.empty?
"locally installed gems"
- elsif @allow_remote
+ elsif @allow_remote && @allow_cached && @allow_local
+ "rubygems repository #{remote_names}, cached gems or installed locally"
+ elsif @allow_remote && @allow_local
"rubygems repository #{remote_names} or installed locally"
- elsif @allow_cached
- "cached gems from rubygems repository #{remote_names} or installed locally"
+ elsif @allow_remote
+ "rubygems repository #{remote_names}"
+ elsif @allow_cached && @allow_local
+ "cached gems or installed locally"
else
"locally installed gems"
end
end
- def to_s
+ def identifier
if remotes.empty?
"locally installed gems"
else
- "rubygems repository #{remote_names} or installed locally"
+ "rubygems repository #{remote_names}"
end
end
- alias_method :name, :to_s
+ alias_method :name, :identifier
def specs
@specs ||= begin
@@ -135,7 +139,7 @@ module Bundler
force = opts[:force]
ensure_builtin_gems_cached = opts[:ensure_builtin_gems_cached]
- if ensure_builtin_gems_cached && builtin_gem?(spec)
+ if ensure_builtin_gems_cached && spec.default_gem?
if !cached_path(spec)
cached_built_in_gem(spec) unless spec.remote
force = true
@@ -162,7 +166,7 @@ module Bundler
begin
s = Bundler.rubygems.spec_from_gem(path, Bundler.settings["trust-policy"])
spec.__swap__(s)
- rescue StandardError
+ rescue Gem::Package::FormatError
Bundler.rm_rf(path)
raise
end
@@ -174,6 +178,7 @@ module Bundler
Bundler.ui.confirm message
path = cached_gem(spec)
+ raise GemNotFound, "Could not find #{spec.file_name} for installation" unless path
if requires_sudo?
install_path = Bundler.tmp(spec.full_name)
bin_path = install_path.join("bin")
@@ -233,12 +238,8 @@ module Bundler
end
def cache(spec, custom_path = nil)
- if builtin_gem?(spec)
- cached_path = cached_built_in_gem(spec)
- else
- cached_path = cached_gem(spec)
- end
- raise GemNotFound, "Missing gem file '#{spec.full_name}.gem'." unless cached_path
+ cached_path = cached_gem(spec)
+ raise GemNotFound, "Missing gem file '#{spec.file_name}'." unless cached_path
return if File.dirname(cached_path) == Bundler.app_cache.to_s
Bundler.ui.info " * #{File.basename(cached_path)}"
FileUtils.cp(cached_path, Bundler.app_cache(custom_path))
@@ -265,10 +266,6 @@ module Bundler
@remotes.unshift(uri) unless @remotes.include?(uri)
end
- def equivalent_remotes?(other_remotes)
- other_remotes.map(&method(:remove_auth)) == @remotes.map(&method(:remove_auth))
- end
-
def spec_names
if @allow_remote && dependency_api_available?
remote_specs.spec_names
@@ -337,7 +334,11 @@ module Bundler
end
def credless_remotes
- remotes.map(&method(:suppress_configured_credentials))
+ if Bundler.settings[:allow_deployment_source_credential_changes]
+ remotes.map(&method(:remove_auth))
+ else
+ remotes.map(&method(:suppress_configured_credentials))
+ end
end
def remotes_for_spec(spec)
@@ -352,14 +353,17 @@ module Bundler
end
def cached_gem(spec)
- cached_gem = cached_path(spec)
- unless cached_gem
- raise Bundler::GemNotFound, "Could not find #{spec.file_name} for installation"
+ if spec.default_gem?
+ cached_built_in_gem(spec)
+ else
+ cached_path(spec)
end
- cached_gem
end
def cached_path(spec)
+ global_cache_path = download_cache_path(spec)
+ @caches << global_cache_path if global_cache_path
+
possibilities = @caches.map {|p| "#{p}/#{spec.file_name}" }
possibilities.find {|p| File.exist?(p) }
end
@@ -459,19 +463,26 @@ module Bundler
spec.fetch_platform
- download_path = requires_sudo? ? Bundler.tmp(spec.full_name) : rubygems_dir
- gem_path = "#{rubygems_dir}/cache/#{spec.full_name}.gem"
+ cache_path = download_cache_path(spec) || default_cache_path_for(rubygems_dir)
+ gem_path = "#{cache_path}/#{spec.file_name}"
- SharedHelpers.filesystem_access("#{download_path}/cache") do |p|
+ if requires_sudo?
+ download_path = Bundler.tmp(spec.full_name)
+ download_cache_path = default_cache_path_for(download_path)
+ else
+ download_cache_path = cache_path
+ end
+
+ SharedHelpers.filesystem_access(download_cache_path) do |p|
FileUtils.mkdir_p(p)
end
- download_gem(spec, download_path)
+ download_gem(spec, download_cache_path)
if requires_sudo?
- SharedHelpers.filesystem_access("#{rubygems_dir}/cache") do |p|
+ SharedHelpers.filesystem_access(cache_path) do |p|
Bundler.mkdir_p(p)
end
- Bundler.sudo "mv #{download_path}/cache/#{spec.full_name}.gem #{gem_path}"
+ Bundler.sudo "mv #{download_cache_path}/#{spec.file_name} #{gem_path}"
end
gem_path
@@ -479,16 +490,8 @@ module Bundler
Bundler.rm_rf(download_path) if requires_sudo?
end
- def builtin_gem?(spec)
- # Ruby 2.1, where all included gems have this summary
- return true if spec.summary =~ /is bundled with Ruby/
-
- # Ruby 2.0, where gemspecs are stored in specifications/default/
- spec.loaded_from && spec.loaded_from.include?("specifications/default/")
- end
-
def installed?(spec)
- installed_specs[spec].any?
+ installed_specs[spec].any? && !spec.deleted_gem?
end
def requires_sudo?
@@ -499,6 +502,10 @@ module Bundler
Bundler.rubygems.gem_dir
end
+ def default_cache_path_for(dir)
+ "#{dir}/cache"
+ end
+
def cache_path
Bundler.app_cache
end
@@ -511,52 +518,13 @@ module Bundler
# @param [Specification] spec
# the spec we want to download or retrieve from the cache.
#
- # @param [String] download_path
+ # @param [String] download_cache_path
# the local directory the .gem will end up in.
#
- def download_gem(spec, download_path)
- local_path = File.join(download_path, "cache/#{spec.full_name}.gem")
-
- if (cache_path = download_cache_path(spec)) && cache_path.file?
- SharedHelpers.filesystem_access(local_path) do
- FileUtils.cp(cache_path, local_path)
- end
- else
- uri = spec.remote.uri
- Bundler.ui.confirm("Fetching #{version_message(spec)}")
- rubygems_local_path = Bundler.rubygems.download_gem(spec, uri, download_path)
-
- # older rubygems return varying file:// variants depending on version
- rubygems_local_path = rubygems_local_path.gsub(/\Afile:/, "") unless Bundler.rubygems.provides?(">= 3.2.0.rc.2")
- rubygems_local_path = rubygems_local_path.gsub(%r{\A//}, "") if Bundler.rubygems.provides?("< 3.1.0")
-
- if rubygems_local_path != local_path
- SharedHelpers.filesystem_access(local_path) do
- FileUtils.mv(rubygems_local_path, local_path)
- end
- end
- cache_globally(spec, local_path)
- end
- end
-
- # Checks if the requested spec exists in the global cache. If it does
- # not, we create the relevant global cache subdirectory if it does not
- # exist and copy the spec from the local cache to the global cache.
- #
- # @param [Specification] spec
- # the spec we want to copy to the global cache.
- #
- # @param [String] local_cache_path
- # the local directory from which we want to copy the .gem.
- #
- def cache_globally(spec, local_cache_path)
- return unless cache_path = download_cache_path(spec)
- return if cache_path.exist?
-
- SharedHelpers.filesystem_access(cache_path.dirname, &:mkpath)
- SharedHelpers.filesystem_access(cache_path) do
- FileUtils.cp(local_cache_path, cache_path)
- end
+ def download_gem(spec, download_cache_path)
+ uri = spec.remote.uri
+ Bundler.ui.confirm("Fetching #{version_message(spec)}")
+ Bundler.rubygems.download_gem(spec, uri, download_cache_path)
end
# Returns the global cache path of the calling Rubygems::Source object.
@@ -575,7 +543,7 @@ module Bundler
return unless remote = spec.remote
return unless cache_slug = remote.cache_slug
- Bundler.user_cache.join("gems", cache_slug, spec.file_name)
+ Bundler.user_cache.join("gems", cache_slug)
end
def extension_cache_slug(spec)
diff --git a/lib/bundler/source/rubygems_aggregate.rb b/lib/bundler/source/rubygems_aggregate.rb
index 09cf4002eab..99ef81ad54b 100644
--- a/lib/bundler/source/rubygems_aggregate.rb
+++ b/lib/bundler/source/rubygems_aggregate.rb
@@ -16,7 +16,7 @@ module Bundler
@index
end
- def to_err
+ def identifier
to_s
end
diff --git a/lib/bundler/source_list.rb b/lib/bundler/source_list.rb
index d6310b78c06..a4773397c7d 100644
--- a/lib/bundler/source_list.rb
+++ b/lib/bundler/source_list.rb
@@ -98,7 +98,7 @@ module Bundler
end
def get(source)
- source_list_for(source).find {|s| equal_source?(source, s) || equivalent_source?(source, s) }
+ source_list_for(source).find {|s| equivalent_source?(source, s) }
end
def lock_sources
@@ -106,14 +106,14 @@ module Bundler
end
def lock_other_sources
- (path_sources + git_sources + plugin_sources).sort_by(&:to_s)
+ (path_sources + git_sources + plugin_sources).sort_by(&:identifier)
end
def lock_rubygems_sources
if merged_gem_lockfile_sections?
[combine_rubygems_sources]
else
- rubygems_sources.sort_by(&:to_s)
+ rubygems_sources.sort_by(&:identifier)
end
end
@@ -173,7 +173,7 @@ module Bundler
end
def different_sources?(lock_sources, replacement_sources)
- !equal_sources?(lock_sources, replacement_sources) && !equivalent_sources?(lock_sources, replacement_sources)
+ !equivalent_sources?(lock_sources, replacement_sources)
end
def rubygems_aggregate_class
@@ -210,34 +210,12 @@ module Bundler
end
end
- def equal_sources?(lock_sources, replacement_sources)
- lock_sources.sort_by(&:to_s) == replacement_sources.sort_by(&:to_s)
- end
-
- def equal_source?(source, other_source)
- return source.include?(other_source) if source.is_a?(Source::Rubygems) && other_source.is_a?(Source::Rubygems)
-
- source == other_source
- end
-
- def equivalent_source?(source, other_source)
- return false unless Bundler.settings[:allow_deployment_source_credential_changes] && source.is_a?(Source::Rubygems)
-
- equivalent_rubygems_sources?([source], [other_source])
- end
-
def equivalent_sources?(lock_sources, replacement_sources)
- return false unless Bundler.settings[:allow_deployment_source_credential_changes]
-
- lock_rubygems_sources, lock_other_sources = lock_sources.partition {|s| s.is_a?(Source::Rubygems) }
- replacement_rubygems_sources, replacement_other_sources = replacement_sources.partition {|s| s.is_a?(Source::Rubygems) }
-
- equivalent_rubygems_sources?(lock_rubygems_sources, replacement_rubygems_sources) && equal_sources?(lock_other_sources, replacement_other_sources)
+ lock_sources.sort_by(&:identifier) == replacement_sources.sort_by(&:identifier)
end
- def equivalent_rubygems_sources?(lock_sources, replacement_sources)
- actual_remotes = replacement_sources.map(&:remotes).flatten.uniq
- lock_sources.all? {|s| s.equivalent_remotes?(actual_remotes) }
+ def equivalent_source?(source, other_source)
+ source == other_source
end
end
end
diff --git a/lib/bundler/spec_set.rb b/lib/bundler/spec_set.rb
index 26d41cb9b8d..a19d18388ab 100644
--- a/lib/bundler/spec_set.rb
+++ b/lib/bundler/spec_set.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require "tsort"
+require_relative "vendored_tsort"
module Bundler
class SpecSet
diff --git a/lib/bundler/templates/newgem/github/workflows/main.yml.tt b/lib/bundler/templates/newgem/github/workflows/main.yml.tt
index 952cd649a24..6570d177afe 100644
--- a/lib/bundler/templates/newgem/github/workflows/main.yml.tt
+++ b/lib/bundler/templates/newgem/github/workflows/main.yml.tt
@@ -10,11 +10,11 @@ on:
jobs:
build:
runs-on: ubuntu-latest
-
+ name: Ruby ${{ matrix.ruby }}
strategy:
matrix:
ruby:
- - <%= RUBY_VERSION %>
+ - '<%= RUBY_VERSION %>'
steps:
- uses: actions/checkout@v2
diff --git a/lib/bundler/templates/newgem/sig/newgem.rbs.tt b/lib/bundler/templates/newgem/sig/newgem.rbs.tt
new file mode 100644
index 00000000000..eb7b380bbb9
--- /dev/null
+++ b/lib/bundler/templates/newgem/sig/newgem.rbs.tt
@@ -0,0 +1,8 @@
+<%- config[:constant_array].each_with_index do |c, i| -%>
+<%= " " * i %>module <%= c %>
+<%- end -%>
+<%= " " * config[:constant_array].size %>VERSION: String
+<%= " " * config[:constant_array].size %># See the writing guide of rbs: https://github.com/ruby/rbs#guides
+<%- (config[:constant_array].size-1).downto(0) do |i| -%>
+<%= " " * i %>end
+<%- end -%>
diff --git a/lib/bundler/templates/newgem/standard.yml.tt b/lib/bundler/templates/newgem/standard.yml.tt
index e720f410313..9e88fbbe8bb 100644
--- a/lib/bundler/templates/newgem/standard.yml.tt
+++ b/lib/bundler/templates/newgem/standard.yml.tt
@@ -1,4 +1,2 @@
# For available configuration options, see:
# https://github.com/testdouble/standard
-
-default_ignores: false
diff --git a/lib/bundler/vendor/.document b/lib/bundler/vendor/.document
new file mode 100644
index 00000000000..0c43bbd6b38
--- /dev/null
+++ b/lib/bundler/vendor/.document
@@ -0,0 +1 @@
+# Vendored files do not need to be documented
diff --git a/lib/bundler/vendor/connection_pool/lib/connection_pool/wrapper.rb b/lib/bundler/vendor/connection_pool/lib/connection_pool/wrapper.rb
index 880170c06b0..9d94c2c0f09 100644
--- a/lib/bundler/vendor/connection_pool/lib/connection_pool/wrapper.rb
+++ b/lib/bundler/vendor/connection_pool/lib/connection_pool/wrapper.rb
@@ -32,13 +32,13 @@ class Bundler::ConnectionPool
# rubocop:disable Style/MethodMissingSuper
# rubocop:disable Style/MissingRespondToMissing
- if ::RUBY_VERSION >= "3.0.0"
+ if ::Gem.ruby_version >= ::Gem::Version.new("3.0.0")
def method_missing(name, *args, **kwargs, &block)
with do |connection|
connection.send(name, *args, **kwargs, &block)
end
end
- elsif ::RUBY_VERSION >= "2.7.0"
+ elsif ::Gem.ruby_version >= ::Gem::Version.new("2.7.0")
ruby2_keywords def method_missing(name, *args, &block)
with do |connection|
connection.send(name, *args, &block)
diff --git a/lib/bundler/vendor/molinillo/lib/molinillo/dependency_graph.rb b/lib/bundler/vendor/molinillo/lib/molinillo/dependency_graph.rb
index 936399ed2f5..10a25d2f08a 100644
--- a/lib/bundler/vendor/molinillo/lib/molinillo/dependency_graph.rb
+++ b/lib/bundler/vendor/molinillo/lib/molinillo/dependency_graph.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'tsort'
+require_relative '../../../../vendored_tsort'
require_relative 'dependency_graph/log'
require_relative 'dependency_graph/vertex'
@@ -17,7 +17,7 @@ module Bundler::Molinillo
vertices.values.each { |v| yield v }
end
- include TSort
+ include Bundler::TSort
# @!visibility private
alias tsort_each_node each
diff --git a/lib/bundler/vendor/tsort/lib/tsort.rb b/lib/bundler/vendor/tsort/lib/tsort.rb
new file mode 100644
index 00000000000..8454583295e
--- /dev/null
+++ b/lib/bundler/vendor/tsort/lib/tsort.rb
@@ -0,0 +1,453 @@
+# frozen_string_literal: true
+
+#--
+# tsort.rb - provides a module for topological sorting and strongly connected components.
+#++
+#
+
+#
+# TSort implements topological sorting using Tarjan's algorithm for
+# strongly connected components.
+#
+# TSort is designed to be able to be used with any object which can be
+# interpreted as a directed graph.
+#
+# TSort requires two methods to interpret an object as a graph,
+# tsort_each_node and tsort_each_child.
+#
+# * tsort_each_node is used to iterate for all nodes over a graph.
+# * tsort_each_child is used to iterate for child nodes of a given node.
+#
+# The equality of nodes are defined by eql? and hash since
+# TSort uses Hash internally.
+#
+# == A Simple Example
+#
+# The following example demonstrates how to mix the TSort module into an
+# existing class (in this case, Hash). Here, we're treating each key in
+# the hash as a node in the graph, and so we simply alias the required
+# #tsort_each_node method to Hash's #each_key method. For each key in the
+# hash, the associated value is an array of the node's child nodes. This
+# choice in turn leads to our implementation of the required #tsort_each_child
+# method, which fetches the array of child nodes and then iterates over that
+# array using the user-supplied block.
+#
+# require 'tsort'
+#
+# class Hash
+# include TSort
+# alias tsort_each_node each_key
+# def tsort_each_child(node, &block)
+# fetch(node).each(&block)
+# end
+# end
+#
+# {1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort
+# #=> [3, 2, 1, 4]
+#
+# {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components
+# #=> [[4], [2, 3], [1]]
+#
+# == A More Realistic Example
+#
+# A very simple `make' like tool can be implemented as follows:
+#
+# require 'tsort'
+#
+# class Make
+# def initialize
+# @dep = {}
+# @dep.default = []
+# end
+#
+# def rule(outputs, inputs=[], &block)
+# triple = [outputs, inputs, block]
+# outputs.each {|f| @dep[f] = [triple]}
+# @dep[triple] = inputs
+# end
+#
+# def build(target)
+# each_strongly_connected_component_from(target) {|ns|
+# if ns.length != 1
+# fs = ns.delete_if {|n| Array === n}
+# raise TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}")
+# end
+# n = ns.first
+# if Array === n
+# outputs, inputs, block = n
+# inputs_time = inputs.map {|f| File.mtime f}.max
+# begin
+# outputs_time = outputs.map {|f| File.mtime f}.min
+# rescue Errno::ENOENT
+# outputs_time = nil
+# end
+# if outputs_time == nil ||
+# inputs_time != nil && outputs_time <= inputs_time
+# sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i
+# block.call
+# end
+# end
+# }
+# end
+#
+# def tsort_each_child(node, &block)
+# @dep[node].each(&block)
+# end
+# include TSort
+# end
+#
+# def command(arg)
+# print arg, "\n"
+# system arg
+# end
+#
+# m = Make.new
+# m.rule(%w[t1]) { command 'date > t1' }
+# m.rule(%w[t2]) { command 'date > t2' }
+# m.rule(%w[t3]) { command 'date > t3' }
+# m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' }
+# m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' }
+# m.build('t5')
+#
+# == Bugs
+#
+# * 'tsort.rb' is wrong name because this library uses
+# Tarjan's algorithm for strongly connected components.
+# Although 'strongly_connected_components.rb' is correct but too long.
+#
+# == References
+#
+# R. E. Tarjan, "Depth First Search and Linear Graph Algorithms",
+# <em>SIAM Journal on Computing</em>, Vol. 1, No. 2, pp. 146-160, June 1972.
+#
+module Bundler
+ module TSort
+ class Cyclic < StandardError
+ end
+
+ # Returns a topologically sorted array of nodes.
+ # The array is sorted from children to parents, i.e.
+ # the first element has no child and the last node has no parent.
+ #
+ # If there is a cycle, TSort::Cyclic is raised.
+ #
+ # class G
+ # include TSort
+ # def initialize(g)
+ # @g = g
+ # end
+ # def tsort_each_child(n, &b) @g[n].each(&b) end
+ # def tsort_each_node(&b) @g.each_key(&b) end
+ # end
+ #
+ # graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
+ # p graph.tsort #=> [4, 2, 3, 1]
+ #
+ # graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
+ # p graph.tsort # raises TSort::Cyclic
+ #
+ def tsort
+ each_node = method(:tsort_each_node)
+ each_child = method(:tsort_each_child)
+ TSort.tsort(each_node, each_child)
+ end
+
+ # Returns a topologically sorted array of nodes.
+ # The array is sorted from children to parents, i.e.
+ # the first element has no child and the last node has no parent.
+ #
+ # The graph is represented by _each_node_ and _each_child_.
+ # _each_node_ should have +call+ method which yields for each node in the graph.
+ # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
+ #
+ # If there is a cycle, TSort::Cyclic is raised.
+ #
+ # g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # p TSort.tsort(each_node, each_child) #=> [4, 2, 3, 1]
+ #
+ # g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # p TSort.tsort(each_node, each_child) # raises TSort::Cyclic
+ #
+ def TSort.tsort(each_node, each_child)
+ TSort.tsort_each(each_node, each_child).to_a
+ end
+
+ # The iterator version of the #tsort method.
+ # <tt><em>obj</em>.tsort_each</tt> is similar to <tt><em>obj</em>.tsort.each</tt>, but
+ # modification of _obj_ during the iteration may lead to unexpected results.
+ #
+ # #tsort_each returns +nil+.
+ # If there is a cycle, TSort::Cyclic is raised.
+ #
+ # class G
+ # include TSort
+ # def initialize(g)
+ # @g = g
+ # end
+ # def tsort_each_child(n, &b) @g[n].each(&b) end
+ # def tsort_each_node(&b) @g.each_key(&b) end
+ # end
+ #
+ # graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
+ # graph.tsort_each {|n| p n }
+ # #=> 4
+ # # 2
+ # # 3
+ # # 1
+ #
+ def tsort_each(&block) # :yields: node
+ each_node = method(:tsort_each_node)
+ each_child = method(:tsort_each_child)
+ TSort.tsort_each(each_node, each_child, &block)
+ end
+
+ # The iterator version of the TSort.tsort method.
+ #
+ # The graph is represented by _each_node_ and _each_child_.
+ # _each_node_ should have +call+ method which yields for each node in the graph.
+ # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
+ #
+ # g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # TSort.tsort_each(each_node, each_child) {|n| p n }
+ # #=> 4
+ # # 2
+ # # 3
+ # # 1
+ #
+ def TSort.tsort_each(each_node, each_child) # :yields: node
+ return to_enum(__method__, each_node, each_child) unless block_given?
+
+ TSort.each_strongly_connected_component(each_node, each_child) {|component|
+ if component.size == 1
+ yield component.first
+ else
+ raise Cyclic.new("topological sort failed: #{component.inspect}")
+ end
+ }
+ end
+
+ # Returns strongly connected components as an array of arrays of nodes.
+ # The array is sorted from children to parents.
+ # Each elements of the array represents a strongly connected component.
+ #
+ # class G
+ # include TSort
+ # def initialize(g)
+ # @g = g
+ # end
+ # def tsort_each_child(n, &b) @g[n].each(&b) end
+ # def tsort_each_node(&b) @g.each_key(&b) end
+ # end
+ #
+ # graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
+ # p graph.strongly_connected_components #=> [[4], [2], [3], [1]]
+ #
+ # graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
+ # p graph.strongly_connected_components #=> [[4], [2, 3], [1]]
+ #
+ def strongly_connected_components
+ each_node = method(:tsort_each_node)
+ each_child = method(:tsort_each_child)
+ TSort.strongly_connected_components(each_node, each_child)
+ end
+
+ # Returns strongly connected components as an array of arrays of nodes.
+ # The array is sorted from children to parents.
+ # Each elements of the array represents a strongly connected component.
+ #
+ # The graph is represented by _each_node_ and _each_child_.
+ # _each_node_ should have +call+ method which yields for each node in the graph.
+ # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
+ #
+ # g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # p TSort.strongly_connected_components(each_node, each_child)
+ # #=> [[4], [2], [3], [1]]
+ #
+ # g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # p TSort.strongly_connected_components(each_node, each_child)
+ # #=> [[4], [2, 3], [1]]
+ #
+ def TSort.strongly_connected_components(each_node, each_child)
+ TSort.each_strongly_connected_component(each_node, each_child).to_a
+ end
+
+ # The iterator version of the #strongly_connected_components method.
+ # <tt><em>obj</em>.each_strongly_connected_component</tt> is similar to
+ # <tt><em>obj</em>.strongly_connected_components.each</tt>, but
+ # modification of _obj_ during the iteration may lead to unexpected results.
+ #
+ # #each_strongly_connected_component returns +nil+.
+ #
+ # class G
+ # include TSort
+ # def initialize(g)
+ # @g = g
+ # end
+ # def tsort_each_child(n, &b) @g[n].each(&b) end
+ # def tsort_each_node(&b) @g.each_key(&b) end
+ # end
+ #
+ # graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
+ # graph.each_strongly_connected_component {|scc| p scc }
+ # #=> [4]
+ # # [2]
+ # # [3]
+ # # [1]
+ #
+ # graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
+ # graph.each_strongly_connected_component {|scc| p scc }
+ # #=> [4]
+ # # [2, 3]
+ # # [1]
+ #
+ def each_strongly_connected_component(&block) # :yields: nodes
+ each_node = method(:tsort_each_node)
+ each_child = method(:tsort_each_child)
+ TSort.each_strongly_connected_component(each_node, each_child, &block)
+ end
+
+ # The iterator version of the TSort.strongly_connected_components method.
+ #
+ # The graph is represented by _each_node_ and _each_child_.
+ # _each_node_ should have +call+ method which yields for each node in the graph.
+ # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
+ #
+ # g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # TSort.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
+ # #=> [4]
+ # # [2]
+ # # [3]
+ # # [1]
+ #
+ # g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # TSort.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
+ # #=> [4]
+ # # [2, 3]
+ # # [1]
+ #
+ def TSort.each_strongly_connected_component(each_node, each_child) # :yields: nodes
+ return to_enum(__method__, each_node, each_child) unless block_given?
+
+ id_map = {}
+ stack = []
+ each_node.call {|node|
+ unless id_map.include? node
+ TSort.each_strongly_connected_component_from(node, each_child, id_map, stack) {|c|
+ yield c
+ }
+ end
+ }
+ nil
+ end
+
+ # Iterates over strongly connected component in the subgraph reachable from
+ # _node_.
+ #
+ # Return value is unspecified.
+ #
+ # #each_strongly_connected_component_from doesn't call #tsort_each_node.
+ #
+ # class G
+ # include TSort
+ # def initialize(g)
+ # @g = g
+ # end
+ # def tsort_each_child(n, &b) @g[n].each(&b) end
+ # def tsort_each_node(&b) @g.each_key(&b) end
+ # end
+ #
+ # graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
+ # graph.each_strongly_connected_component_from(2) {|scc| p scc }
+ # #=> [4]
+ # # [2]
+ #
+ # graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
+ # graph.each_strongly_connected_component_from(2) {|scc| p scc }
+ # #=> [4]
+ # # [2, 3]
+ #
+ def each_strongly_connected_component_from(node, id_map={}, stack=[], &block) # :yields: nodes
+ TSort.each_strongly_connected_component_from(node, method(:tsort_each_child), id_map, stack, &block)
+ end
+
+ # Iterates over strongly connected components in a graph.
+ # The graph is represented by _node_ and _each_child_.
+ #
+ # _node_ is the first node.
+ # _each_child_ should have +call+ method which takes a node argument
+ # and yields for each child node.
+ #
+ # Return value is unspecified.
+ #
+ # #TSort.each_strongly_connected_component_from is a class method and
+ # it doesn't need a class to represent a graph which includes TSort.
+ #
+ # graph = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
+ # each_child = lambda {|n, &b| graph[n].each(&b) }
+ # TSort.each_strongly_connected_component_from(1, each_child) {|scc|
+ # p scc
+ # }
+ # #=> [4]
+ # # [2, 3]
+ # # [1]
+ #
+ def TSort.each_strongly_connected_component_from(node, each_child, id_map={}, stack=[]) # :yields: nodes
+ return to_enum(__method__, node, each_child, id_map, stack) unless block_given?
+
+ minimum_id = node_id = id_map[node] = id_map.size
+ stack_length = stack.length
+ stack << node
+
+ each_child.call(node) {|child|
+ if id_map.include? child
+ child_id = id_map[child]
+ minimum_id = child_id if child_id && child_id < minimum_id
+ else
+ sub_minimum_id =
+ TSort.each_strongly_connected_component_from(child, each_child, id_map, stack) {|c|
+ yield c
+ }
+ minimum_id = sub_minimum_id if sub_minimum_id < minimum_id
+ end
+ }
+
+ if node_id == minimum_id
+ component = stack.slice!(stack_length .. -1)
+ component.each {|n| id_map[n] = nil}
+ yield component
+ end
+
+ minimum_id
+ end
+
+ # Should be implemented by a extended class.
+ #
+ # #tsort_each_node is used to iterate for all nodes over a graph.
+ #
+ def tsort_each_node # :yields: node
+ raise NotImplementedError.new
+ end
+
+ # Should be implemented by a extended class.
+ #
+ # #tsort_each_child is used to iterate for child nodes of _node_.
+ #
+ def tsort_each_child(node) # :yields: child
+ raise NotImplementedError.new
+ end
+ end
+end
diff --git a/lib/bundler/vendored_tsort.rb b/lib/bundler/vendored_tsort.rb
new file mode 100644
index 00000000000..38aed0b5def
--- /dev/null
+++ b/lib/bundler/vendored_tsort.rb
@@ -0,0 +1,4 @@
+# frozen_string_literal: true
+
+module Bundler; end
+require_relative "vendor/tsort/lib/tsort"
diff --git a/lib/cgi.rb b/lib/cgi.rb
index 3b53d27a2e2..1a03d064f1b 100644
--- a/lib/cgi.rb
+++ b/lib/cgi.rb
@@ -288,7 +288,7 @@
#
class CGI
- VERSION = "0.2.0"
+ VERSION = "0.3.1"
end
require 'cgi/core'
diff --git a/lib/cgi/cgi.gemspec b/lib/cgi/cgi.gemspec
index 5d23ef0f614..3ba62b93f6d 100644
--- a/lib/cgi/cgi.gemspec
+++ b/lib/cgi/cgi.gemspec
@@ -23,9 +23,9 @@ Gem::Specification.new do |spec|
spec.metadata["source_code_uri"] = spec.homepage
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
- `git ls-files -z 2>/dev/null`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
+ `git ls-files -z 2>/dev/null`.split("\x0").reject { |f| f.match(%r{\A(?:(?:test|spec|features)/|\.git)}) }
end
- spec.bindir = "exe"
+ spec.extensions = ["ext/cgi/escape/extconf.rb"]
spec.executables = []
spec.require_paths = ["lib"]
end
diff --git a/lib/cgi/cookie.rb b/lib/cgi/cookie.rb
index ae9ab58edef..6b0d89ca3ba 100644
--- a/lib/cgi/cookie.rb
+++ b/lib/cgi/cookie.rb
@@ -159,7 +159,6 @@ class CGI
raw_cookie.split(/;\s?/).each do |pairs|
name, values = pairs.split('=',2)
next unless name and values
- name = CGI.unescape(name)
values ||= ""
values = values.split('&').collect{|v| CGI.unescape(v,@@accept_charset) }
if cookies.has_key?(name)
diff --git a/lib/csv.rb b/lib/csv.rb
index 868f8e5b0e9..42e99435cbf 100644
--- a/lib/csv.rb
+++ b/lib/csv.rb
@@ -90,11 +90,11 @@
# with any questions.
require "forwardable"
-require "English"
require "date"
require "stringio"
require_relative "csv/fields_converter"
+require_relative "csv/input_record_separator"
require_relative "csv/match_p"
require_relative "csv/parser"
require_relative "csv/row"
@@ -502,7 +502,7 @@ using CSV::MatchP if CSV.const_defined?(:MatchP)
# [" 1 ", #<struct CSV::FieldInfo index=1, line=2, header=nil>]
# [" baz ", #<struct CSV::FieldInfo index=0, line=3, header=nil>]
# [" 2 ", #<struct CSV::FieldInfo index=1, line=3, header=nil>]
-# Each CSV::Info object shows:
+# Each CSV::FieldInfo object shows:
# - The 0-based field index.
# - The 1-based line index.
# - The field header, if any.
@@ -536,6 +536,14 @@ using CSV::MatchP if CSV.const_defined?(:MatchP)
#
# There is no such storage structure for write headers.
#
+# In order for the parsing methods to access stored converters in non-main-Ractors, the
+# storage structure must be made shareable first.
+# Therefore, <tt>Ractor.make_shareable(CSV::Converters)</tt> and
+# <tt>Ractor.make_shareable(CSV::HeaderConverters)</tt> must be called before the creation
+# of Ractors that use the converters stored in these structures. (Since making the storage
+# structures shareable involves freezing them, any custom converters that are to be used
+# must be added first.)
+#
# ===== Converter Lists
#
# A _converter_ _list_ is an \Array that may include any assortment of:
@@ -908,6 +916,7 @@ class CSV
gsub(/\s+/, "_").to_sym
}
}
+
# Default values for method options.
DEFAULT_OPTIONS = {
# For both parsing and generating.
@@ -946,6 +955,8 @@ class CSV
# Creates or retrieves cached \CSV objects.
# For arguments and options, see CSV.new.
#
+ # This API is not Ractor-safe.
+ #
# ---
#
# With no block given, returns a \CSV object.
@@ -1051,7 +1062,7 @@ class CSV
# out_string # => "FOO,0000\nBAR,1111\nBAZ,2222\n"
def filter(input=nil, output=nil, **options)
# parse options for input, output, or both
- in_options, out_options = Hash.new, {row_sep: $INPUT_RECORD_SEPARATOR}
+ in_options, out_options = Hash.new, {row_sep: InputRecordSeparator.value}
options.each do |key, value|
case key.to_s
when /\Ain(?:put)?_(.+)\Z/
@@ -1292,8 +1303,8 @@ class CSV
# Argument +ary+ must be an \Array.
#
# Special options:
- # * Option <tt>:row_sep</tt> defaults to <tt>$INPUT_RECORD_SEPARATOR</tt>
- # (<tt>$/</tt>).:
+ # * Option <tt>:row_sep</tt> defaults to <tt>"\n"> on Ruby 3.0 or later
+ # and <tt>$INPUT_RECORD_SEPARATOR</tt> (<tt>$/</tt>) otherwise.:
# $INPUT_RECORD_SEPARATOR # => "\n"
# * This method accepts an additional option, <tt>:encoding</tt>, which sets the base
# Encoding for the output. This method will try to guess your Encoding from
@@ -1315,7 +1326,7 @@ class CSV
# CSV.generate_line(:foo)
#
def generate_line(row, **options)
- options = {row_sep: $INPUT_RECORD_SEPARATOR}.merge(options)
+ options = {row_sep: InputRecordSeparator.value}.merge(options)
str = +""
if options[:encoding]
str.force_encoding(options[:encoding])
@@ -1873,6 +1884,10 @@ class CSV
# csv.converters # => [:integer]
# csv.convert(proc {|x| x.to_s })
# csv.converters
+ #
+ # Notes that you need to call
+ # +Ractor.make_shareable(CSV::Converters)+ on the main Ractor to use
+ # this method.
def converters
parser_fields_converter.map do |converter|
name = Converters.rassoc(converter)
@@ -1935,6 +1950,10 @@ class CSV
# Returns an \Array containing header converters; used for parsing;
# see {Header Converters}[#class-CSV-label-Header+Converters]:
# CSV.new('').header_converters # => []
+ #
+ # Notes that you need to call
+ # +Ractor.make_shareable(CSV::HeaderConverters)+ on the main Ractor
+ # to use this method.
def header_converters
header_fields_converter.map do |converter|
name = HeaderConverters.rassoc(converter)
@@ -2575,7 +2594,7 @@ class CSV
def build_parser_fields_converter
specific_options = {
- builtin_converters: Converters,
+ builtin_converters_name: :Converters,
}
options = @base_fields_converter_options.merge(specific_options)
build_fields_converter(@initial_converters, options)
@@ -2587,7 +2606,7 @@ class CSV
def build_header_fields_converter
specific_options = {
- builtin_converters: HeaderConverters,
+ builtin_converters_name: :HeaderConverters,
accept_nil: true,
}
options = @base_fields_converter_options.merge(specific_options)
@@ -2650,8 +2669,15 @@ end
# c.read.any? { |a| a.include?("zombies") }
# } #=> false
#
-def CSV(*args, &block)
- CSV.instance(*args, &block)
+# CSV options may also be given.
+#
+# io = StringIO.new
+# CSV(io, col_sep: ";") { |csv| csv << ["a", "b", "c"] }
+#
+# This API is not Ractor-safe.
+#
+def CSV(*args, **options, &block)
+ CSV.instance(*args, **options, &block)
end
require_relative "csv/version"
diff --git a/lib/csv/csv.gemspec b/lib/csv/csv.gemspec
index d0284728f78..11c5b0f2a6e 100644
--- a/lib/csv/csv.gemspec
+++ b/lib/csv/csv.gemspec
@@ -60,5 +60,5 @@ Gem::Specification.new do |spec|
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake"
spec.add_development_dependency "benchmark_driver"
- spec.add_development_dependency "simplecov"
+ spec.add_development_dependency "test-unit", ">= 3.4.8"
end
diff --git a/lib/csv/fields_converter.rb b/lib/csv/fields_converter.rb
index 178ffb37bc8..b206118d99b 100644
--- a/lib/csv/fields_converter.rb
+++ b/lib/csv/fields_converter.rb
@@ -16,7 +16,7 @@ class CSV
@empty_value = options[:empty_value]
@empty_value_is_empty_string = (@empty_value == "")
@accept_nil = options[:accept_nil]
- @builtin_converters = options[:builtin_converters]
+ @builtin_converters_name = options[:builtin_converters_name]
@need_static_convert = need_static_convert?
end
@@ -24,7 +24,7 @@ class CSV
if name.nil? # custom converter
@converters << converter
else # named converter
- combo = @builtin_converters[name]
+ combo = builtin_converters[name]
case combo
when Array # combo converter
combo.each do |sub_name|
@@ -80,5 +80,9 @@ class CSV
@need_static_convert or
(not @converters.empty?)
end
+
+ def builtin_converters
+ @builtin_converters ||= ::CSV.const_get(@builtin_converters_name)
+ end
end
end
diff --git a/lib/csv/input_record_separator.rb b/lib/csv/input_record_separator.rb
new file mode 100644
index 00000000000..bbf13479f78
--- /dev/null
+++ b/lib/csv/input_record_separator.rb
@@ -0,0 +1,31 @@
+require "English"
+require "stringio"
+
+class CSV
+ module InputRecordSeparator
+ class << self
+ is_input_record_separator_deprecated = false
+ verbose, $VERBOSE = $VERBOSE, true
+ stderr, $stderr = $stderr, StringIO.new
+ input_record_separator = $INPUT_RECORD_SEPARATOR
+ begin
+ $INPUT_RECORD_SEPARATOR = "\r\n"
+ is_input_record_separator_deprecated = (not $stderr.string.empty?)
+ ensure
+ $INPUT_RECORD_SEPARATOR = input_record_separator
+ $stderr = stderr
+ $VERBOSE = verbose
+ end
+
+ if is_input_record_separator_deprecated
+ def value
+ "\n"
+ end
+ else
+ def value
+ $INPUT_RECORD_SEPARATOR
+ end
+ end
+ end
+ end
+end
diff --git a/lib/csv/parser.rb b/lib/csv/parser.rb
index 2fb3b0a46ed..3334acfbdd7 100644
--- a/lib/csv/parser.rb
+++ b/lib/csv/parser.rb
@@ -3,6 +3,7 @@
require "strscan"
require_relative "delete_suffix"
+require_relative "input_record_separator"
require_relative "match_p"
require_relative "row"
require_relative "table"
@@ -479,9 +480,9 @@ class CSV
begin
StringScanner.new("x").scan("x")
rescue TypeError
- @@string_scanner_scan_accept_string = false
+ STRING_SCANNER_SCAN_ACCEPT_STRING = false
else
- @@string_scanner_scan_accept_string = true
+ STRING_SCANNER_SCAN_ACCEPT_STRING = true
end
def prepare_separators
@@ -505,7 +506,7 @@ class CSV
@first_column_separators = Regexp.new(@escaped_first_column_separator +
"+".encode(@encoding))
else
- if @@string_scanner_scan_accept_string
+ if STRING_SCANNER_SCAN_ACCEPT_STRING
@column_end = @column_separator
else
@column_end = Regexp.new(@escaped_column_separator)
@@ -526,7 +527,7 @@ class CSV
@cr = "\r".encode(@encoding)
@lf = "\n".encode(@encoding)
- @cr_or_lf = Regexp.new("[\r\n]".encode(@encoding))
+ @line_end = Regexp.new("\r\n|\n|\r".encode(@encoding))
@not_line_end = Regexp.new("[^\r\n]+".encode(@encoding))
end
@@ -605,7 +606,7 @@ class CSV
# do nothing: ensure will set default
end
end
- separator = $INPUT_RECORD_SEPARATOR if separator == :auto
+ separator = InputRecordSeparator.value if separator == :auto
end
separator.to_s.encode(@encoding)
end
@@ -724,6 +725,8 @@ class CSV
end
end
+ SCANNER_TEST_CHUNK_SIZE =
+ Integer((ENV["CSV_PARSER_SCANNER_TEST_CHUNK_SIZE"] || "1"), 10)
def build_scanner
inputs = @samples.collect do |sample|
UnoptimizedStringIO.new(sample)
@@ -733,10 +736,9 @@ class CSV
else
inputs << @input
end
- chunk_size = ENV["CSV_PARSER_SCANNER_TEST_CHUNK_SIZE"] || "1"
InputsScanner.new(inputs,
@encoding,
- chunk_size: Integer(chunk_size, 10))
+ chunk_size: SCANNER_TEST_CHUNK_SIZE)
end
else
def build_scanner
@@ -914,7 +916,7 @@ class CSV
message = "Any value after quoted field isn't allowed"
raise MalformedCSVError.new(message, @lineno)
elsif @unquoted_column_value and
- (new_line = @scanner.scan(@cr_or_lf))
+ (new_line = @scanner.scan(@line_end))
ignore_broken_line
message = "Unquoted fields do not allow new line " +
"<#{new_line.inspect}>"
@@ -923,7 +925,7 @@ class CSV
ignore_broken_line
message = "Illegal quoting"
raise MalformedCSVError.new(message, @lineno)
- elsif (new_line = @scanner.scan(@cr_or_lf))
+ elsif (new_line = @scanner.scan(@line_end))
ignore_broken_line
message = "New line must be <#{@row_separator.inspect}> " +
"not <#{new_line.inspect}>"
@@ -1089,7 +1091,7 @@ class CSV
def ignore_broken_line
@scanner.scan_all(@not_line_end)
- @scanner.scan_all(@cr_or_lf)
+ @scanner.scan_all(@line_end)
@lineno += 1
end
diff --git a/lib/csv/version.rb b/lib/csv/version.rb
index b509299d96e..72d61caf9fc 100644
--- a/lib/csv/version.rb
+++ b/lib/csv/version.rb
@@ -2,5 +2,5 @@
class CSV
# The version of the installed library.
- VERSION = "3.2.0"
+ VERSION = "3.2.1"
end
diff --git a/lib/csv/writer.rb b/lib/csv/writer.rb
index d49115fccf8..4a9a35c5afc 100644
--- a/lib/csv/writer.rb
+++ b/lib/csv/writer.rb
@@ -1,5 +1,6 @@
# frozen_string_literal: true
+require_relative "input_record_separator"
require_relative "match_p"
require_relative "row"
@@ -133,7 +134,7 @@ class CSV
@column_separator = @options[:column_separator].to_s.encode(@encoding)
row_separator = @options[:row_separator]
if row_separator == :auto
- @row_separator = $INPUT_RECORD_SEPARATOR.encode(@encoding)
+ @row_separator = InputRecordSeparator.value.encode(@encoding)
else
@row_separator = row_separator.to_s.encode(@encoding)
end
diff --git a/lib/debug.gemspec b/lib/debug.gemspec
deleted file mode 100644
index 71f93f7409c..00000000000
--- a/lib/debug.gemspec
+++ /dev/null
@@ -1,22 +0,0 @@
-Gem::Specification.new do |spec|
- spec.name = "debug"
- spec.version = "0.1.0"
- spec.authors = ["Yukihiro Matsumoto"]
- spec.email = ["matz@ruby-lang.org"]
-
- spec.summary = %q{Debugging functionality for Ruby}
- spec.description = %q{Debugging functionality for Ruby}
- spec.homepage = "https://github.com/ruby/debug"
- spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
- spec.licenses = ["Ruby", "BSD-2-Clause"]
-
- spec.metadata["homepage_uri"] = spec.homepage
- spec.metadata["source_code_uri"] = spec.homepage
-
- spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
- `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
- end
- spec.bindir = "exe"
- spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
- spec.require_paths = ["lib"]
-end
diff --git a/lib/debug.rb b/lib/debug.rb
deleted file mode 100644
index bf53eb80a47..00000000000
--- a/lib/debug.rb
+++ /dev/null
@@ -1,1106 +0,0 @@
-# frozen_string_literal: true
-# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
-# Copyright (C) 2000 Information-technology Promotion Agency, Japan
-# Copyright (C) 2000-2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>
-
-require 'continuation'
-
-require 'tracer'
-require 'pp'
-
-class Tracer # :nodoc:
- def Tracer.trace_func(*vars)
- Single.trace_func(*vars)
- end
-end
-
-SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__ # :nodoc:
-
-##
-# This library provides debugging functionality to Ruby.
-#
-# To add a debugger to your code, start by requiring +debug+ in your
-# program:
-#
-# def say(word)
-# require 'debug'
-# puts word
-# end
-#
-# This will cause Ruby to interrupt execution and show a prompt when the +say+
-# method is run.
-#
-# Once you're inside the prompt, you can start debugging your program.
-#
-# (rdb:1) p word
-# "hello"
-#
-# == Getting help
-#
-# You can get help at any time by pressing +h+.
-#
-# (rdb:1) h
-# Debugger help v.-0.002b
-# Commands
-# b[reak] [file:|class:]<line|method>
-# b[reak] [class.]<line|method>
-# set breakpoint to some position
-# wat[ch] <expression> set watchpoint to some expression
-# cat[ch] (<exception>|off) set catchpoint to an exception
-# b[reak] list breakpoints
-# cat[ch] show catchpoint
-# del[ete][ nnn] delete some or all breakpoints
-# disp[lay] <expression> add expression into display expression list
-# undisp[lay][ nnn] delete one particular or all display expressions
-# c[ont] run until program ends or hit breakpoint
-# s[tep][ nnn] step (into methods) one line or till line nnn
-# n[ext][ nnn] go over one line or till line nnn
-# w[here] display frames
-# f[rame] alias for where
-# l[ist][ (-|nn-mm)] list program, - lists backwards
-# nn-mm lists given lines
-# up[ nn] move to higher frame
-# down[ nn] move to lower frame
-# fin[ish] return to outer frame
-# tr[ace] (on|off) set trace mode of current thread
-# tr[ace] (on|off) all set trace mode of all threads
-# q[uit] exit from debugger
-# v[ar] g[lobal] show global variables
-# v[ar] l[ocal] show local variables
-# v[ar] i[nstance] <object> show instance variables of object
-# v[ar] c[onst] <object> show constants of object
-# m[ethod] i[nstance] <obj> show methods of object
-# m[ethod] <class|module> show instance methods of class or module
-# th[read] l[ist] list all threads
-# th[read] c[ur[rent]] show current thread
-# th[read] [sw[itch]] <nnn> switch thread context to nnn
-# th[read] stop <nnn> stop thread nnn
-# th[read] resume <nnn> resume thread nnn
-# p expression evaluate expression and print its value
-# h[elp] print this help
-# <everything else> evaluate
-#
-# == Usage
-#
-# The following is a list of common functionalities that the debugger
-# provides.
-#
-# === Navigating through your code
-#
-# In general, a debugger is used to find bugs in your program, which
-# often means pausing execution and inspecting variables at some point
-# in time.
-#
-# Let's look at an example:
-#
-# def my_method(foo)
-# require 'debug'
-# foo = get_foo if foo.nil?
-# raise if foo.nil?
-# end
-#
-# When you run this program, the debugger will kick in just before the
-# +foo+ assignment.
-#
-# (rdb:1) p foo
-# nil
-#
-# In this example, it'd be interesting to move to the next line and
-# inspect the value of +foo+ again. You can do that by pressing +n+:
-#
-# (rdb:1) n # goes to next line
-# (rdb:1) p foo
-# nil
-#
-# You now know that the original value of +foo+ was nil, and that it
-# still was nil after calling +get_foo+.
-#
-# Other useful commands for navigating through your code are:
-#
-# +c+::
-# Runs the program until it either exists or encounters another breakpoint.
-# You usually press +c+ when you are finished debugging your program and
-# want to resume its execution.
-# +s+::
-# Steps into method definition. In the previous example, +s+ would take you
-# inside the method definition of +get_foo+.
-# +r+::
-# Restart the program.
-# +q+::
-# Quit the program.
-#
-# === Inspecting variables
-#
-# You can use the debugger to easily inspect both local and global variables.
-# We've seen how to inspect local variables before:
-#
-# (rdb:1) p my_arg
-# 42
-#
-# You can also pretty print the result of variables or expressions:
-#
-# (rdb:1) pp %w{a very long long array containing many words}
-# ["a",
-# "very",
-# "long",
-# ...
-# ]
-#
-# You can list all local variables with +v l+:
-#
-# (rdb:1) v l
-# foo => "hello"
-#
-# Similarly, you can show all global variables with +v g+:
-#
-# (rdb:1) v g
-# all global variables
-#
-# Finally, you can omit +p+ if you simply want to evaluate a variable or
-# expression
-#
-# (rdb:1) 5**2
-# 25
-#
-# === Going beyond basics
-#
-# Ruby Debug provides more advanced functionalities like switching
-# between threads, setting breakpoints and watch expressions, and more.
-# The full list of commands is available at any time by pressing +h+.
-#
-# == Staying out of trouble
-#
-# Make sure you remove every instance of +require 'debug'+ before
-# shipping your code. Failing to do so may result in your program
-# hanging unpredictably.
-#
-# Debug is not available in safe mode.
-
-class DEBUGGER__
- MUTEX = Thread::Mutex.new # :nodoc:
-
- class Context # :nodoc:
- DEBUG_LAST_CMD = []
-
- begin
- require 'readline'
- def readline(prompt, hist)
- Readline::readline(prompt, hist)
- end
- rescue LoadError
- def readline(prompt, hist)
- STDOUT.print prompt
- STDOUT.flush
- line = STDIN.gets
- exit unless line
- line.chomp!
- line
- end
- USE_READLINE = false
- end
-
- def initialize
- if Thread.current == Thread.main
- @stop_next = 1
- else
- @stop_next = 0
- end
- @last_file = nil
- @file = nil
- @line = nil
- @no_step = nil
- @frames = []
- @finish_pos = 0
- @trace = false
- @catch = "StandardError"
- @suspend_next = false
- end
-
- def stop_next(n=1)
- @stop_next = n
- end
-
- def set_suspend
- @suspend_next = true
- end
-
- def clear_suspend
- @suspend_next = false
- end
-
- def suspend_all
- DEBUGGER__.suspend
- end
-
- def resume_all
- DEBUGGER__.resume
- end
-
- def check_suspend
- while MUTEX.synchronize {
- if @suspend_next
- DEBUGGER__.waiting.push Thread.current
- @suspend_next = false
- true
- end
- }
- end
- end
-
- def trace?
- @trace
- end
-
- def set_trace(arg)
- @trace = arg
- end
-
- def stdout
- DEBUGGER__.stdout
- end
-
- def break_points
- DEBUGGER__.break_points
- end
-
- def display
- DEBUGGER__.display
- end
-
- def context(th)
- DEBUGGER__.context(th)
- end
-
- def set_trace_all(arg)
- DEBUGGER__.set_trace(arg)
- end
-
- def set_last_thread(th)
- DEBUGGER__.set_last_thread(th)
- end
-
- def debug_eval(str, binding)
- begin
- eval(str, binding)
- rescue StandardError, ScriptError => e
- at = eval("caller(1)", binding)
- stdout.printf "%s:%s\n", at.shift, e.to_s.sub(/\(eval\):1:(in `.*?':)?/, '')
- for i in at
- stdout.printf "\tfrom %s\n", i
- end
- throw :debug_error
- end
- end
-
- def debug_silent_eval(str, binding)
- begin
- eval(str, binding)
- rescue StandardError, ScriptError
- nil
- end
- end
-
- def var_list(ary, binding)
- ary.sort!
- for v in ary
- stdout.printf " %s => %s\n", v, eval(v.to_s, binding).inspect
- end
- end
-
- def debug_variable_info(input, binding)
- case input
- when /^\s*g(?:lobal)?\s*$/
- var_list(global_variables, binding)
-
- when /^\s*l(?:ocal)?\s*$/
- var_list(eval("local_variables", binding), binding)
-
- when /^\s*i(?:nstance)?\s+/
- obj = debug_eval($', binding)
- var_list(obj.instance_variables, obj.instance_eval{binding()})
-
- when /^\s*c(?:onst(?:ant)?)?\s+/
- obj = debug_eval($', binding)
- unless obj.kind_of? Module
- stdout.print "Should be Class/Module: ", $', "\n"
- else
- var_list(obj.constants, obj.module_eval{binding()})
- end
- end
- end
-
- def debug_method_info(input, binding)
- case input
- when /^i(:?nstance)?\s+/
- obj = debug_eval($', binding)
-
- len = 0
- for v in obj.methods.sort
- len += v.size + 1
- if len > 70
- len = v.size + 1
- stdout.print "\n"
- end
- stdout.print v, " "
- end
- stdout.print "\n"
-
- else
- obj = debug_eval(input, binding)
- unless obj.kind_of? Module
- stdout.print "Should be Class/Module: ", input, "\n"
- else
- len = 0
- for v in obj.instance_methods(false).sort
- len += v.size + 1
- if len > 70
- len = v.size + 1
- stdout.print "\n"
- end
- stdout.print v, " "
- end
- stdout.print "\n"
- end
- end
- end
-
- def thnum
- num = DEBUGGER__.instance_eval{@thread_list[Thread.current]}
- unless num
- DEBUGGER__.make_thread_list
- num = DEBUGGER__.instance_eval{@thread_list[Thread.current]}
- end
- num
- end
-
- def debug_command(file, line, id, binding)
- MUTEX.lock
- unless defined?($debugger_restart) and $debugger_restart
- callcc{|c| $debugger_restart = c}
- end
- set_last_thread(Thread.current)
- frame_pos = 0
- binding_file = file
- binding_line = line
- previous_line = nil
- if ENV['EMACS']
- stdout.printf "\032\032%s:%d:\n", binding_file, binding_line
- else
- stdout.printf "%s:%d:%s", binding_file, binding_line,
- line_at(binding_file, binding_line)
- end
- @frames[0] = [binding, file, line, id]
- display_expressions(binding)
- prompt = true
- while prompt and input = readline("(rdb:%d) "%thnum(), true)
- catch(:debug_error) do
- if input == ""
- next unless DEBUG_LAST_CMD[0]
- input = DEBUG_LAST_CMD[0]
- stdout.print input, "\n"
- else
- DEBUG_LAST_CMD[0] = input
- end
-
- case input
- when /^\s*tr(?:ace)?(?:\s+(on|off))?(?:\s+(all))?$/
- if defined?( $2 )
- if $1 == 'on'
- set_trace_all true
- else
- set_trace_all false
- end
- elsif defined?( $1 )
- if $1 == 'on'
- set_trace true
- else
- set_trace false
- end
- end
- if trace?
- stdout.print "Trace on.\n"
- else
- stdout.print "Trace off.\n"
- end
-
- when /^\s*b(?:reak)?\s+(?:(.+):)?([^.:]+)$/
- pos = $2
- if $1
- klass = debug_silent_eval($1, binding)
- file = File.expand_path($1)
- end
- if pos =~ /^\d+$/
- pname = pos
- pos = pos.to_i
- else
- pname = pos = pos.intern.id2name
- end
- break_points.push [true, 0, klass || file, pos]
- stdout.printf "Set breakpoint %d at %s:%s\n", break_points.size, klass || file, pname
-
- when /^\s*b(?:reak)?\s+(.+)[#.]([^.:]+)$/
- pos = $2.intern.id2name
- klass = debug_eval($1, binding)
- break_points.push [true, 0, klass, pos]
- stdout.printf "Set breakpoint %d at %s.%s\n", break_points.size, klass, pos
-
- when /^\s*wat(?:ch)?\s+(.+)$/
- exp = $1
- break_points.push [true, 1, exp]
- stdout.printf "Set watchpoint %d:%s\n", break_points.size, exp
-
- when /^\s*b(?:reak)?$/
- if break_points.find{|b| b[1] == 0}
- n = 1
- stdout.print "Breakpoints:\n"
- break_points.each do |b|
- if b[0] and b[1] == 0
- stdout.printf " %d %s:%s\n", n, b[2], b[3]
- end
- n += 1
- end
- end
- if break_points.find{|b| b[1] == 1}
- n = 1
- stdout.print "\n"
- stdout.print "Watchpoints:\n"
- for b in break_points
- if b[0] and b[1] == 1
- stdout.printf " %d %s\n", n, b[2]
- end
- n += 1
- end
- end
- if break_points.size == 0
- stdout.print "No breakpoints\n"
- else
- stdout.print "\n"
- end
-
- when /^\s*del(?:ete)?(?:\s+(\d+))?$/
- pos = $1
- unless pos
- input = readline("Clear all breakpoints? (y/n) ", false)
- if input == "y"
- for b in break_points
- b[0] = false
- end
- end
- else
- pos = pos.to_i
- if break_points[pos-1]
- break_points[pos-1][0] = false
- else
- stdout.printf "Breakpoint %d is not defined\n", pos
- end
- end
-
- when /^\s*disp(?:lay)?\s+(.+)$/
- exp = $1
- display.push [true, exp]
- stdout.printf "%d: ", display.size
- display_expression(exp, binding)
-
- when /^\s*disp(?:lay)?$/
- display_expressions(binding)
-
- when /^\s*undisp(?:lay)?(?:\s+(\d+))?$/
- pos = $1
- unless pos
- input = readline("Clear all expressions? (y/n) ", false)
- if input == "y"
- for d in display
- d[0] = false
- end
- end
- else
- pos = pos.to_i
- if display[pos-1]
- display[pos-1][0] = false
- else
- stdout.printf "Display expression %d is not defined\n", pos
- end
- end
-
- when /^\s*c(?:ont)?$/
- prompt = false
-
- when /^\s*s(?:tep)?(?:\s+(\d+))?$/
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- @stop_next = lev
- prompt = false
-
- when /^\s*n(?:ext)?(?:\s+(\d+))?$/
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- @stop_next = lev
- @no_step = @frames.size - frame_pos
- prompt = false
-
- when /^\s*w(?:here)?$/, /^\s*f(?:rame)?$/
- display_frames(frame_pos)
-
- when /^\s*l(?:ist)?(?:\s+(.+))?$/
- if not $1
- b = previous_line ? previous_line + 10 : binding_line - 5
- e = b + 9
- elsif $1 == '-'
- b = previous_line ? previous_line - 10 : binding_line - 5
- e = b + 9
- else
- b, e = $1.split(/[-,]/)
- if e
- b = b.to_i
- e = e.to_i
- else
- b = b.to_i - 5
- e = b + 9
- end
- end
- previous_line = b
- display_list(b, e, binding_file, binding_line)
-
- when /^\s*up(?:\s+(\d+))?$/
- previous_line = nil
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- frame_pos += lev
- if frame_pos >= @frames.size
- frame_pos = @frames.size - 1
- stdout.print "At toplevel\n"
- end
- binding, binding_file, binding_line = @frames[frame_pos]
- stdout.print format_frame(frame_pos)
-
- when /^\s*down(?:\s+(\d+))?$/
- previous_line = nil
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- frame_pos -= lev
- if frame_pos < 0
- frame_pos = 0
- stdout.print "At stack bottom\n"
- end
- binding, binding_file, binding_line = @frames[frame_pos]
- stdout.print format_frame(frame_pos)
-
- when /^\s*fin(?:ish)?$/
- if frame_pos == @frames.size
- stdout.print "\"finish\" not meaningful in the outermost frame.\n"
- else
- @finish_pos = @frames.size - frame_pos
- frame_pos = 0
- prompt = false
- end
-
- when /^\s*cat(?:ch)?(?:\s+(.+))?$/
- if $1
- excn = $1
- if excn == 'off'
- @catch = nil
- stdout.print "Clear catchpoint.\n"
- else
- @catch = excn
- stdout.printf "Set catchpoint %s.\n", @catch
- end
- else
- if @catch
- stdout.printf "Catchpoint %s.\n", @catch
- else
- stdout.print "No catchpoint.\n"
- end
- end
-
- when /^\s*q(?:uit)?$/
- input = readline("Really quit? (y/n) ", false)
- if input == "y"
- exit! # exit -> exit!: No graceful way to stop threads...
- end
-
- when /^\s*v(?:ar)?\s+/
- debug_variable_info($', binding)
-
- when /^\s*m(?:ethod)?\s+/
- debug_method_info($', binding)
-
- when /^\s*th(?:read)?\s+/
- if DEBUGGER__.debug_thread_info($', binding) == :cont
- prompt = false
- end
-
- when /^\s*pp\s+/
- PP.pp(debug_eval($', binding), stdout)
-
- when /^\s*p\s+/
- stdout.printf "%s\n", debug_eval($', binding).inspect
-
- when /^\s*r(?:estart)?$/
- $debugger_restart.call
-
- when /^\s*h(?:elp)?$/
- debug_print_help()
-
- else
- v = debug_eval(input, binding)
- stdout.printf "%s\n", v.inspect
- end
- end
- end
- MUTEX.unlock
- resume_all
- end
-
- def debug_print_help
- stdout.print <<EOHELP
-Debugger help v.-0.002b
-Commands
- b[reak] [file:|class:]<line|method>
- b[reak] [class.]<line|method>
- set breakpoint to some position
- wat[ch] <expression> set watchpoint to some expression
- cat[ch] (<exception>|off) set catchpoint to an exception
- b[reak] list breakpoints
- cat[ch] show catchpoint
- del[ete][ nnn] delete some or all breakpoints
- disp[lay] <expression> add expression into display expression list
- undisp[lay][ nnn] delete one particular or all display expressions
- c[ont] run until program ends or hit breakpoint
- s[tep][ nnn] step (into methods) one line or till line nnn
- n[ext][ nnn] go over one line or till line nnn
- w[here] display frames
- f[rame] alias for where
- l[ist][ (-|nn-mm)] list program, - lists backwards
- nn-mm lists given lines
- up[ nn] move to higher frame
- down[ nn] move to lower frame
- fin[ish] return to outer frame
- tr[ace] (on|off) set trace mode of current thread
- tr[ace] (on|off) all set trace mode of all threads
- q[uit] exit from debugger
- v[ar] g[lobal] show global variables
- v[ar] l[ocal] show local variables
- v[ar] i[nstance] <object> show instance variables of object
- v[ar] c[onst] <object> show constants of object
- m[ethod] i[nstance] <obj> show methods of object
- m[ethod] <class|module> show instance methods of class or module
- th[read] l[ist] list all threads
- th[read] c[ur[rent]] show current thread
- th[read] [sw[itch]] <nnn> switch thread context to nnn
- th[read] stop <nnn> stop thread nnn
- th[read] resume <nnn> resume thread nnn
- pp expression evaluate expression and pretty_print its value
- p expression evaluate expression and print its value
- r[estart] restart program
- h[elp] print this help
- <everything else> evaluate
-EOHELP
- end
-
- def display_expressions(binding)
- n = 1
- for d in display
- if d[0]
- stdout.printf "%d: ", n
- display_expression(d[1], binding)
- end
- n += 1
- end
- end
-
- def display_expression(exp, binding)
- stdout.printf "%s = %s\n", exp, debug_silent_eval(exp, binding).to_s
- end
-
- def frame_set_pos(file, line)
- if @frames[0]
- @frames[0][1] = file
- @frames[0][2] = line
- end
- end
-
- def display_frames(pos)
- 0.upto(@frames.size - 1) do |n|
- if n == pos
- stdout.print "--> "
- else
- stdout.print " "
- end
- stdout.print format_frame(n)
- end
- end
-
- def format_frame(pos)
- _, file, line, id = @frames[pos]
- sprintf "#%d %s:%s%s\n", pos + 1, file, line,
- (id ? ":in `#{id.id2name}'" : "")
- end
-
- def script_lines(file, line)
- unless (lines = SCRIPT_LINES__[file]) and lines != true
- Tracer::Single.get_line(file, line) if File.exist?(file)
- lines = SCRIPT_LINES__[file]
- lines = nil if lines == true
- end
- lines
- end
-
- def display_list(b, e, file, line)
- if lines = script_lines(file, line)
- stdout.printf "[%d, %d] in %s\n", b, e, file
- b.upto(e) do |n|
- if n > 0 && lines[n-1]
- if n == line
- stdout.printf "=> %d %s\n", n, lines[n-1].chomp
- else
- stdout.printf " %d %s\n", n, lines[n-1].chomp
- end
- end
- end
- else
- stdout.printf "No sourcefile available for %s\n", file
- end
- end
-
- def line_at(file, line)
- lines = script_lines(file, line)
- if lines and line = lines[line-1]
- return line
- end
- return "\n"
- end
-
- def debug_funcname(id)
- if id.nil?
- "toplevel"
- else
- id.id2name
- end
- end
-
- def check_break_points(file, klass, pos, binding, id)
- return false if break_points.empty?
- n = 1
- for b in break_points
- if b[0] # valid
- if b[1] == 0 # breakpoint
- if (b[2] == file and b[3] == pos) or
- (klass and b[2] == klass and b[3] == pos)
- stdout.printf "Breakpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
- return true
- end
- elsif b[1] == 1 # watchpoint
- if debug_silent_eval(b[2], binding)
- stdout.printf "Watchpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
- return true
- end
- end
- end
- n += 1
- end
- return false
- end
-
- def excn_handle(file, line, id, binding)
- if $!.class <= SystemExit
- set_trace_func nil
- exit
- end
-
- if @catch and ($!.class.ancestors.find { |e| e.to_s == @catch })
- stdout.printf "%s:%d: `%s' (%s)\n", file, line, $!, $!.class
- fs = @frames.size
- tb = caller(0)[-fs..-1]
- if tb
- for i in tb
- stdout.printf "\tfrom %s\n", i
- end
- end
- suspend_all
- debug_command(file, line, id, binding)
- end
- end
-
- def trace_func(event, file, line, id, binding, klass)
- Tracer.trace_func(event, file, line, id, binding, klass) if trace?
- context(Thread.current).check_suspend
- @file = file
- @line = line
- case event
- when 'line'
- frame_set_pos(file, line)
- if !@no_step or @frames.size == @no_step
- @stop_next -= 1
- @stop_next = -1 if @stop_next < 0
- elsif @frames.size < @no_step
- @stop_next = 0 # break here before leaving...
- else
- # nothing to do. skipped.
- end
- if @stop_next == 0 or check_break_points(file, nil, line, binding, id)
- @no_step = nil
- suspend_all
- debug_command(file, line, id, binding)
- end
-
- when 'call'
- @frames.unshift [binding, file, line, id]
- if check_break_points(file, klass, id.id2name, binding, id)
- suspend_all
- debug_command(file, line, id, binding)
- end
-
- when 'c-call'
- frame_set_pos(file, line)
-
- when 'class'
- @frames.unshift [binding, file, line, id]
-
- when 'return', 'end'
- if @frames.size == @finish_pos
- @stop_next = 1
- @finish_pos = 0
- end
- @frames.shift
-
- when 'raise'
- excn_handle(file, line, id, binding)
-
- end
- @last_file = file
- end
- end
-
- trap("INT") { DEBUGGER__.interrupt }
- @last_thread = Thread::main
- @max_thread = 1
- @thread_list = {Thread::main => 1}
- @break_points = []
- @display = []
- @waiting = []
- @stdout = STDOUT
-
- class << DEBUGGER__
- # Returns the IO used as stdout. Defaults to STDOUT
- def stdout
- @stdout
- end
-
- # Sets the IO used as stdout. Defaults to STDOUT
- def stdout=(s)
- @stdout = s
- end
-
- # Returns the display expression list
- #
- # See DEBUGGER__ for more usage
- def display
- @display
- end
-
- # Returns the list of break points where execution will be stopped.
- #
- # See DEBUGGER__ for more usage
- def break_points
- @break_points
- end
-
- # Returns the list of waiting threads.
- #
- # When stepping through the traces of a function, thread gets suspended, to
- # be resumed later.
- def waiting
- @waiting
- end
-
- def set_trace( arg )
- MUTEX.synchronize do
- make_thread_list
- for th, in @thread_list
- context(th).set_trace arg
- end
- end
- arg
- end
-
- def set_last_thread(th)
- @last_thread = th
- end
-
- def suspend
- MUTEX.synchronize do
- make_thread_list
- for th, in @thread_list
- next if th == Thread.current
- context(th).set_suspend
- end
- end
- # Schedule other threads to suspend as soon as possible.
- Thread.pass
- end
-
- def resume
- MUTEX.synchronize do
- make_thread_list
- @thread_list.each do |th,|
- next if th == Thread.current
- context(th).clear_suspend
- end
- waiting.each do |th|
- th.run
- end
- waiting.clear
- end
- # Schedule other threads to restart as soon as possible.
- Thread.pass
- end
-
- def context(thread=Thread.current)
- c = thread[:__debugger_data__]
- unless c
- thread[:__debugger_data__] = c = Context.new
- end
- c
- end
-
- def interrupt
- context(@last_thread).stop_next
- end
-
- def get_thread(num)
- th = @thread_list.key(num)
- unless th
- @stdout.print "No thread ##{num}\n"
- throw :debug_error
- end
- th
- end
-
- def thread_list(num)
- th = get_thread(num)
- if th == Thread.current
- @stdout.print "+"
- else
- @stdout.print " "
- end
- @stdout.printf "%d ", num
- @stdout.print th.inspect, "\t"
- file = context(th).instance_eval{@file}
- if file
- @stdout.print file,":",context(th).instance_eval{@line}
- end
- @stdout.print "\n"
- end
-
- # Prints all threads in @thread_list to @stdout. Returns a sorted array of
- # values from the @thread_list hash.
- #
- # While in the debugger you can list all of
- # the threads with: <b>DEBUGGER__.thread_list_all</b>
- #
- # (rdb:1) DEBUGGER__.thread_list_all
- # +1 #<Thread:0x007fb2320c03f0 run> debug_me.rb.rb:3
- # 2 #<Thread:0x007fb23218a538 debug_me.rb.rb:3 sleep>
- # 3 #<Thread:0x007fb23218b0f0 debug_me.rb.rb:3 sleep>
- # [1, 2, 3]
- #
- # Your current thread is indicated by a <b>+</b>
- #
- # Additionally you can list all threads with <b>th l</b>
- #
- # (rdb:1) th l
- # +1 #<Thread:0x007f99328c0410 run> debug_me.rb:3
- # 2 #<Thread:0x007f9932938230 debug_me.rb:3 sleep> debug_me.rb:3
- # 3 #<Thread:0x007f9932938e10 debug_me.rb:3 sleep> debug_me.rb:3
- #
- # See DEBUGGER__ for more usage.
-
- def thread_list_all
- for th in @thread_list.values.sort
- thread_list(th)
- end
- end
-
- def make_thread_list
- hash = {}
- for th in Thread::list
- if @thread_list.key? th
- hash[th] = @thread_list[th]
- else
- @max_thread += 1
- hash[th] = @max_thread
- end
- end
- @thread_list = hash
- end
-
- def debug_thread_info(input, binding)
- case input
- when /^l(?:ist)?/
- make_thread_list
- thread_list_all
-
- when /^c(?:ur(?:rent)?)?$/
- make_thread_list
- thread_list(@thread_list[Thread.current])
-
- when /^(?:sw(?:itch)?\s+)?(\d+)/
- make_thread_list
- th = get_thread($1.to_i)
- if th == Thread.current
- @stdout.print "It's the current thread.\n"
- else
- thread_list(@thread_list[th])
- context(th).stop_next
- th.run
- return :cont
- end
-
- when /^stop\s+(\d+)/
- make_thread_list
- th = get_thread($1.to_i)
- if th == Thread.current
- @stdout.print "It's the current thread.\n"
- elsif th.stop?
- @stdout.print "Already stopped.\n"
- else
- thread_list(@thread_list[th])
- context(th).suspend
- end
-
- when /^resume\s+(\d+)/
- make_thread_list
- th = get_thread($1.to_i)
- if th == Thread.current
- @stdout.print "It's the current thread.\n"
- elsif !th.stop?
- @stdout.print "Already running."
- else
- thread_list(@thread_list[th])
- th.run
- end
- end
- end
- end
-
- stdout.printf "Debug.rb\n"
- stdout.printf "Emacs support available.\n\n"
- RubyVM::InstructionSequence.compile_option = {
- trace_instruction: true
- }
- set_trace_func proc { |event, file, line, id, binding, klass, *rest|
- DEBUGGER__.context.trace_func event, file, line, id, binding, klass
- }
-end
diff --git a/lib/delegate/delegate.gemspec b/lib/delegate/delegate.gemspec
index 05d9ced1754..1cfacfeb2fb 100644
--- a/lib/delegate/delegate.gemspec
+++ b/lib/delegate/delegate.gemspec
@@ -24,8 +24,6 @@ Gem::Specification.new do |spec|
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z 2>/dev/null`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
- spec.bindir = "exe"
- spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.required_ruby_version = '>= 2.7'
end
diff --git a/lib/did_you_mean.rb b/lib/did_you_mean.rb
index ab7e6b01a8e..6d3a6e8bdab 100644
--- a/lib/did_you_mean.rb
+++ b/lib/did_you_mean.rb
@@ -7,7 +7,8 @@ require_relative 'did_you_mean/spell_checkers/method_name_checker'
require_relative 'did_you_mean/spell_checkers/key_error_checker'
require_relative 'did_you_mean/spell_checkers/null_checker'
require_relative 'did_you_mean/spell_checkers/require_path_checker'
-require_relative 'did_you_mean/formatters/plain_formatter'
+require_relative 'did_you_mean/spell_checkers/pattern_key_name_checker'
+require_relative 'did_you_mean/formatter'
require_relative 'did_you_mean/tree_spell_checker'
# The +DidYouMean+ gem adds functionality to suggest possible method/class
@@ -97,16 +98,17 @@ module DidYouMean
correct_error KeyError, KeyErrorChecker
correct_error NoMethodError, MethodNameChecker
correct_error LoadError, RequirePathChecker if RUBY_VERSION >= '2.8.0'
+ correct_error NoMatchingPatternKeyError, PatternKeyNameChecker if defined?(::NoMatchingPatternKeyError)
# Returns the currently set formatter. By default, it is set to +DidYouMean::Formatter+.
def self.formatter
- @@formatter
+ @formatter
end
# Updates the primary formatter used to format the suggestions.
def self.formatter=(formatter)
- @@formatter = formatter
+ @formatter = formatter
end
- self.formatter = PlainFormatter.new
+ @formatter = Formatter.new
end
diff --git a/lib/did_you_mean/formatter.rb b/lib/did_you_mean/formatter.rb
new file mode 100644
index 00000000000..01eb59100ac
--- /dev/null
+++ b/lib/did_you_mean/formatter.rb
@@ -0,0 +1,35 @@
+# frozen-string-literal: true
+
+module DidYouMean
+ # The +DidYouMean::Formatter+ is the basic, default formatter for the
+ # gem. The formatter responds to the +message_for+ method and it returns a
+ # human readable string.
+ class Formatter
+
+ # Returns a human readable string that contains +corrections+. This
+ # formatter is designed to be less verbose to not take too much screen
+ # space while being helpful enough to the user.
+ #
+ # @example
+ #
+ # formatter = DidYouMean::Formatter.new
+ #
+ # # displays suggestions in two lines with the leading empty line
+ # puts formatter.message_for(["methods", "method"])
+ #
+ # Did you mean? methods
+ # method
+ # # => nil
+ #
+ # # displays an empty line
+ # puts formatter.message_for([])
+ #
+ # # => nil
+ #
+ def message_for(corrections)
+ corrections.empty? ? "" : "\nDid you mean? #{corrections.join("\n ")}"
+ end
+ end
+
+ PlainFormatter = Formatter
+end
diff --git a/lib/did_you_mean/formatters/plain_formatter.rb b/lib/did_you_mean/formatters/plain_formatter.rb
index e2d995f5871..d669588e0f3 100644
--- a/lib/did_you_mean/formatters/plain_formatter.rb
+++ b/lib/did_you_mean/formatters/plain_formatter.rb
@@ -1,33 +1,4 @@
-# frozen-string-literal: true
+require_relative '../formatter'
-module DidYouMean
- # The +DidYouMean::PlainFormatter+ is the basic, default formatter for the
- # gem. The formatter responds to the +message_for+ method and it returns a
- # human readable string.
- class PlainFormatter
-
- # Returns a human readable string that contains +corrections+. This
- # formatter is designed to be less verbose to not take too much screen
- # space while being helpful enough to the user.
- #
- # @example
- #
- # formatter = DidYouMean::PlainFormatter.new
- #
- # # displays suggestions in two lines with the leading empty line
- # puts formatter.message_for(["methods", "method"])
- #
- # Did you mean? methods
- # method
- # # => nil
- #
- # # displays an empty line
- # puts formatter.message_for([])
- #
- # # => nil
- #
- def message_for(corrections)
- corrections.empty? ? "" : "\nDid you mean? #{corrections.join("\n ")}"
- end
- end
-end
+warn "`require 'did_you_mean/formatters/plain_formatter'` is deprecated. Please `require 'did_you_mean/formatter'` " \
+ "instead."
diff --git a/lib/did_you_mean/formatters/verbose_formatter.rb b/lib/did_you_mean/formatters/verbose_formatter.rb
index b8fe214d578..8ee98fa070e 100644
--- a/lib/did_you_mean/formatters/verbose_formatter.rb
+++ b/lib/did_you_mean/formatters/verbose_formatter.rb
@@ -1,49 +1,9 @@
-# frozen-string-literal: true
-
-module DidYouMean
- # The +DidYouMean::VerboseFormatter+ uses extra empty lines to make the
- # suggestion stand out more in the error message.
- #
- # In order to activate the verbose formatter,
- #
- # @example
- #
- # OBject
- # # => NameError: uninitialized constant OBject
- # # Did you mean? Object
- #
- # require 'did_you_mean/verbose'
- #
- # OBject
- # # => NameError: uninitialized constant OBject
- # #
- # # Did you mean? Object
- # #
- #
- class VerboseFormatter
+warn "`require 'did_you_mean/formatters/verbose_formatter'` is deprecated and falls back to the default formatter. "
- # Returns a human readable string that contains +corrections+. This
- # formatter is designed to be less verbose to not take too much screen
- # space while being helpful enough to the user.
- #
- # @example
- #
- # formatter = DidYouMean::PlainFormatter.new
- #
- # puts formatter.message_for(["methods", "method"])
- #
- #
- # Did you mean? methods
- # method
- #
- # # => nil
- #
- def message_for(corrections)
- return "" if corrections.empty?
+require_relative '../formatter'
- output = "\n\n Did you mean? ".dup
- output << corrections.join("\n ")
- output << "\n "
- end
- end
+# frozen-string-literal: true
+module DidYouMean
+ # For compatibility:
+ VerboseFormatter = Formatter
end
diff --git a/lib/did_you_mean/spell_checker.rb b/lib/did_you_mean/spell_checker.rb
index e5106abba2c..37da2fc7a6e 100644
--- a/lib/did_you_mean/spell_checker.rb
+++ b/lib/did_you_mean/spell_checker.rb
@@ -10,25 +10,25 @@ module DidYouMean
end
def correct(input)
- input = normalize(input)
- threshold = input.length > 3 ? 0.834 : 0.77
+ normalized_input = normalize(input)
+ threshold = normalized_input.length > 3 ? 0.834 : 0.77
- words = @dictionary.select { |word| JaroWinkler.distance(normalize(word), input) >= threshold }
- words.reject! { |word| input == word.to_s }
- words.sort_by! { |word| JaroWinkler.distance(word.to_s, input) }
+ words = @dictionary.select { |word| JaroWinkler.distance(normalize(word), normalized_input) >= threshold }
+ words.reject! { |word| input.to_s == word.to_s }
+ words.sort_by! { |word| JaroWinkler.distance(word.to_s, normalized_input) }
words.reverse!
# Correct mistypes
- threshold = (input.length * 0.25).ceil
- corrections = words.select { |c| Levenshtein.distance(normalize(c), input) <= threshold }
+ threshold = (normalized_input.length * 0.25).ceil
+ corrections = words.select { |c| Levenshtein.distance(normalize(c), normalized_input) <= threshold }
# Correct misspells
if corrections.empty?
corrections = words.select do |word|
word = normalize(word)
- length = input.length < word.length ? input.length : word.length
+ length = normalized_input.length < word.length ? normalized_input.length : word.length
- Levenshtein.distance(word, input) < length
+ Levenshtein.distance(word, normalized_input) < length
end.first(1)
end
diff --git a/lib/did_you_mean/spell_checkers/pattern_key_name_checker.rb b/lib/did_you_mean/spell_checkers/pattern_key_name_checker.rb
new file mode 100644
index 00000000000..ed263c8f937
--- /dev/null
+++ b/lib/did_you_mean/spell_checkers/pattern_key_name_checker.rb
@@ -0,0 +1,20 @@
+require_relative "../spell_checker"
+
+module DidYouMean
+ class PatternKeyNameChecker
+ def initialize(no_matching_pattern_key_error)
+ @key = no_matching_pattern_key_error.key
+ @keys = no_matching_pattern_key_error.matchee.keys
+ end
+
+ def corrections
+ @corrections ||= exact_matches.empty? ? SpellChecker.new(dictionary: @keys).correct(@key).map(&:inspect) : exact_matches
+ end
+
+ private
+
+ def exact_matches
+ @exact_matches ||= @keys.select { |word| @key == word.to_s }.map(&:inspect)
+ end
+ end
+end
diff --git a/lib/did_you_mean/verbose.rb b/lib/did_you_mean/verbose.rb
index 4e86f167ea7..1ff19aef809 100644
--- a/lib/did_you_mean/verbose.rb
+++ b/lib/did_you_mean/verbose.rb
@@ -1,4 +1,2 @@
-require_relative '../did_you_mean'
-require_relative 'formatters/verbose_formatter'
-
-DidYouMean.formatter = DidYouMean::VerboseFormatter.new
+warn "The verbose formatter has been removed and now `require 'did_you_mean/verbose'` has no effect. Please " \
+ "remove this call."
diff --git a/lib/drb/version.rb b/lib/drb/version.rb
index ffba81d48e6..efaccf0319d 100644
--- a/lib/drb/version.rb
+++ b/lib/drb/version.rb
@@ -1,3 +1,3 @@
module DRb
- VERSION = "2.0.4"
+ VERSION = "2.1.0"
end
diff --git a/lib/error_highlight/core_ext.rb b/lib/error_highlight/core_ext.rb
index 1ae180aeac8..ebb6788b020 100644
--- a/lib/error_highlight/core_ext.rb
+++ b/lib/error_highlight/core_ext.rb
@@ -29,7 +29,7 @@ module ErrorHighlight
spot = ErrorHighlight.spot(node, **opts)
- rescue Errno::ENOENT, SyntaxError
+ rescue SystemCallError, SyntaxError
end
if spot
diff --git a/lib/error_highlight/formatter.rb b/lib/error_highlight/formatter.rb
index ce687fb2a28..20ca78d468a 100644
--- a/lib/error_highlight/formatter.rb
+++ b/lib/error_highlight/formatter.rb
@@ -1,6 +1,6 @@
module ErrorHighlight
class DefaultFormatter
- def message_for(spot)
+ def self.message_for(spot)
# currently only a one-line code snippet is supported
if spot[:first_lineno] == spot[:last_lineno]
indent = spot[:snippet][0...spot[:first_column]].gsub(/[^\t]/, " ")
@@ -14,12 +14,10 @@ module ErrorHighlight
end
def self.formatter
- @@formatter
+ Ractor.current[:__error_highlight_formatter__] || DefaultFormatter
end
def self.formatter=(formatter)
- @@formatter = formatter
+ Ractor.current[:__error_highlight_formatter__] = formatter
end
-
- self.formatter = DefaultFormatter.new
end
diff --git a/lib/fileutils.rb b/lib/fileutils.rb
index 69de4586658..c115005163b 100644
--- a/lib/fileutils.rb
+++ b/lib/fileutils.rb
@@ -102,7 +102,7 @@ end
# <tt>:verbose</tt> flags to methods in FileUtils.
#
module FileUtils
- VERSION = "1.5.0"
+ VERSION = "1.6.0"
def self.private_module_function(name) #:nodoc:
module_function name
@@ -211,21 +211,11 @@ module FileUtils
list.each do |item|
path = remove_trailing_slash(item)
- # optimize for the most common case
- begin
- fu_mkdir path, mode
- next
- rescue SystemCallError
- next if File.directory?(path)
- end
-
stack = []
- until path == stack.last # dirname("/")=="/", dirname("C:/")=="C:/"
+ until File.directory?(path)
stack.push path
path = File.dirname(path)
- break if File.directory?(path)
end
- stack.pop if path == stack.last # root directory should exist
stack.reverse_each do |dir|
begin
fu_mkdir dir, mode
diff --git a/lib/find.gemspec b/lib/find.gemspec
index fff0f706cdf..3f0aadcdae6 100644
--- a/lib/find.gemspec
+++ b/lib/find.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |spec|
spec.name = "find"
- spec.version = "0.1.0"
+ spec.version = "0.1.1"
spec.authors = ['Kazuki Tsujimoto']
spec.email = ['kazuki@callcc.net']
diff --git a/lib/ipaddr.gemspec b/lib/ipaddr.gemspec
index 5187f3be11f..36e23000020 100644
--- a/lib/ipaddr.gemspec
+++ b/lib/ipaddr.gemspec
@@ -5,7 +5,7 @@ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "ipaddr"
- spec.version = "1.2.2"
+ spec.version = "1.2.3"
spec.authors = ["Akinori MUSHA", "Hajimu UMEMOTO"]
spec.email = ["knu@idaemons.org", "ume@mahoroba.org"]
diff --git a/lib/ipaddr.rb b/lib/ipaddr.rb
index 7fff54b9d01..5df798f5d74 100644
--- a/lib/ipaddr.rb
+++ b/lib/ipaddr.rb
@@ -112,13 +112,12 @@ class IPAddr
def self.ntop(addr)
case addr.size
when 4
- s = addr.unpack('C4').join('.')
+ addr.unpack('C4').join('.')
when 16
- s = IN6FORMAT % addr.unpack('n8')
+ IN6FORMAT % addr.unpack('n8')
else
raise AddressFamilyError, "unsupported address family"
end
- return s
end
# Returns a new ipaddr built by bitwise AND.
@@ -168,34 +167,17 @@ class IPAddr
# net1 = IPAddr.new("192.168.2.0/24")
# net2 = IPAddr.new("192.168.2.100")
# net3 = IPAddr.new("192.168.3.0")
+ # net4 = IPAddr.new("192.168.2.0/16")
# p net1.include?(net2) #=> true
# p net1.include?(net3) #=> false
+ # p net1.include?(net4) #=> false
+ # p net4.include?(net1) #=> true
def include?(other)
other = coerce_other(other)
- if ipv4_mapped?
- if (@mask_addr >> 32) != 0xffffffffffffffffffffffff
- return false
- end
- mask_addr = (@mask_addr & IN4MASK)
- addr = (@addr & IN4MASK)
- family = Socket::AF_INET
- else
- mask_addr = @mask_addr
- addr = @addr
- family = @family
- end
- if other.ipv4_mapped?
- other_addr = (other.to_i & IN4MASK)
- other_family = Socket::AF_INET
- else
- other_addr = other.to_i
- other_family = other.family
- end
-
- if family != other_family
- return false
- end
- return ((addr & mask_addr) == (other_addr & mask_addr))
+ return false unless other.family == family
+ range = to_range
+ other = other.to_range
+ range.begin <= other.begin && range.end >= other.end
end
alias === include?
@@ -232,7 +214,13 @@ class IPAddr
# Returns a string containing the IP address representation in
# canonical form.
def to_string
- return _to_string(@addr)
+ str = _to_string(@addr)
+
+ if @family == Socket::AF_INET6
+ str << zone_id.to_s
+ end
+
+ return str
end
# Returns a network byte ordered string form of the IP address.
@@ -328,9 +316,11 @@ class IPAddr
# into an IPv4-mapped IPv6 address.
def ipv4_mapped
if !ipv4?
- raise InvalidAddressError, "not an IPv4 address"
+ raise InvalidAddressError, "not an IPv4 address: #{@addr}"
end
- return self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6)
+ clone = self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6)
+ clone.instance_variable_set(:@mask_addr, @mask_addr | 0xffffffffffffffffffffffff00000000)
+ clone
end
# Returns a new ipaddr built by converting the native IPv4 address
@@ -338,7 +328,7 @@ class IPAddr
def ipv4_compat
warn "IPAddr\##{__callee__} is obsolete", uplevel: 1 if $VERBOSE
if !ipv4?
- raise InvalidAddressError, "not an IPv4 address"
+ raise InvalidAddressError, "not an IPv4 address: #{@addr}"
end
return self.clone.set(@addr, Socket::AF_INET6)
end
@@ -369,7 +359,7 @@ class IPAddr
# Returns a string for DNS reverse lookup compatible with RFC3172.
def ip6_arpa
if !ipv6?
- raise InvalidAddressError, "not an IPv6 address"
+ raise InvalidAddressError, "not an IPv6 address: #{@addr}"
end
return _reverse + ".ip6.arpa"
end
@@ -377,7 +367,7 @@ class IPAddr
# Returns a string for DNS reverse lookup compatible with RFC1886.
def ip6_int
if !ipv6?
- raise InvalidAddressError, "not an IPv6 address"
+ raise InvalidAddressError, "not an IPv6 address: #{@addr}"
end
return _reverse + ".ip6.int"
end
@@ -404,7 +394,7 @@ class IPAddr
# Returns a hash value used by Hash, Set, and Array classes
def hash
- return ([@addr, @mask_addr].hash << 1) | (ipv4? ? 0 : 1)
+ return ([@addr, @mask_addr, @zone_id].hash << 1) | (ipv4? ? 0 : 1)
end
# Creates a Range object for the network address.
@@ -448,7 +438,7 @@ class IPAddr
when Integer
mask!(prefix)
else
- raise InvalidPrefixError, "prefix must be an integer"
+ raise InvalidPrefixError, "prefix must be an integer: #{@addr}"
end
end
@@ -460,11 +450,42 @@ class IPAddr
af = "IPv4"
when Socket::AF_INET6
af = "IPv6"
+ zone_id = @zone_id.to_s
else
raise AddressFamilyError, "unsupported address family"
end
- return sprintf("#<%s: %s:%s/%s>", self.class.name,
- af, _to_string(@addr), _to_string(@mask_addr))
+ return sprintf("#<%s: %s:%s%s/%s>", self.class.name,
+ af, _to_string(@addr), zone_id, _to_string(@mask_addr))
+ end
+
+ # Returns the netmask in string format e.g. 255.255.0.0
+ def netmask
+ _to_string(@mask_addr)
+ end
+
+ # Returns the IPv6 zone identifier, if present.
+ # Raises InvalidAddressError if not an IPv6 address.
+ def zone_id
+ if @family == Socket::AF_INET6
+ @zone_id
+ else
+ raise InvalidAddressError, "not an IPv6 address"
+ end
+ end
+
+ # Returns the IPv6 zone identifier, if present.
+ # Raises InvalidAddressError if not an IPv6 address.
+ def zone_id=(zid)
+ if @family == Socket::AF_INET6
+ case zid
+ when nil, /\A%(\w+)\z/
+ @zone_id = zid
+ else
+ raise InvalidAddressError, "invalid zone identifier for address"
+ end
+ else
+ raise InvalidAddressError, "not an IPv6 address"
+ end
end
protected
@@ -476,11 +497,11 @@ class IPAddr
case family[0] ? family[0] : @family
when Socket::AF_INET
if addr < 0 || addr > IN4MASK
- raise InvalidAddressError, "invalid address"
+ raise InvalidAddressError, "invalid address: #{@addr}"
end
when Socket::AF_INET6
if addr < 0 || addr > IN6MASK
- raise InvalidAddressError, "invalid address"
+ raise InvalidAddressError, "invalid address: #{@addr}"
end
else
raise AddressFamilyError, "unsupported address family"
@@ -496,17 +517,20 @@ class IPAddr
def mask!(mask)
case mask
when String
- if mask =~ /\A\d+\z/
+ case mask
+ when /\A(0|[1-9]+\d*)\z/
prefixlen = mask.to_i
+ when /\A\d+\z/
+ raise InvalidPrefixError, "leading zeros in prefix"
else
m = IPAddr.new(mask)
if m.family != @family
- raise InvalidPrefixError, "address family is not same"
+ raise InvalidPrefixError, "address family is not same: #{@addr}"
end
@mask_addr = m.to_i
n = @mask_addr ^ m.instance_variable_get(:@mask_addr)
unless ((n + 1) & n).zero?
- raise InvalidPrefixError, "invalid mask #{mask}"
+ raise InvalidPrefixError, "invalid mask #{mask}: #{@addr}"
end
@addr &= @mask_addr
return self
@@ -517,13 +541,13 @@ class IPAddr
case @family
when Socket::AF_INET
if prefixlen < 0 || prefixlen > 32
- raise InvalidPrefixError, "invalid length"
+ raise InvalidPrefixError, "invalid length: #{@addr}"
end
masklen = 32 - prefixlen
@mask_addr = ((IN4MASK >> masklen) << masklen)
when Socket::AF_INET6
if prefixlen < 0 || prefixlen > 128
- raise InvalidPrefixError, "invalid length"
+ raise InvalidPrefixError, "invalid length: #{@addr}"
end
masklen = 128 - prefixlen
@mask_addr = ((IN6MASK >> masklen) << masklen)
@@ -567,11 +591,16 @@ class IPAddr
raise AddressFamilyError, "unsupported address family: #{family}"
end
end
- prefix, prefixlen = addr.split('/')
+ prefix, prefixlen = addr.split('/', 2)
if prefix =~ /\A\[(.*)\]\z/i
prefix = $1
family = Socket::AF_INET6
end
+ if prefix =~ /\A(.*)(%\w+)\z/
+ prefix = $1
+ zone_id = $2
+ family = Socket::AF_INET6
+ end
# It seems AI_NUMERICHOST doesn't do the job.
#Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil,
# Socket::AI_NUMERICHOST)
@@ -586,6 +615,7 @@ class IPAddr
@addr = in6_addr(prefix)
@family = Socket::AF_INET6
end
+ @zone_id = zone_id
if family != Socket::AF_UNSPEC && @family != family
raise AddressFamilyError, "address family mismatch"
end
@@ -594,8 +624,6 @@ class IPAddr
else
@mask_addr = (@family == Socket::AF_INET) ? IN4MASK : IN6MASK
end
- rescue InvalidAddressError => e
- raise e.class, "#{e.message}: #{addr}"
end
def coerce_other(other)
@@ -618,8 +646,8 @@ class IPAddr
octets = m.captures
end
octets.inject(0) { |i, s|
- (n = s.to_i) < 256 or raise InvalidAddressError, "invalid address"
- s.match(/\A0./) and raise InvalidAddressError, "zero-filled number in IPv4 address is ambiguous"
+ (n = s.to_i) < 256 or raise InvalidAddressError, "invalid address: #{@addr}"
+ s.match(/\A0./) and raise InvalidAddressError, "zero-filled number in IPv4 address is ambiguous: #{@addr}"
i << 8 | n
}
end
@@ -636,19 +664,19 @@ class IPAddr
right = ''
when RE_IPV6ADDRLIKE_COMPRESSED
if $4
- left.count(':') <= 6 or raise InvalidAddressError, "invalid address"
+ left.count(':') <= 6 or raise InvalidAddressError, "invalid address: #{@addr}"
addr = in_addr($~[4,4])
left = $1
right = $3 + '0:0'
else
left.count(':') <= ($1.empty? || $2.empty? ? 8 : 7) or
- raise InvalidAddressError, "invalid address"
+ raise InvalidAddressError, "invalid address: #{@addr}"
left = $1
right = $2
addr = 0
end
else
- raise InvalidAddressError, "invalid address"
+ raise InvalidAddressError, "invalid address: #{@addr}"
end
l = left.split(':')
r = right.split(':')
diff --git a/lib/irb.rb b/lib/irb.rb
index fad738f7c89..6b296448db6 100644
--- a/lib/irb.rb
+++ b/lib/irb.rb
@@ -613,7 +613,7 @@ module IRB
ret = conv.primitive_convert(str, dst)
case ret
when :invalid_byte_sequence
- conv.insert_output(conf.primitive_errinfo[3].dump[1..-2])
+ conv.insert_output(conv.primitive_errinfo[3].dump[1..-2])
redo
when :undefined_conversion
c = conv.primitive_errinfo[3].dup.force_encoding(conv.primitive_errinfo[1])
@@ -867,7 +867,7 @@ module IRB
# If the expression is invalid, Ripper.sexp should return nil which will
# result in false being returned. Any valid expression should return an
- # s-expression where the second selement of the top level array is an
+ # s-expression where the second element of the top level array is an
# array of parsed expressions. The first element of each expression is the
# expression's type.
verbose, $VERBOSE = $VERBOSE, nil
diff --git a/lib/irb/cmd/show_source.rb b/lib/irb/cmd/show_source.rb
index feff8315f60..8f203ef1250 100644
--- a/lib/irb/cmd/show_source.rb
+++ b/lib/irb/cmd/show_source.rb
@@ -61,15 +61,12 @@ module IRB
lex = RubyLex.new
lines = File.read(file).lines[(first_line - 1)..-1]
tokens = RubyLex.ripper_lex_without_warning(lines.join)
-
- code = +""
prev_tokens = []
# chunk with line number
- tokens.chunk { |tok| tok[0][0] }.each do |lnum, chunk|
- code << lines[lnum]
+ tokens.chunk { |tok| tok.pos[0] }.each do |lnum, chunk|
+ code = lines[0..lnum].join
prev_tokens.concat chunk
-
continue = lex.process_continue(prev_tokens)
code_block_open = lex.check_code_block(code, prev_tokens)
if !continue && !code_block_open
diff --git a/lib/irb/completion.rb b/lib/irb/completion.rb
index a8a73cce80b..9121174a508 100644
--- a/lib/irb/completion.rb
+++ b/lib/irb/completion.rb
@@ -197,7 +197,7 @@ module IRB
end
candidates.grep(/^#{Regexp.quote(sym)}/)
- when /^::([A-Z][^:\.\(]*)$/
+ when /^::([A-Z][^:\.\(\)]*)$/
# Absolute Constant or class methods
receiver = $1
candidates = Object.constants.collect{|m| m.to_s}
diff --git a/lib/irb/context.rb b/lib/irb/context.rb
index 09fd840bd38..0a46c1b1d41 100644
--- a/lib/irb/context.rb
+++ b/lib/irb/context.rb
@@ -125,6 +125,8 @@ module IRB
end
self.save_history = IRB.conf[:SAVE_HISTORY] if IRB.conf[:SAVE_HISTORY]
+ @extra_doc_dirs = IRB.conf[:EXTRA_DOC_DIRS]
+
@echo = IRB.conf[:ECHO]
if @echo.nil?
@echo = true
@@ -148,18 +150,18 @@ module IRB
# The toplevel workspace, see #home_workspace
attr_reader :workspace_home
- # WorkSpace in the current context
+ # WorkSpace in the current context.
attr_accessor :workspace
- # The current thread in this context
+ # The current thread in this context.
attr_reader :thread
- # The current input method
+ # The current input method.
#
# Can be either StdioInputMethod, ReadlineInputMethod,
# ReidlineInputMethod, FileInputMethod or other specified when the
# context is created. See ::new for more # information on +input_method+.
attr_accessor :io
- # Current irb session
+ # Current irb session.
attr_accessor :irb
# A copy of the default <code>IRB.conf[:AP_NAME]</code>
attr_accessor :ap_name
@@ -193,15 +195,15 @@ module IRB
# A copy of the default <code>IRB.conf[:PROMPT_MODE]</code>
attr_reader :prompt_mode
- # Standard IRB prompt
+ # Standard IRB prompt.
#
# See IRB@Customizing+the+IRB+Prompt for more information.
attr_accessor :prompt_i
- # IRB prompt for continuated strings
+ # IRB prompt for continuated strings.
#
# See IRB@Customizing+the+IRB+Prompt for more information.
attr_accessor :prompt_s
- # IRB prompt for continuated statement (e.g. immediately after an +if+)
+ # IRB prompt for continuated statement. (e.g. immediately after an +if+)
#
# See IRB@Customizing+the+IRB+Prompt for more information.
attr_accessor :prompt_c
@@ -241,6 +243,9 @@ module IRB
#
# If set to +false+, <code>^D</code> will quit irb.
attr_accessor :ignore_eof
+ # Specify the installation locations of the ri file to be displayed in the
+ # document dialog.
+ attr_accessor :extra_doc_dirs
# Whether to echo the return value to output or not.
#
# Uses <code>IRB.conf[:ECHO]</code> if available, or defaults to +true+.
@@ -252,7 +257,7 @@ module IRB
# puts "omg"
# # omg
attr_accessor :echo
- # Whether to echo for assignment expressions
+ # Whether to echo for assignment expressions.
#
# If set to +false+, the value of assignment will not be shown.
#
@@ -386,6 +391,7 @@ module IRB
@prompt_c = pconf[:PROMPT_C]
@prompt_n = pconf[:PROMPT_N]
@return_format = pconf[:RETURN]
+ @return_format = "%s\n" if @return_format == nil
if ai = pconf.include?(:AUTO_INDENT)
@auto_indent_mode = ai
else
@@ -478,6 +484,8 @@ module IRB
# Exits the current session, see IRB.irb_exit
def exit(ret = 0)
IRB.irb_exit(@irb, ret)
+ rescue UncaughtThrowError
+ super
end
NOPRINTING_IVARS = ["@last_value"] # :nodoc:
diff --git a/lib/irb/init.rb b/lib/irb/init.rb
index 3c27b4ffffe..d2baee2017e 100644
--- a/lib/irb/init.rb
+++ b/lib/irb/init.rb
@@ -51,6 +51,7 @@ module IRB # :nodoc:
@CONF[:USE_LOADER] = false
@CONF[:IGNORE_SIGINT] = true
@CONF[:IGNORE_EOF] = false
+ @CONF[:EXTRA_DOC_DIRS] = []
@CONF[:ECHO] = nil
@CONF[:ECHO_ON_ASSIGNMENT] = nil
@CONF[:VERBOSE] = nil
@@ -257,6 +258,9 @@ module IRB # :nodoc:
@CONF[:USE_MULTILINE] = true
when "--nomultiline", "--noreidline"
@CONF[:USE_MULTILINE] = false
+ when /^--extra-doc-dir(?:=(.+))?/
+ opt = $1 || argv.shift
+ @CONF[:EXTRA_DOC_DIRS] << opt
when "--echo"
@CONF[:ECHO] = true
when "--noecho"
diff --git a/lib/irb/input-method.rb b/lib/irb/input-method.rb
index ea3f31bffc8..f7a4535da78 100644
--- a/lib/irb/input-method.rb
+++ b/lib/irb/input-method.rb
@@ -265,7 +265,8 @@ module IRB
class ReidlineInputMethod < InputMethod
include Reline
- # Creates a new input method object using Readline
+
+ # Creates a new input method object using Reline
def initialize
IRB.__send__(:set_encoding, Reline.encoding_system_needs.name, override: false)
super
@@ -317,13 +318,9 @@ module IRB
dialog.trap_key = nil
alt_d = [
[Reline::Key.new(nil, 0xE4, true)], # Normal Alt+d.
+ [27, 100], # Normal Alt+d when convert-meta isn't used.
[195, 164] # The "ä" that appears when Alt+d is pressed on xterm.
]
- begin
- require 'rdoc'
- rescue LoadError
- return nil
- end
if just_cursor_moving and completion_journey_data.nil?
return nil
@@ -333,7 +330,9 @@ module IRB
name = result[pointer]
name = IRB::InputCompletor.retrieve_completion_data(name, doc_namespace: true)
- driver = RDoc::RI::Driver.new
+ options = {}
+ options[:extra_doc_dirs] = IRB.conf[:EXTRA_DOC_DIRS] unless IRB.conf[:EXTRA_DOC_DIRS].empty?
+ driver = RDoc::RI::Driver.new(options)
if key.match?(dialog.name)
begin
@@ -370,14 +369,39 @@ module IRB
end
return nil if doc.nil?
width = 40
+
+ right_x = cursor_pos_to_render.x + autocomplete_dialog.width
+ if right_x + width > screen_width
+ right_width = screen_width - (right_x + 1)
+ left_x = autocomplete_dialog.column - width
+ left_x = 0 if left_x < 0
+ left_width = width > autocomplete_dialog.column ? autocomplete_dialog.column : width
+ if right_width.positive? and left_width.positive?
+ if right_width >= left_width
+ width = right_width
+ x = right_x
+ else
+ width = left_width
+ x = left_x
+ end
+ elsif right_width.positive? and left_width <= 0
+ width = right_width
+ x = right_x
+ elsif right_width <= 0 and left_width.positive?
+ width = left_width
+ x = left_x
+ else # Both are negative width.
+ return nil
+ end
+ else
+ x = right_x
+ end
formatter = RDoc::Markup::ToAnsi.new
formatter.width = width
dialog.trap_key = alt_d
message = 'Press Alt+d to read the full document'
contents = [message] + doc.accept(formatter).split("\n")
- x = cursor_pos_to_render.x + autocomplete_dialog.width
- x = autocomplete_dialog.column - width if x + width >= screen_width
y = cursor_pos_to_render.y
DialogRenderInfo.new(pos: Reline::CursorPos.new(x, y), contents: contents, width: width, bg_color: '49')
}
diff --git a/lib/irb/irb.gemspec b/lib/irb/irb.gemspec
index cb619b61f77..594fae7ff63 100644
--- a/lib/irb/irb.gemspec
+++ b/lib/irb/irb.gemspec
@@ -36,5 +36,5 @@ Gem::Specification.new do |spec|
spec.required_ruby_version = Gem::Requirement.new(">= 2.5")
- spec.add_dependency "reline", ">= 0.2.8.pre.9"
+ spec.add_dependency "reline", ">= 0.2.8.pre.11"
end
diff --git a/lib/irb/lc/help-message b/lib/irb/lc/help-message
index cee860fdeb6..939dc389759 100644
--- a/lib/irb/lc/help-message
+++ b/lib/irb/lc/help-message
@@ -20,6 +20,7 @@ Usage: irb.rb [options] [programfile] [arguments]
-W[level=2] Same as `ruby -W`
--context-mode n Set n[0-4] to method to create Binding Object,
when new workspace was created
+ --extra-doc-dir Add an extra doc dir for the doc dialog
--echo Show result (default)
--noecho Don't show result
--echo-on-assignment
diff --git a/lib/irb/ruby-lex.rb b/lib/irb/ruby-lex.rb
index f0c056e2979..f2069a2b5fd 100644
--- a/lib/irb/ruby-lex.rb
+++ b/lib/irb/ruby-lex.rb
@@ -87,8 +87,8 @@ class RubyLex
tokens.each do |t|
partial_tokens << t
unprocessed_tokens << t
- if t[2].include?("\n")
- t_str = t[2]
+ if t.tok.include?("\n")
+ t_str = t.tok
t_str.each_line("\n") do |s|
code << s << "\n"
ltype, indent, continue, code_block_open = check_state(code, partial_tokens, context: context)
@@ -97,9 +97,10 @@ class RubyLex
end
unprocessed_tokens = []
else
- code << t[2]
+ code << t.tok
end
end
+
unless unprocessed_tokens.empty?
ltype, indent, continue, code_block_open = check_state(code, unprocessed_tokens, context: context)
result << @prompt.call(ltype, indent, continue || code_block_open, @line_no + line_num_offset)
@@ -107,6 +108,7 @@ class RubyLex
result
end
end
+
if p.respond_to?(:call)
@input = p
elsif block_given?
@@ -153,19 +155,19 @@ class RubyLex
pos_to_index = {}
lexer.scan.each do |t|
next if t.pos.first == 0
- if pos_to_index.has_key?(t[0])
- index = pos_to_index[t[0]]
+ if pos_to_index.has_key?(t.pos)
+ index = pos_to_index[t.pos]
found_tk = tokens[index]
- if ERROR_TOKENS.include?(found_tk[1]) && !ERROR_TOKENS.include?(t[1])
+ if ERROR_TOKENS.include?(found_tk.event) && !ERROR_TOKENS.include?(t.event)
tokens[index] = t
end
else
- pos_to_index[t[0]] = tokens.size
+ pos_to_index[t.pos] = tokens.size
tokens << t
end
end
else
- tokens = lexer.parse
+ tokens = lexer.parse.reject { |it| it.pos.first == 0 }
end
end
tokens
@@ -175,17 +177,17 @@ class RubyLex
def find_prev_spaces(line_index)
return 0 if @tokens.size == 0
- md = @tokens[0][2].match(/(\A +)/)
+ md = @tokens[0].tok.match(/(\A +)/)
prev_spaces = md.nil? ? 0 : md[1].count(' ')
line_count = 0
@tokens.each_with_index do |t, i|
- if t[2].include?("\n")
- line_count += t[2].count("\n")
+ if t.tok.include?("\n")
+ line_count += t.tok.count("\n")
if line_count >= line_index
return prev_spaces
end
if (@tokens.size - 1) > i
- md = @tokens[i + 1][2].match(/(\A +)/)
+ md = @tokens[i + 1].tok.match(/(\A +)/)
prev_spaces = md.nil? ? 0 : md[1].count(' ')
end
end
@@ -295,18 +297,18 @@ class RubyLex
def process_continue(tokens = @tokens)
# last token is always newline
- if tokens.size >= 2 and tokens[-2][1] == :on_regexp_end
+ if tokens.size >= 2 and tokens[-2].event == :on_regexp_end
# end of regexp literal
return false
- elsif tokens.size >= 2 and tokens[-2][1] == :on_semicolon
+ elsif tokens.size >= 2 and tokens[-2].event == :on_semicolon
return false
- elsif tokens.size >= 2 and tokens[-2][1] == :on_kw and ['begin', 'else', 'ensure'].include?(tokens[-2][2])
+ elsif tokens.size >= 2 and tokens[-2].event == :on_kw and ['begin', 'else', 'ensure'].include?(tokens[-2].tok)
return false
- elsif !tokens.empty? and tokens.last[2] == "\\\n"
+ elsif !tokens.empty? and tokens.last.tok == "\\\n"
return true
- elsif tokens.size >= 1 and tokens[-1][1] == :on_heredoc_end # "EOH\n"
+ elsif tokens.size >= 1 and tokens[-1].event == :on_heredoc_end # "EOH\n"
return false
- elsif tokens.size >= 2 and defined?(Ripper::EXPR_BEG) and tokens[-2][3].anybits?(Ripper::EXPR_BEG | Ripper::EXPR_FNAME) and tokens[-2][2] !~ /\A\.\.\.?\z/
+ elsif tokens.size >= 2 and defined?(Ripper::EXPR_BEG) and tokens[-2].state.anybits?(Ripper::EXPR_BEG | Ripper::EXPR_FNAME) and tokens[-2].tok !~ /\A\.\.\.?\z/
# end of literal except for regexp
# endless range at end of line is not a continue
return true
@@ -316,7 +318,7 @@ class RubyLex
def check_code_block(code, tokens = @tokens)
return true if tokens.empty?
- if tokens.last[1] == :on_heredoc_beg
+ if tokens.last.event == :on_heredoc_beg
return true
end
@@ -388,7 +390,7 @@ class RubyLex
end
if defined?(Ripper::EXPR_BEG)
- last_lex_state = tokens.last[3]
+ last_lex_state = tokens.last.state
if last_lex_state.allbits?(Ripper::EXPR_BEG)
return false
elsif last_lex_state.allbits?(Ripper::EXPR_DOT)
@@ -413,14 +415,14 @@ class RubyLex
tokens.each_with_index { |t, index|
# detecting one-liner method definition
if in_oneliner_def.nil?
- if t[3].allbits?(Ripper::EXPR_ENDFN)
+ if t.state.allbits?(Ripper::EXPR_ENDFN)
in_oneliner_def = :ENDFN
end
else
- if t[3].allbits?(Ripper::EXPR_ENDFN)
+ if t.state.allbits?(Ripper::EXPR_ENDFN)
# continuing
- elsif t[3].allbits?(Ripper::EXPR_BEG)
- if t[2] == '='
+ elsif t.state.allbits?(Ripper::EXPR_BEG)
+ if t.tok == '='
in_oneliner_def = :BODY
end
else
@@ -432,14 +434,14 @@ class RubyLex
end
end
- case t[1]
+ case t.event
when :on_lbracket, :on_lbrace, :on_lparen, :on_tlambeg
indent += 1
when :on_rbracket, :on_rbrace, :on_rparen
indent -= 1
when :on_kw
- next if index > 0 and tokens[index - 1][3].allbits?(Ripper::EXPR_FNAME)
- case t[2]
+ next if index > 0 and tokens[index - 1].state.allbits?(Ripper::EXPR_FNAME)
+ case t.tok
when 'do'
syntax_of_do = take_corresponding_syntax_to_kw_do(tokens, index)
indent += 1 if syntax_of_do == :method_calling
@@ -447,7 +449,7 @@ class RubyLex
indent += 1
when 'if', 'unless', 'while', 'until'
# postfix if/unless/while/until must be Ripper::EXPR_LABEL
- indent += 1 unless t[3].allbits?(Ripper::EXPR_LABEL)
+ indent += 1 unless t.state.allbits?(Ripper::EXPR_LABEL)
when 'end'
indent -= 1
end
@@ -459,14 +461,14 @@ class RubyLex
def is_method_calling?(tokens, index)
tk = tokens[index]
- if tk[3].anybits?(Ripper::EXPR_CMDARG) and tk[1] == :on_ident
+ if tk.state.anybits?(Ripper::EXPR_CMDARG) and tk.event == :on_ident
# The target method call to pass the block with "do".
return true
- elsif tk[3].anybits?(Ripper::EXPR_ARG) and tk[1] == :on_ident
- non_sp_index = tokens[0..(index - 1)].rindex{ |t| t[1] != :on_sp }
+ elsif tk.state.anybits?(Ripper::EXPR_ARG) and tk.event == :on_ident
+ non_sp_index = tokens[0..(index - 1)].rindex{ |t| t.event != :on_sp }
if non_sp_index
prev_tk = tokens[non_sp_index]
- if prev_tk[3].anybits?(Ripper::EXPR_DOT) and prev_tk[1] == :on_period
+ if prev_tk.state.anybits?(Ripper::EXPR_DOT) and prev_tk.event == :on_period
# The target method call with receiver to pass the block with "do".
return true
end
@@ -477,21 +479,21 @@ class RubyLex
def take_corresponding_syntax_to_kw_do(tokens, index)
syntax_of_do = nil
- # Finding a syntax correnponding to "do".
+ # Finding a syntax corresponding to "do".
index.downto(0) do |i|
tk = tokens[i]
# In "continue", the token isn't the corresponding syntax to "do".
- non_sp_index = tokens[0..(i - 1)].rindex{ |t| t[1] != :on_sp }
+ non_sp_index = tokens[0..(i - 1)].rindex{ |t| t.event != :on_sp }
first_in_fomula = false
if non_sp_index.nil?
first_in_fomula = true
- elsif [:on_ignored_nl, :on_nl, :on_comment].include?(tokens[non_sp_index][1])
+ elsif [:on_ignored_nl, :on_nl, :on_comment].include?(tokens[non_sp_index].event)
first_in_fomula = true
end
if is_method_calling?(tokens, i)
syntax_of_do = :method_calling
break if first_in_fomula
- elsif tk[1] == :on_kw && %w{while until for}.include?(tk[2])
+ elsif tk.event == :on_kw && %w{while until for}.include?(tk.tok)
# A loop syntax in front of "do" found.
#
# while cond do # also "until" or "for"
@@ -508,18 +510,18 @@ class RubyLex
def is_the_in_correspond_to_a_for(tokens, index)
syntax_of_in = nil
- # Finding a syntax correnponding to "do".
+ # Finding a syntax corresponding to "do".
index.downto(0) do |i|
tk = tokens[i]
# In "continue", the token isn't the corresponding syntax to "do".
- non_sp_index = tokens[0..(i - 1)].rindex{ |t| t[1] != :on_sp }
+ non_sp_index = tokens[0..(i - 1)].rindex{ |t| t.event != :on_sp }
first_in_fomula = false
if non_sp_index.nil?
first_in_fomula = true
- elsif [:on_ignored_nl, :on_nl, :on_comment].include?(tokens[non_sp_index][1])
+ elsif [:on_ignored_nl, :on_nl, :on_comment].include?(tokens[non_sp_index].event)
first_in_fomula = true
end
- if tk[1] == :on_kw && tk[2] == 'for'
+ if tk.event == :on_kw && tk.tok == 'for'
# A loop syntax in front of "do" found.
#
# while cond do # also "until" or "for"
@@ -541,14 +543,14 @@ class RubyLex
@tokens.each_with_index do |t, index|
# detecting one-liner method definition
if in_oneliner_def.nil?
- if t[3].allbits?(Ripper::EXPR_ENDFN)
+ if t.state.allbits?(Ripper::EXPR_ENDFN)
in_oneliner_def = :ENDFN
end
else
- if t[3].allbits?(Ripper::EXPR_ENDFN)
+ if t.state.allbits?(Ripper::EXPR_ENDFN)
# continuing
- elsif t[3].allbits?(Ripper::EXPR_BEG)
- if t[2] == '='
+ elsif t.state.allbits?(Ripper::EXPR_BEG)
+ if t.tok == '='
in_oneliner_def = :BODY
end
else
@@ -560,7 +562,7 @@ class RubyLex
end
end
- case t[1]
+ case t.event
when :on_ignored_nl, :on_nl, :on_comment
if index != (@tokens.size - 1) and in_oneliner_def != :BODY
depth_difference = 0
@@ -570,15 +572,16 @@ class RubyLex
when :on_sp
next
end
- case t[1]
+
+ case t.event
when :on_lbracket, :on_lbrace, :on_lparen, :on_tlambeg
depth_difference += 1
open_brace_on_line += 1
when :on_rbracket, :on_rbrace, :on_rparen
depth_difference -= 1 if open_brace_on_line > 0
when :on_kw
- next if index > 0 and @tokens[index - 1][3].allbits?(Ripper::EXPR_FNAME)
- case t[2]
+ next if index > 0 and @tokens[index - 1].state.allbits?(Ripper::EXPR_FNAME)
+ case t.tok
when 'do'
syntax_of_do = take_corresponding_syntax_to_kw_do(@tokens, index)
depth_difference += 1 if syntax_of_do == :method_calling
@@ -586,7 +589,7 @@ class RubyLex
depth_difference += 1
when 'if', 'unless', 'while', 'until', 'rescue'
# postfix if/unless/while/until/rescue must be Ripper::EXPR_LABEL
- unless t[3].allbits?(Ripper::EXPR_LABEL)
+ unless t.state.allbits?(Ripper::EXPR_LABEL)
depth_difference += 1
end
when 'else', 'elsif', 'ensure', 'when'
@@ -619,14 +622,14 @@ class RubyLex
@tokens.each_with_index do |t, index|
# detecting one-liner method definition
if in_oneliner_def.nil?
- if t[3].allbits?(Ripper::EXPR_ENDFN)
+ if t.state.allbits?(Ripper::EXPR_ENDFN)
in_oneliner_def = :ENDFN
end
else
- if t[3].allbits?(Ripper::EXPR_ENDFN)
+ if t.state.allbits?(Ripper::EXPR_ENDFN)
# continuing
- elsif t[3].allbits?(Ripper::EXPR_BEG)
- if t[2] == '='
+ elsif t.state.allbits?(Ripper::EXPR_BEG)
+ if t.tok == '='
in_oneliner_def = :BODY
end
else
@@ -643,7 +646,7 @@ class RubyLex
end
end
- case t[1]
+ case t.event
when :on_ignored_nl, :on_nl, :on_comment
if in_oneliner_def != :BODY
corresponding_token_depth = nil
@@ -654,11 +657,12 @@ class RubyLex
end
next
when :on_sp
- spaces_at_line_head = t[2].count(' ') if is_first_spaces_of_line
+ spaces_at_line_head = t.tok.count(' ') if is_first_spaces_of_line
is_first_spaces_of_line = false
next
end
- case t[1]
+
+ case t.event
when :on_lbracket, :on_lbrace, :on_lparen, :on_tlambeg
spaces_of_nest.push(spaces_at_line_head + open_brace_on_line * 2)
open_brace_on_line += 1
@@ -671,8 +675,8 @@ class RubyLex
end
open_brace_on_line -= 1
when :on_kw
- next if index > 0 and @tokens[index - 1][3].allbits?(Ripper::EXPR_FNAME)
- case t[2]
+ next if index > 0 and @tokens[index - 1].state.allbits?(Ripper::EXPR_FNAME)
+ case t.tok
when 'do'
syntax_of_do = take_corresponding_syntax_to_kw_do(@tokens, index)
if syntax_of_do == :method_calling
@@ -681,16 +685,20 @@ class RubyLex
when 'def', 'case', 'for', 'begin', 'class', 'module'
spaces_of_nest.push(spaces_at_line_head)
when 'rescue'
- unless t[3].allbits?(Ripper::EXPR_LABEL)
+ unless t.state.allbits?(Ripper::EXPR_LABEL)
corresponding_token_depth = spaces_of_nest.last
end
when 'if', 'unless', 'while', 'until'
# postfix if/unless/while/until must be Ripper::EXPR_LABEL
- unless t[3].allbits?(Ripper::EXPR_LABEL)
+ unless t.state.allbits?(Ripper::EXPR_LABEL)
spaces_of_nest.push(spaces_at_line_head)
end
- when 'else', 'elsif', 'ensure', 'when', 'in'
+ when 'else', 'elsif', 'ensure', 'when'
corresponding_token_depth = spaces_of_nest.last
+ when 'in'
+ if in_keyword_case_scope?
+ corresponding_token_depth = spaces_of_nest.last
+ end
when 'end'
if is_first_printable_of_line
corresponding_token_depth = spaces_of_nest.pop
@@ -712,7 +720,7 @@ class RubyLex
end_type = []
while i < tokens.size
t = tokens[i]
- case t[1]
+ case t.event
when *end_type.last
start_token.pop
end_type.pop
@@ -725,7 +733,7 @@ class RubyLex
when :on_symbeg
acceptable_single_tokens = %i{on_ident on_const on_op on_cvar on_ivar on_gvar on_kw on_int on_backtick}
if (i + 1) < tokens.size
- if acceptable_single_tokens.all?{ |st| tokens[i + 1][1] != st }
+ if acceptable_single_tokens.all?{ |st| tokens[i + 1].event != st }
start_token << t
end_type << :on_tstring_end
else
@@ -749,9 +757,11 @@ class RubyLex
def process_literal_type(tokens = @tokens)
start_token = check_string_literal(tokens)
- case start_token[1]
+ return nil if start_token == ""
+
+ case start_token.event
when :on_tstring_beg
- case start_token[2]
+ case start_token.tok
when ?" then ?"
when /^%.$/ then ?"
when /^%Q.$/ then ?"
@@ -766,7 +776,7 @@ class RubyLex
when :on_qsymbols_beg then ?]
when :on_symbols_beg then ?]
when :on_heredoc_beg
- start_token[2] =~ /<<[-~]?(['"`])[_a-zA-Z0-9]+\1/
+ start_token.tok =~ /<<[-~]?(['"`])[_a-zA-Z0-9]+\1/
case $1
when ?" then ?"
when ?' then ?'
@@ -794,6 +804,7 @@ class RubyLex
false
end
end
+
if index
first_token = nil
last_line_tokens = tokens[(index + 1)..(tokens.size - 1)]
@@ -803,6 +814,7 @@ class RubyLex
break
end
end
+
if first_token.nil?
return false
elsif first_token && first_token.state == Ripper::EXPR_DOT
@@ -829,5 +841,21 @@ class RubyLex
heredoc_tokens = @tokens.select { |t| [:on_heredoc_beg, :on_heredoc_end].include?(t.event) }
heredoc_tokens[-1]&.event == :on_heredoc_beg
end
+
+ def in_keyword_case_scope?
+ kw_tokens = @tokens.select { |t| t.event == :on_kw && ['case', 'for', 'end'].include?(t.tok) }
+ counter = 0
+ kw_tokens.reverse.each do |t|
+ if t.tok == 'case'
+ return true if counter.zero?
+ counter += 1
+ elsif t.tok == 'for'
+ counter += 1
+ elsif t.tok == 'end'
+ counter -= 1
+ end
+ end
+ false
+ end
end
# :startdoc:
diff --git a/lib/irb/version.rb b/lib/irb/version.rb
index 4bf79e89ce0..df58edd4a57 100644
--- a/lib/irb/version.rb
+++ b/lib/irb/version.rb
@@ -11,7 +11,7 @@
#
module IRB # :nodoc:
- VERSION = "1.3.8.pre.9"
+ VERSION = "1.3.8.pre.11"
@RELEASE_VERSION = VERSION
- @LAST_UPDATE_DATE = "2021-09-10"
+ @LAST_UPDATE_DATE = "2021-10-09"
end
diff --git a/lib/logger/version.rb b/lib/logger/version.rb
index e0f71830d21..b2e6909c327 100644
--- a/lib/logger/version.rb
+++ b/lib/logger/version.rb
@@ -1,5 +1,5 @@
# frozen_string_literal: true
class Logger
- VERSION = "1.4.3"
+ VERSION = "1.4.4"
end
diff --git a/lib/mkmf.rb b/lib/mkmf.rb
index cab9a3f646b..52788ab3abc 100644
--- a/lib/mkmf.rb
+++ b/lib/mkmf.rb
@@ -386,38 +386,64 @@ MESSAGE
end
end
- def xsystem command, opts = nil
+ def expand_command(commands, envs = libpath_env)
varpat = /\$\((\w+)\)|\$\{(\w+)\}/
- if varpat =~ command
- vars = Hash.new {|h, k| h[k] = ENV[k]}
- command = command.dup
- nil while command.gsub!(varpat) {vars[$1||$2]}
+ vars = nil
+ expand = proc do |command|
+ case command
+ when Array
+ command.map(&expand)
+ when String
+ if varpat =~ command
+ vars ||= Hash.new {|h, k| h[k] = ENV[k]}
+ command = command.dup
+ nil while command.gsub!(varpat) {vars[$1||$2]}
+ end
+ command
+ else
+ command
+ end
+ end
+ if Array === commands
+ env, *commands = commands if Hash === commands.first
+ envs.merge!(env) if env
end
+ return envs, expand[commands]
+ end
+
+ def env_quote(envs)
+ envs.map {|e, v| "#{e}=#{v.quote}"}
+ end
+
+ def xsystem command, opts = nil
+ env, command = expand_command(command)
Logging::open do
- puts command.quote
+ puts [env_quote(env), command.quote].join(' ')
if opts and opts[:werror]
result = nil
Logging.postpone do |log|
- output = IO.popen(libpath_env, command, &:read)
+ output = IO.popen(env, command, &:read)
result = ($?.success? and File.zero?(log.path))
output
end
result
else
- system(libpath_env, command)
+ system(env, *command)
end
end
end
def xpopen command, *mode, &block
+ env, commands = expand_command(command)
+ command = [env_quote(env), command].join(' ')
Logging::open do
case mode[0]
- when nil, /^r/
+ when nil, Hash, /^r/
puts "#{command} |"
else
puts "| #{command}"
end
- IO.popen(libpath_env, command, *mode, &block)
+ IO.popen(env, commands, *mode, &block)
end
end
@@ -447,7 +473,7 @@ EOM
src.sub!(/[^\n]\z/, "\\&\n")
count = 0
begin
- open(conftest_source, "wb") do |cfile|
+ File.open(conftest_source, "wb") do |cfile|
cfile.print src
end
rescue Errno::EACCES
@@ -821,21 +847,13 @@ SRC
# You should use +have_var+ rather than +try_var+.
def try_var(var, headers = nil, opt = "", &b)
headers = cpp_include(headers)
- try_compile(<<"SRC", opt, &b) or
+ try_compile(<<"SRC", opt, &b)
#{headers}
/*top*/
extern int t(void);
#{MAIN_DOES_NOTHING 't'}
int t(void) { const volatile void *volatile p; p = &(&#{var})[0]; return !p; }
SRC
- try_link(<<"SRC", opt, &b)
-#{headers}
-/*top*/
-extern int t(void);
-#{MAIN_DOES_NOTHING 't'}
-extern int #{var};
-int t(void) { const volatile void *volatile p; p = &(&#{var})[0]; return !p; }
-SRC
end
# Returns whether or not the +src+ can be preprocessed with the C
@@ -1746,7 +1764,7 @@ SRC
hdr = hdr.join("")
log_src(hdr, "#{header} is")
unless (IO.read(header) == hdr rescue false)
- open(header, "wb") do |hfile|
+ File.open(header, "wb") do |hfile|
hfile.write(hdr)
end
end
@@ -1838,16 +1856,24 @@ SRC
# invoked with the option and a stripped output string is returned
# without modifying any of the global values mentioned above.
def pkg_config(pkg, option=nil)
+ _, ldir = dir_config(pkg)
+ if ldir
+ pkg_config_path = "#{ldir}/pkgconfig"
+ if File.directory?(pkg_config_path)
+ Logging.message("PKG_CONFIG_PATH = %s\n", pkg_config_path)
+ envs = ["PKG_CONFIG_PATH"=>[pkg_config_path, ENV["PKG_CONFIG_PATH"]].compact.join(File::PATH_SEPARATOR)]
+ end
+ end
if pkgconfig = with_config("#{pkg}-config") and find_executable0(pkgconfig)
# if and only if package specific config command is given
elsif ($PKGCONFIG ||=
(pkgconfig = with_config("pkg-config", ("pkg-config" unless CROSS_COMPILING))) &&
find_executable0(pkgconfig) && pkgconfig) and
- xsystem("#{$PKGCONFIG} --exists #{pkg}")
+ xsystem([*envs, $PKGCONFIG, "--exists", pkg])
# default to pkg-config command
pkgconfig = $PKGCONFIG
get = proc {|opt|
- opt = xpopen("#{$PKGCONFIG} --#{opt} #{pkg}", err:[:child, :out], &:read)
+ opt = xpopen([*envs, $PKGCONFIG, "--#{opt}", pkg], err:[:child, :out], &:read)
Logging.open {puts opt.each_line.map{|s|"=> #{s.inspect}"}}
opt.strip if $?.success?
}
@@ -1858,7 +1884,7 @@ SRC
end
if pkgconfig
get ||= proc {|opt|
- opt = xpopen("#{pkgconfig} --#{opt}", err:[:child, :out], &:read)
+ opt = xpopen([*envs, pkgconfig, "--#{opt}"], err:[:child, :out], &:read)
Logging.open {puts opt.each_line.map{|s|"=> #{s.inspect}"}}
opt.strip if $?.success?
}
@@ -2358,7 +2384,7 @@ CLEANOBJS = *.#{$OBJEXT} #{config_string('cleanobjs') {|t| t.gsub(/\$\*/, "$
" #"
conf = yield(conf) if block_given?
- mfile = open("Makefile", "wb")
+ mfile = File.open("Makefile", "wb")
mfile.puts(conf)
mfile.print "
all: #{$extout ? "install" : target ? "$(DLLIB)" : "Makefile"}
diff --git a/lib/mutex_m.rb b/lib/mutex_m.rb
index 706d3c1b3c6..abd0fc6add3 100644
--- a/lib/mutex_m.rb
+++ b/lib/mutex_m.rb
@@ -41,6 +41,7 @@
module Mutex_m
VERSION = "0.1.1"
+ Ractor.make_shareable(VERSION) if defined?(Ractor)
def Mutex_m.define_aliases(cl) # :nodoc:
cl.module_eval %q{
diff --git a/lib/net/http.rb b/lib/net/http.rb
index 1fcf13530de..552f818e5dc 100644
--- a/lib/net/http.rb
+++ b/lib/net/http.rb
@@ -327,6 +327,8 @@ module Net #:nodoc:
# HTTPInformation:: 1xx
# HTTPContinue:: 100
# HTTPSwitchProtocol:: 101
+ # HTTPProcessing:: 102
+ # HTTPEarlyHints:: 103
# HTTPSuccess:: 2xx
# HTTPOK:: 200
# HTTPCreated:: 201
@@ -336,6 +338,7 @@ module Net #:nodoc:
# HTTPResetContent:: 205
# HTTPPartialContent:: 206
# HTTPMultiStatus:: 207
+ # HTTPAlreadyReported:: 208
# HTTPIMUsed:: 226
# HTTPRedirection:: 3xx
# HTTPMultipleChoices:: 300
@@ -345,6 +348,7 @@ module Net #:nodoc:
# HTTPNotModified:: 304
# HTTPUseProxy:: 305
# HTTPTemporaryRedirect:: 307
+ # HTTPPermanentRedirect:: 308
# HTTPClientError:: 4xx
# HTTPBadRequest:: 400
# HTTPUnauthorized:: 401
@@ -364,6 +368,7 @@ module Net #:nodoc:
# HTTPUnsupportedMediaType:: 415
# HTTPRequestedRangeNotSatisfiable:: 416
# HTTPExpectationFailed:: 417
+ # HTTPMisdirectedRequest:: 421
# HTTPUnprocessableEntity:: 422
# HTTPLocked:: 423
# HTTPFailedDependency:: 424
@@ -379,7 +384,10 @@ module Net #:nodoc:
# HTTPServiceUnavailable:: 503
# HTTPGatewayTimeOut:: 504
# HTTPVersionNotSupported:: 505
+ # HTTPVariantAlsoNegotiates:: 506
# HTTPInsufficientStorage:: 507
+ # HTTPLoopDetected:: 508
+ # HTTPNotExtended:: 510
# HTTPNetworkAuthenticationRequired:: 511
#
# There is also the Net::HTTPBadResponse exception which is raised when
@@ -388,7 +396,7 @@ module Net #:nodoc:
class HTTP < Protocol
# :stopdoc:
- VERSION = "0.1.1"
+ VERSION = "0.2.0"
Revision = %q$Revision$.split[1]
HTTPVersion = '1.1'
begin
@@ -1047,6 +1055,7 @@ module Net #:nodoc:
write_timeout: @write_timeout,
continue_timeout: @continue_timeout,
debug_output: @debug_output)
+ @last_communicated = nil
on_connect
rescue => exception
if s
diff --git a/lib/net/http/backward.rb b/lib/net/http/backward.rb
index 9e24eae32c4..691e41e4f10 100644
--- a/lib/net/http/backward.rb
+++ b/lib/net/http/backward.rb
@@ -5,22 +5,36 @@
class Net::HTTP
ProxyMod = ProxyDelta
-end
-
-module Net
- HTTPSession = Net::HTTP
+ deprecate_constant :ProxyMod
end
module Net::NetPrivate
HTTPRequest = ::Net::HTTPRequest
+ deprecate_constant :HTTPRequest
end
-Net::HTTPInformationCode = Net::HTTPInformation
-Net::HTTPSuccessCode = Net::HTTPSuccess
-Net::HTTPRedirectionCode = Net::HTTPRedirection
-Net::HTTPRetriableCode = Net::HTTPRedirection
-Net::HTTPClientErrorCode = Net::HTTPClientError
-Net::HTTPFatalErrorCode = Net::HTTPClientError
-Net::HTTPServerErrorCode = Net::HTTPServerError
-Net::HTTPResponceReceiver = Net::HTTPResponse
+module Net
+ HTTPSession = HTTP
+ HTTPInformationCode = HTTPInformation
+ HTTPSuccessCode = HTTPSuccess
+ HTTPRedirectionCode = HTTPRedirection
+ HTTPRetriableCode = HTTPRedirection
+ HTTPClientErrorCode = HTTPClientError
+ HTTPFatalErrorCode = HTTPClientError
+ HTTPServerErrorCode = HTTPServerError
+ HTTPResponseReceiver = HTTPResponse
+
+ HTTPResponceReceiver = HTTPResponse # Typo since 2001
+
+ deprecate_constant :HTTPSession,
+ :HTTPInformationCode,
+ :HTTPSuccessCode,
+ :HTTPRedirectionCode,
+ :HTTPRetriableCode,
+ :HTTPClientErrorCode,
+ :HTTPFatalErrorCode,
+ :HTTPServerErrorCode,
+ :HTTPResponseReceiver,
+ :HTTPResponceReceiver
+end
diff --git a/lib/net/http/generic_request.rb b/lib/net/http/generic_request.rb
index d6198cd6246..313de6ac923 100644
--- a/lib/net/http/generic_request.rb
+++ b/lib/net/http/generic_request.rb
@@ -31,12 +31,12 @@ class Net::HTTPGenericRequest
@decode_content = false
- if @response_has_body and Net::HTTP::HAVE_ZLIB then
+ if Net::HTTP::HAVE_ZLIB then
if !initheader ||
!initheader.keys.any? { |k|
%w[accept-encoding range].include? k.downcase
} then
- @decode_content = true
+ @decode_content = true if @response_has_body
initheader = initheader ? initheader.dup : {}
initheader["accept-encoding"] =
"gzip;q=1.0,deflate;q=0.6,identity;q=0.3"
diff --git a/lib/net/http/net-http.gemspec b/lib/net/http/net-http.gemspec
index f5ef4045e8f..dd4fc2b17ed 100644
--- a/lib/net/http/net-http.gemspec
+++ b/lib/net/http/net-http.gemspec
@@ -28,7 +28,6 @@ Gem::Specification.new do |spec|
`git ls-files -z 2>/dev/null`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "exe"
- spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "net-protocol"
diff --git a/lib/net/net-protocol.gemspec b/lib/net/net-protocol.gemspec
index 767a7d48e28..021a5dcbf33 100644
--- a/lib/net/net-protocol.gemspec
+++ b/lib/net/net-protocol.gemspec
@@ -16,7 +16,7 @@ Gem::Specification.new do |spec|
spec.summary = %q{The abstruct interface for net-* client.}
spec.description = %q{The abstruct interface for net-* client.}
spec.homepage = "https://github.com/ruby/net-protocol"
- spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.6.0")
spec.licenses = ["Ruby", "BSD-2-Clause"]
spec.metadata["homepage_uri"] = spec.homepage
diff --git a/lib/net/protocol.rb b/lib/net/protocol.rb
index 0afac2a02a6..add2c87a71a 100644
--- a/lib/net/protocol.rb
+++ b/lib/net/protocol.rb
@@ -26,7 +26,7 @@ require 'io/wait'
module Net # :nodoc:
class Protocol #:nodoc: internal use only
- VERSION = "0.1.1"
+ VERSION = "0.1.2"
private
def Protocol.protocol_param(name, val)
diff --git a/lib/open-uri.gemspec b/lib/open-uri.gemspec
index 853049f7ece..cc41fc60cf9 100644
--- a/lib/open-uri.gemspec
+++ b/lib/open-uri.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |spec|
spec.name = "open-uri"
- spec.version = "0.1.0"
+ spec.version = "0.2.0"
spec.authors = ["Tanaka Akira"]
spec.email = ["akr@fsij.org"]
diff --git a/lib/optparse.rb b/lib/optparse.rb
index 060b13428a5..61dd87f5589 100644
--- a/lib/optparse.rb
+++ b/lib/optparse.rb
@@ -425,7 +425,7 @@
# If you have any questions, file a ticket at http://bugs.ruby-lang.org.
#
class OptionParser
- OptionParser::Version = "0.1.1"
+ OptionParser::Version = "0.2.0"
# :stopdoc:
NoArgument = [NO_ARGUMENT = :NONE, nil].freeze
diff --git a/lib/ostruct.rb b/lib/ostruct.rb
index ecfacd10fbd..c2de7a493d8 100644
--- a/lib/ostruct.rb
+++ b/lib/ostruct.rb
@@ -93,21 +93,21 @@
# o.methods = [:foo, :bar]
# o.methods # => [:foo, :bar]
#
-# To help remedy clashes, OpenStruct uses only protected/private methods ending with `!`
-# and defines aliases for builtin public methods by adding a `!`:
+# To help remedy clashes, OpenStruct uses only protected/private methods ending with <code>!</code>
+# and defines aliases for builtin public methods by adding a <code>!</code>:
#
# o = OpenStruct.new(make: 'Bentley', class: :luxury)
# o.class # => :luxury
# o.class! # => OpenStruct
#
-# It is recommended (but not enforced) to not use fields ending in `!`;
+# It is recommended (but not enforced) to not use fields ending in <code>!</code>;
# Note that a subclass' methods may not be overwritten, nor can OpenStruct's own methods
-# ending with `!`.
+# ending with <code>!</code>.
#
# For all these reasons, consider not using OpenStruct at all.
#
class OpenStruct
- VERSION = "0.4.0"
+ VERSION = "0.5.0"
#
# Creates a new OpenStruct object. By default, the resulting OpenStruct
@@ -279,7 +279,7 @@ class OpenStruct
# :call-seq:
# ostruct[name] -> object
#
- # Returns the value of an attribute, or `nil` if there is no such attribute.
+ # Returns the value of an attribute, or +nil+ if there is no such attribute.
#
# require "ostruct"
# person = OpenStruct.new("name" => "John Smith", "age" => 70)
@@ -452,7 +452,7 @@ class OpenStruct
update_to_values!(h)
end
- # Make all public methods (builtin or our own) accessible with `!`:
+ # Make all public methods (builtin or our own) accessible with <code>!</code>:
instance_methods.each do |method|
new_name = "#{method}!"
alias_method new_name, method
diff --git a/lib/pp.gemspec b/lib/pp.gemspec
index 4d2400c31cc..b81df28bee7 100644
--- a/lib/pp.gemspec
+++ b/lib/pp.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |spec|
spec.name = "pp"
- spec.version = "0.2.0"
+ spec.version = "0.2.1"
spec.authors = ["Tanaka Akira"]
spec.email = ["akr@fsij.org"]
diff --git a/lib/pp.rb b/lib/pp.rb
index 72480e53047..eb8ea1e10a2 100644
--- a/lib/pp.rb
+++ b/lib/pp.rb
@@ -61,6 +61,15 @@ require 'prettyprint'
# Tanaka Akira <akr@fsij.org>
class PP < PrettyPrint
+ def PP.width_for(out)
+ begin
+ require 'io/console'
+ _, width = out.winsize
+ rescue LoadError, NoMethodError, SystemCallError
+ end
+ (width || ENV['COLUMNS']&.to_i&.nonzero? || 80) - 1
+ end
+
# Outputs +obj+ to +out+ in pretty printed format of
# +width+ columns in width.
#
@@ -68,7 +77,7 @@ class PP < PrettyPrint
# If +width+ is omitted, 79 is assumed.
#
# PP.pp returns +out+.
- def PP.pp(obj, out=$>, width=79)
+ def PP.pp(obj, out=$>, width=width_for(out))
q = PP.new(out, width)
q.guard_inspect_key {q.pp obj}
q.flush
diff --git a/lib/prettyprint.gemspec b/lib/prettyprint.gemspec
index 169267fb167..eae2227d604 100644
--- a/lib/prettyprint.gemspec
+++ b/lib/prettyprint.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |spec|
spec.name = "prettyprint"
- spec.version = "0.1.0"
+ spec.version = "0.1.1"
spec.authors = ["Tanaka Akira"]
spec.email = ["akr@fsij.org"]
diff --git a/lib/racc/grammar.rb b/lib/racc/grammar.rb
index 3444dfcce3e..01c4c3df69b 100644
--- a/lib/racc/grammar.rb
+++ b/lib/racc/grammar.rb
@@ -335,14 +335,14 @@ module Racc
if action
idbase = "#{type}@#{id}-#{@seqs[type] += 1}"
target = _wrap(idbase, "#{idbase}-core", action)
- _regist("#{idbase}-core", &block)
+ _register("#{idbase}-core", &block)
else
- target = _regist("#{type}@#{id}", &block)
+ target = _register("#{type}@#{id}", &block)
end
@grammar.intern(target)
end
- def _regist(target_name)
+ def _register(target_name)
target = target_name.intern
unless _added?(@grammar.intern(target))
yield(target).each_rule do |rule|
diff --git a/lib/racc/grammarfileparser.rb b/lib/racc/grammarfileparser.rb
index 419495113b8..c7d1207f0b5 100644
--- a/lib/racc/grammarfileparser.rb
+++ b/lib/racc/grammarfileparser.rb
@@ -260,9 +260,9 @@ module Racc
_, *blocks = *@scanner.epilogue.split(/^----/)
blocks.each do |block|
header, *body = block.lines.to_a
- label0, pathes = *header.sub(/\A-+/, '').split('=', 2)
+ label0, paths = *header.sub(/\A-+/, '').split('=', 2)
label = canonical_label(label0)
- (pathes ? pathes.strip.split(' ') : []).each do |path|
+ (paths ? paths.strip.split(' ') : []).each do |path|
add_user_code label, SourceText.new(File.read(path), path, 1)
end
add_user_code label, SourceText.new(body.join(''), @filename, line + 1)
diff --git a/lib/racc/info.rb b/lib/racc/info.rb
index f599b13cbb2..bb1f100adc0 100644
--- a/lib/racc/info.rb
+++ b/lib/racc/info.rb
@@ -11,7 +11,7 @@
#++
module Racc
- VERSION = '1.5.2'
+ VERSION = '1.6.0'
Version = VERSION
Copyright = 'Copyright (c) 1999-2006 Minero Aoki'
end
diff --git a/lib/rdoc/any_method.rb b/lib/rdoc/any_method.rb
index 562e68461c3..0b7dd717ab9 100644
--- a/lib/rdoc/any_method.rb
+++ b/lib/rdoc/any_method.rb
@@ -26,6 +26,9 @@ class RDoc::AnyMethod < RDoc::MethodAttr
attr_accessor :c_function
+ # The section title of the method (if defined in a C file via +:category:+)
+ attr_accessor :section_title
+
# Parameters for this method
attr_accessor :params
@@ -356,6 +359,6 @@ class RDoc::AnyMethod < RDoc::MethodAttr
entry =~ /\s#{ignore}\s/
end
- matching.join "\n"
+ matching.empty? ? nil : matching.join("\n")
end
end
diff --git a/lib/rdoc/cross_reference.rb b/lib/rdoc/cross_reference.rb
index 99a64cd99a7..4a6abfa3ac0 100644
--- a/lib/rdoc/cross_reference.rb
+++ b/lib/rdoc/cross_reference.rb
@@ -19,7 +19,7 @@ class RDoc::CrossReference
#
# See CLASS_REGEXP_STR
- METHOD_REGEXP_STR = '([a-z]\w*[!?=]?|%|===|\[\]=?|<<|>>|\+@|-@|-|\+|\*)(?:\([\w.+*/=<>-]*\))?'
+ METHOD_REGEXP_STR = '([a-z]\w*[!?=]?|%|===?|\[\]=?|<<|>>|\+@|-@|-|\+|\*)(?:\([\w.+*/=<>-]*\))?'
##
# Regular expressions matching text that should potentially have
diff --git a/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Bold.ttf b/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Bold.ttf
index 61e3090c1c6..dd00982d495 100644
--- a/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Bold.ttf
+++ b/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Bold.ttf
Binary files differ
diff --git a/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Regular.ttf b/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Regular.ttf
index 85686d967df..1decfb95af6 100644
--- a/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Regular.ttf
+++ b/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Regular.ttf
Binary files differ
diff --git a/lib/rdoc/markup/pre_process.rb b/lib/rdoc/markup/pre_process.rb
index 3080ae35787..88078c9cefc 100644
--- a/lib/rdoc/markup/pre_process.rb
+++ b/lib/rdoc/markup/pre_process.rb
@@ -163,6 +163,8 @@ class RDoc::Markup::PreProcess
if RDoc::Context === code_object then
section = code_object.add_section param
code_object.temporary_section = section
+ elsif RDoc::AnyMethod === code_object then
+ code_object.section_title = param
end
blankline # ignore category if we're not on an RDoc::Context
diff --git a/lib/rdoc/parser/c.rb b/lib/rdoc/parser/c.rb
index 9d8db6cdee4..b89aaa6dcc9 100644
--- a/lib/rdoc/parser/c.rb
+++ b/lib/rdoc/parser/c.rb
@@ -173,6 +173,8 @@ class RDoc::Parser::C < RDoc::Parser
@classes = load_variable_map :c_class_variables
@singleton_classes = load_variable_map :c_singleton_class_variables
+ @markup = @options.markup
+
# class_variable => { function => [method, ...] }
@methods = Hash.new { |h, f| h[f] = Hash.new { |i, m| i[m] = [] } }
@@ -439,7 +441,7 @@ class RDoc::Parser::C < RDoc::Parser
next unless cls = @classes[c]
m = @known_classes[m] || m
- comment = RDoc::Comment.new '', @top_level, :c
+ comment = new_comment '', @top_level, :c
incl = cls.add_include RDoc::Include.new(m, comment)
incl.record_location @top_level
end
@@ -521,7 +523,7 @@ class RDoc::Parser::C < RDoc::Parser
\s*"#{Regexp.escape new_name}"\s*,
\s*"#{Regexp.escape old_name}"\s*\);%xm
- RDoc::Comment.new($1 || '', @top_level, :c)
+ new_comment($1 || '', @top_level, :c)
end
##
@@ -560,7 +562,7 @@ class RDoc::Parser::C < RDoc::Parser
''
end
- RDoc::Comment.new comment, @top_level, :c
+ new_comment comment, @top_level, :c
end
##
@@ -600,7 +602,7 @@ class RDoc::Parser::C < RDoc::Parser
case type
when :func_def
- comment = RDoc::Comment.new args[0], @top_level, :c
+ comment = new_comment args[0], @top_level, :c
body = args[1]
offset, = args[2]
@@ -630,7 +632,7 @@ class RDoc::Parser::C < RDoc::Parser
body
when :macro_def
- comment = RDoc::Comment.new args[0], @top_level, :c
+ comment = new_comment args[0], @top_level, :c
body = args[1]
offset, = args[2]
@@ -737,7 +739,7 @@ class RDoc::Parser::C < RDoc::Parser
comment = ''
end
- comment = RDoc::Comment.new comment, @top_level, :c
+ comment = new_comment comment, @top_level, :c
comment.normalize
look_for_directives_in class_mod, comment
@@ -782,7 +784,7 @@ class RDoc::Parser::C < RDoc::Parser
table[const_name] ||
''
- RDoc::Comment.new comment, @top_level, :c
+ new_comment comment, @top_level, :c
end
##
@@ -813,7 +815,7 @@ class RDoc::Parser::C < RDoc::Parser
return unless comment
- RDoc::Comment.new comment, @top_level, :c
+ new_comment comment, @top_level, :c
end
##
@@ -947,7 +949,7 @@ class RDoc::Parser::C < RDoc::Parser
new_comment = "#{$1}#{new_comment.lstrip}"
- new_comment = RDoc::Comment.new new_comment, @top_level, :c
+ new_comment = self.new_comment(new_comment, @top_level, :c)
con = RDoc::Constant.new const_name, new_definition, new_comment
else
@@ -1028,7 +1030,12 @@ class RDoc::Parser::C < RDoc::Parser
meth_obj.record_location @top_level
+
+ if meth_obj.section_title
+ class_obj.temporary_section = class_obj.add_section(meth_obj.section_title)
+ end
class_obj.add_method meth_obj
+
@stats.add_method meth_obj
meth_obj.visibility = :private if 'private_method' == type
end
@@ -1222,4 +1229,9 @@ class RDoc::Parser::C < RDoc::Parser
@top_level
end
+ def new_comment text = nil, location = nil, language = nil
+ RDoc::Comment.new(text, location, language).tap do |comment|
+ comment.format = @markup
+ end
+ end
end
diff --git a/lib/readline.rb b/lib/readline.rb
index 6cc923cb2fb..29cdf3a14f0 100644
--- a/lib/readline.rb
+++ b/lib/readline.rb
@@ -2,5 +2,6 @@ begin
require 'readline.so'
rescue LoadError
require 'reline' unless defined? Reline
+ Object.send(:remove_const, :Readline) if Object.const_defined?(:Readline)
Readline = Reline
end
diff --git a/lib/reline.rb b/lib/reline.rb
index 9746b35ac5f..b872fe69455 100644
--- a/lib/reline.rb
+++ b/lib/reline.rb
@@ -17,19 +17,15 @@ module Reline
class ConfigEncodingConversionError < StandardError; end
Key = Struct.new('Key', :char, :combined_char, :with_meta) do
- def match?(key)
- if key.instance_of?(Reline::Key)
- (key.char.nil? or char.nil? or char == key.char) and
- (key.combined_char.nil? or combined_char.nil? or combined_char == key.combined_char) and
- (key.with_meta.nil? or with_meta.nil? or with_meta == key.with_meta)
- elsif key.is_a?(Integer) or key.is_a?(Symbol)
- if not combined_char.nil? and combined_char == key
- true
- elsif combined_char.nil? and not char.nil? and char == key
- true
- else
- false
- end
+ def match?(other)
+ case other
+ when Reline::Key
+ (other.char.nil? or char.nil? or char == other.char) and
+ (other.combined_char.nil? or combined_char.nil? or combined_char == other.combined_char) and
+ (other.with_meta.nil? or with_meta.nil? or with_meta == other.with_meta)
+ when Integer, Symbol
+ (combined_char and combined_char == other) or
+ (combined_char.nil? and char and char == other)
else
false
end
@@ -461,7 +457,7 @@ module Reline
private def may_req_ambiguous_char_width
@ambiguous_width = 2 if Reline::IOGate == Reline::GeneralIO or STDOUT.is_a?(File)
- return if @ambiguous_width
+ return if defined? @ambiguous_width
Reline::IOGate.move_cursor_column(0)
begin
output.write "\u{25bd}"
diff --git a/lib/reline/ansi.rb b/lib/reline/ansi.rb
index f34d0b53fe3..c5648732419 100644
--- a/lib/reline/ansi.rb
+++ b/lib/reline/ansi.rb
@@ -4,6 +4,19 @@ require 'timeout'
require_relative 'terminfo'
class Reline::ANSI
+ CAPNAME_KEY_BINDINGS = {
+ 'khome' => :ed_move_to_beg,
+ 'kend' => :ed_move_to_end,
+ 'kcuu1' => :ed_prev_history,
+ 'kcud1' => :ed_next_history,
+ 'kcuf1' => :ed_next_char,
+ 'kcub1' => :ed_prev_char,
+ 'cuu' => :ed_prev_history,
+ 'cud' => :ed_next_history,
+ 'cuf' => :ed_next_char,
+ 'cub' => :ed_prev_char,
+ }
+
if Reline::Terminfo.enabled?
Reline::Terminfo.setupterm(0, 2)
end
@@ -44,20 +57,23 @@ class Reline::ANSI
end
def self.set_default_key_bindings_terminfo(config)
- {
- Reline::Terminfo.tigetstr('khome').bytes => :ed_move_to_beg,
- Reline::Terminfo.tigetstr('kend').bytes => :ed_move_to_end,
- Reline::Terminfo.tigetstr('kcuu1').bytes => :ed_prev_history,
- Reline::Terminfo.tigetstr('kcud1').bytes => :ed_next_history,
- Reline::Terminfo.tigetstr('kcuf1').bytes => :ed_next_char,
- Reline::Terminfo.tigetstr('kcub1').bytes => :ed_prev_char,
- # Escape sequences that omit the move distance and are set to defaults
- # value 1 may be sometimes sent by pressing the arrow-key.
- Reline::Terminfo.tigetstr('cuu').sub(/%p1%d/, '').bytes => :ed_prev_history,
- Reline::Terminfo.tigetstr('cud').sub(/%p1%d/, '').bytes => :ed_next_history,
- Reline::Terminfo.tigetstr('cuf').sub(/%p1%d/, '').bytes => :ed_next_char,
- Reline::Terminfo.tigetstr('cub').sub(/%p1%d/, '').bytes => :ed_prev_char,
- }.each_pair do |key, func|
+ key_bindings = CAPNAME_KEY_BINDINGS.map do |capname, key_binding|
+ begin
+ key_code = Reline::Terminfo.tigetstr(capname)
+ case capname
+ # Escape sequences that omit the move distance and are set to defaults
+ # value 1 may be sometimes sent by pressing the arrow-key.
+ when 'cuu', 'cud', 'cuf', 'cub'
+ [ key_code.sub(/%p1%d/, '').bytes, key_binding ]
+ else
+ [ key_code.bytes, key_binding ]
+ end
+ rescue Reline::Terminfo::TerminfoError
+ # capname is undefined
+ end
+ end.compact.to_h
+
+ key_bindings.each_pair do |key, func|
config.add_default_key_binding_by_keymap(:emacs, key, func)
config.add_default_key_binding_by_keymap(:vi_insert, key, func)
config.add_default_key_binding_by_keymap(:vi_command, key, func)
@@ -126,8 +142,8 @@ class Reline::ANSI
unless @@buf.empty?
return @@buf.shift
end
- until c = @@input.raw(intr: true, &:getbyte)
- sleep 0.1
+ until c = @@input.raw(intr: true) { select([@@input], [], [], 0.1) && @@input.getbyte }
+ Reline.core.line_editor.resize
end
(c == 0x16 && @@input.raw(min: 0, tim: 0, &:getbyte)) || c
rescue Errno::EIO
@@ -261,7 +277,7 @@ class Reline::ANSI
def self.move_cursor_up(x)
if x > 0
- @@output.write "\e[#{x}A" if x > 0
+ @@output.write "\e[#{x}A"
elsif x < 0
move_cursor_down(-x)
end
@@ -269,7 +285,7 @@ class Reline::ANSI
def self.move_cursor_down(x)
if x > 0
- @@output.write "\e[#{x}B" if x > 0
+ @@output.write "\e[#{x}B"
elsif x < 0
move_cursor_up(-x)
end
@@ -277,7 +293,11 @@ class Reline::ANSI
def self.hide_cursor
if Reline::Terminfo.enabled?
- @@output.write Reline::Terminfo.tigetstr('civis')
+ begin
+ @@output.write Reline::Terminfo.tigetstr('civis')
+ rescue Reline::Terminfo::TerminfoError
+ # civis is undefined
+ end
else
# ignored
end
@@ -285,7 +305,11 @@ class Reline::ANSI
def self.show_cursor
if Reline::Terminfo.enabled?
- @@output.write Reline::Terminfo.tigetstr('cnorm')
+ begin
+ @@output.write Reline::Terminfo.tigetstr('cnorm')
+ rescue Reline::Terminfo::TerminfoError
+ # cnorm is undefined
+ end
else
# ignored
end
diff --git a/lib/reline/line_editor.rb b/lib/reline/line_editor.rb
index 71cca85ad05..50bd22b424a 100644
--- a/lib/reline/line_editor.rb
+++ b/lib/reline/line_editor.rb
@@ -5,6 +5,7 @@ require 'tempfile'
class Reline::LineEditor
# TODO: undo
+ # TODO: Use "private alias_method" idiom after drop Ruby 2.5.
attr_reader :line
attr_reader :byte_pointer
attr_accessor :confirm_multiline_termination_proc
@@ -178,43 +179,69 @@ class Reline::LineEditor
rescue ArgumentError
end
Reline::IOGate.set_winch_handler do
- @rest_height = (Reline::IOGate.get_screen_size.first - 1) - Reline::IOGate.cursor_pos.y
- old_screen_size = @screen_size
- @screen_size = Reline::IOGate.get_screen_size
- @screen_height = @screen_size.first
- if old_screen_size.last < @screen_size.last # columns increase
- @rerender_all = true
- rerender
- else
- back = 0
- new_buffer = whole_lines
- prompt, prompt_width, prompt_list = check_multiline_prompt(new_buffer, prompt)
- new_buffer.each_with_index do |line, index|
- prompt_width = calculate_width(prompt_list[index], true) if @prompt_proc
- width = prompt_width + calculate_width(line)
- height = calculate_height_by_width(width)
- back += height
- end
- @highest_in_all = back
- @highest_in_this = calculate_height_by_width(prompt_width + @cursor_max)
- @first_line_started_from =
- if @line_index.zero?
- 0
- else
- calculate_height_by_lines(@buffer_of_lines[0..(@line_index - 1)], prompt_list || prompt)
- end
- if @prompt_proc
- prompt = prompt_list[@line_index]
- prompt_width = calculate_width(prompt, true)
+ @resized = true
+ end
+ if ENV.key?('RELINE_ALT_SCROLLBAR')
+ @full_block = '::'
+ @upper_half_block = "''"
+ @lower_half_block = '..'
+ @block_elem_width = 2
+ elsif Reline::IOGate.win?
+ @full_block = '█'
+ @upper_half_block = '▀'
+ @lower_half_block = '▄'
+ @block_elem_width = 1
+ elsif @encoding == Encoding::UTF_8
+ @full_block = '█'
+ @upper_half_block = '▀'
+ @lower_half_block = '▄'
+ @block_elem_width = Reline::Unicode.calculate_width('█')
+ else
+ @full_block = '::'
+ @upper_half_block = "''"
+ @lower_half_block = '..'
+ @block_elem_width = 2
+ end
+ end
+
+ def resize
+ return unless @resized
+ @resized = false
+ @rest_height = (Reline::IOGate.get_screen_size.first - 1) - Reline::IOGate.cursor_pos.y
+ old_screen_size = @screen_size
+ @screen_size = Reline::IOGate.get_screen_size
+ @screen_height = @screen_size.first
+ if old_screen_size.last < @screen_size.last # columns increase
+ @rerender_all = true
+ rerender
+ else
+ back = 0
+ new_buffer = whole_lines
+ prompt, prompt_width, prompt_list = check_multiline_prompt(new_buffer, prompt)
+ new_buffer.each_with_index do |line, index|
+ prompt_width = calculate_width(prompt_list[index], true) if @prompt_proc
+ width = prompt_width + calculate_width(line)
+ height = calculate_height_by_width(width)
+ back += height
+ end
+ @highest_in_all = back
+ @highest_in_this = calculate_height_by_width(prompt_width + @cursor_max)
+ @first_line_started_from =
+ if @line_index.zero?
+ 0
+ else
+ calculate_height_by_lines(@buffer_of_lines[0..(@line_index - 1)], prompt_list || prompt)
end
- calculate_nearest_cursor
- @started_from = calculate_height_by_width(prompt_width + @cursor) - 1
- Reline::IOGate.move_cursor_column((prompt_width + @cursor) % @screen_size.last)
- @highest_in_this = calculate_height_by_width(prompt_width + @cursor_max)
- @rerender_all = true
+ if @prompt_proc
+ prompt = prompt_list[@line_index]
+ prompt_width = calculate_width(prompt, true)
end
+ calculate_nearest_cursor
+ @started_from = calculate_height_by_width(prompt_width + @cursor) - 1
+ Reline::IOGate.move_cursor_column((prompt_width + @cursor) % @screen_size.last)
+ @highest_in_this = calculate_height_by_width(prompt_width + @cursor_max)
+ @rerender_all = true
end
- @block_elem_width = Reline::Unicode.calculate_width('█')
end
def finalize
@@ -264,6 +291,7 @@ class Reline::LineEditor
@auto_indent_proc = nil
@dialogs = []
@last_key = nil
+ @resized = false
reset_line
end
@@ -568,6 +596,7 @@ class Reline::LineEditor
@proc_scope = proc_scope
@width = nil
@scroll_top = 0
+ @trap_key = nil
end
def set_cursor_pos(col, row)
@@ -609,7 +638,7 @@ class Reline::LineEditor
@dialogs << Dialog.new(name, @config, DialogProcScope.new(self, @config, p, context))
end
- DIALOG_HEIGHT = 20
+ DIALOG_DEFAULT_HEIGHT = 20
private def render_dialog(cursor_column)
@dialogs.each do |dialog|
render_each_dialog(dialog, cursor_column)
@@ -649,7 +678,7 @@ class Reline::LineEditor
else
dialog.width = dialog.contents.map { |l| calculate_width(l, true) }.max
end
- height = dialog_render_info.height || DIALOG_HEIGHT
+ height = dialog_render_info.height || DIALOG_DEFAULT_HEIGHT
height = dialog.contents.size if dialog.contents.size < height
if dialog.contents.size > height
if dialog.pointer
@@ -664,6 +693,9 @@ class Reline::LineEditor
end
dialog.contents = dialog.contents[dialog.scroll_top, height]
end
+ if dialog.contents and dialog.scroll_top >= dialog.contents.size
+ dialog.scroll_top = dialog.contents.size - height
+ end
if dialog_render_info.scrollbar and dialog_render_info.contents.size > height
bar_max_height = height * 2
moving_distance = (dialog_render_info.contents.size - height) * 2
@@ -676,7 +708,8 @@ class Reline::LineEditor
upper_space = @first_line_started_from - @started_from
lower_space = @highest_in_all - @first_line_started_from - @started_from - 1
dialog.column = dialog_render_info.pos.x
- diff = (dialog.column + dialog.width) - (@screen_size.last - 1)
+ dialog.width += @block_elem_width if dialog.scrollbar_pos
+ diff = (dialog.column + dialog.width) - (@screen_size.last)
if diff > 0
dialog.column -= diff
end
@@ -692,7 +725,10 @@ class Reline::LineEditor
dialog.vertical_offset = dialog_render_info.pos.y + 1
end
Reline::IOGate.hide_cursor
- dialog.width += @block_elem_width if dialog.scrollbar_pos
+ if dialog.column < 0
+ dialog.column = 0
+ dialog.width = @screen_size.last
+ end
reset_dialog(dialog, old_dialog)
move_cursor_down(dialog.vertical_offset)
Reline::IOGate.move_cursor_column(dialog.column)
@@ -711,13 +747,13 @@ class Reline::LineEditor
@output.write "\e[#{bg_color}m#{str}"
if dialog.scrollbar_pos and (dialog.scrollbar_pos != old_dialog.scrollbar_pos or dialog.column != old_dialog.column)
@output.write "\e[37m"
- if dialog.scrollbar_pos <= (i * 2) and (i * 2 + @block_elem_width) < (dialog.scrollbar_pos + bar_height)
- @output.write '█'
+ if dialog.scrollbar_pos <= (i * 2) and (i * 2 + 1) < (dialog.scrollbar_pos + bar_height)
+ @output.write @full_block
elsif dialog.scrollbar_pos <= (i * 2) and (i * 2) < (dialog.scrollbar_pos + bar_height)
- @output.write '▀'
+ @output.write @upper_half_block
str += ''
- elsif dialog.scrollbar_pos <= (i * 2 + @block_elem_width) and (i * 2) < (dialog.scrollbar_pos + bar_height)
- @output.write '▄'
+ elsif dialog.scrollbar_pos <= (i * 2 + 1) and (i * 2) < (dialog.scrollbar_pos + bar_height)
+ @output.write @lower_half_block
else
@output.write ' ' * @block_elem_width
end
@@ -822,7 +858,8 @@ class Reline::LineEditor
s = ' ' * width
else
s = Reline::Unicode.take_range(visual_lines[start + i], old_dialog.column + dialog.width, width)
- s = padding_space_with_escape_sequences(s, dialog.width)
+ rerender_width = old_dialog.width - dialog.width
+ s = padding_space_with_escape_sequences(s, rerender_width)
end
Reline::IOGate.move_cursor_column(dialog.column + dialog.width)
@output.write "\e[0m#{s}\e[0m"
@@ -1401,7 +1438,10 @@ class Reline::LineEditor
end
@waiting_operator_proc = nil
@waiting_operator_vi_arg = nil
- @vi_arg = nil
+ if @vi_arg
+ @rerender_all = true
+ @vi_arg = nil
+ end
else
block.(false)
end
@@ -1452,7 +1492,10 @@ class Reline::LineEditor
wrap_method_call(method_symbol, method_obj, key) if method_obj
end
@kill_ring.process
- @vi_arg = nil
+ if @vi_arg
+ @rerender_al = true
+ @vi_arg = nil
+ end
elsif @vi_arg
if key.chr =~ /[0-9]/
ed_argument_digit(key)
@@ -1469,7 +1512,10 @@ class Reline::LineEditor
ed_insert(key) unless @config.editing_mode_is?(:vi_command)
end
@kill_ring.process
- @vi_arg = nil
+ if @vi_arg
+ @rerender_all = true
+ @vi_arg = nil
+ end
end
elsif @waiting_proc
@waiting_proc.(key)
@@ -1908,6 +1954,8 @@ class Reline::LineEditor
end
end
+ # Editline:: +ed-unassigned+ This editor command always results in an error.
+ # GNU Readline:: There is no corresponding macro.
private def ed_unassigned(key) end # do nothing
private def process_insert(force: false)
@@ -1925,6 +1973,19 @@ class Reline::LineEditor
@continuous_insertion_buffer.clear
end
+ # Editline:: +ed-insert+ (vi input: almost all; emacs: printable characters)
+ # In insert mode, insert the input character left of the cursor
+ # position. In replace mode, overwrite the character at the
+ # cursor and move the cursor to the right by one character
+ # position. Accept an argument to do this repeatedly. It is an
+ # error if the input character is the NUL character (+Ctrl-@+).
+ # Failure to enlarge the edit buffer also results in an error.
+ # Editline:: +ed-digit+ (emacs: 0 to 9) If in argument input mode, append
+ # the input digit to the argument being read. Otherwise, call
+ # +ed-insert+. It is an error if the input character is not a
+ # digit or if the existing argument is already greater than a
+ # million.
+ # GNU Readline:: +self-insert+ (a, b, A, 1, !, …) Insert yourself.
private def ed_insert(key)
str = nil
width = nil
@@ -2494,7 +2555,7 @@ class Reline::LineEditor
end
end
- private def em_delete_prev_char(key)
+ private def em_delete_prev_char(key, arg: 1)
if @is_multiline and @cursor == 0 and @line_index > 0
@buffer_of_lines[@line_index] = @line
@cursor = calculate_width(@buffer_of_lines[@line_index - 1])
@@ -2512,6 +2573,8 @@ class Reline::LineEditor
@cursor -= width
@cursor_max -= width
end
+ arg -= 1
+ em_delete_prev_char(key, arg: arg) if arg > 0
end
alias_method :backward_delete_char, :em_delete_prev_char
@@ -3048,7 +3111,14 @@ class Reline::LineEditor
private def ed_argument_digit(key)
if @vi_arg.nil?
- unless key.chr.to_i.zero?
+ if key.chr.to_i.zero?
+ if key.anybits?(0b10000000)
+ unescaped_key = key ^ 0b10000000
+ unless unescaped_key.chr.to_i.zero?
+ @vi_arg = unescaped_key.chr.to_i
+ end
+ end
+ else
@vi_arg = key.chr.to_i
end
else
diff --git a/lib/reline/terminfo.rb b/lib/reline/terminfo.rb
index 3f32a5aab0e..b4d1d735f84 100644
--- a/lib/reline/terminfo.rb
+++ b/lib/reline/terminfo.rb
@@ -1,5 +1,13 @@
-require 'fiddle'
-require 'fiddle/import'
+begin
+ require 'fiddle'
+ require 'fiddle/import'
+rescue LoadError
+ module Reline::Terminfo
+ def self.curses_dl
+ false
+ end
+ end
+end
module Reline::Terminfo
extend Fiddle::Importer
@@ -50,7 +58,7 @@ module Reline::Terminfo
@curses_dl = nil if @curses_dl == false
@curses_dl
end
-end
+end if not Reline.const_defined?(:Terminfo) or not Reline::Terminfo.respond_to?(:curses_dl)
module Reline::Terminfo
dlload curses_dl
diff --git a/lib/reline/version.rb b/lib/reline/version.rb
index 1c8ef4ce895..8425d5e14af 100644
--- a/lib/reline/version.rb
+++ b/lib/reline/version.rb
@@ -1,3 +1,3 @@
module Reline
- VERSION = '0.2.8.pre.9'
+ VERSION = '0.2.8.pre.11'
end
diff --git a/lib/reline/windows.rb b/lib/reline/windows.rb
index 5bbf1e9d570..73653b2de2c 100644
--- a/lib/reline/windows.rb
+++ b/lib/reline/windows.rb
@@ -233,23 +233,24 @@ class Reline::Windows
def self.check_input_event
num_of_events = 0.chr * 8
- while @@output_buf.empty? #or true
+ while @@output_buf.empty?
+ Reline.core.line_editor.resize
next if @@WaitForSingleObject.(@@hConsoleInputHandle, 100) != 0 # max 0.1 sec
- next if @@GetNumberOfConsoleInputEvents.(@@hConsoleInputHandle, num_of_events) == 0 or num_of_events.unpack('L').first == 0
+ next if @@GetNumberOfConsoleInputEvents.(@@hConsoleInputHandle, num_of_events) == 0 or num_of_events.unpack1('L') == 0
input_record = 0.chr * 18
read_event = 0.chr * 4
if @@ReadConsoleInputW.(@@hConsoleInputHandle, input_record, 1, read_event) != 0
- event = input_record[0, 2].unpack('s*').first
+ event = input_record[0, 2].unpack1('s*')
case event
when WINDOW_BUFFER_SIZE_EVENT
@@winch_handler.()
when KEY_EVENT
- key_down = input_record[4, 4].unpack('l*').first
- repeat_count = input_record[8, 2].unpack('s*').first
- virtual_key_code = input_record[10, 2].unpack('s*').first
- virtual_scan_code = input_record[12, 2].unpack('s*').first
- char_code = input_record[14, 2].unpack('S*').first
- control_key_state = input_record[16, 2].unpack('S*').first
+ key_down = input_record[4, 4].unpack1('l*')
+ repeat_count = input_record[8, 2].unpack1('s*')
+ virtual_key_code = input_record[10, 2].unpack1('s*')
+ virtual_scan_code = input_record[12, 2].unpack1('s*')
+ char_code = input_record[14, 2].unpack1('S*')
+ control_key_state = input_record[16, 2].unpack1('S*')
is_key_down = key_down.zero? ? false : true
if is_key_down
process_key_event(repeat_count, virtual_key_code, virtual_scan_code, char_code, control_key_state)
@@ -282,17 +283,25 @@ class Reline::Windows
end
end
- def self.get_screen_size
+ def self.get_console_screen_buffer_info
csbi = 0.chr * 22
- @@GetConsoleScreenBufferInfo.call(@@hConsoleHandle, csbi)
+ return if @@GetConsoleScreenBufferInfo.call(@@hConsoleHandle, csbi) == 0
+ csbi
+ end
+
+ def self.get_screen_size
+ unless csbi = get_console_screen_buffer_info
+ return [1, 1]
+ end
csbi[0, 4].unpack('SS').reverse
end
def self.cursor_pos
- csbi = 0.chr * 22
- @@GetConsoleScreenBufferInfo.call(@@hConsoleHandle, csbi)
- x = csbi[4, 2].unpack('s*').first
- y = csbi[6, 2].unpack('s*').first
+ unless csbi = get_console_screen_buffer_info
+ return Reline::CursorPos.new(0, 0)
+ end
+ x = csbi[4, 2].unpack1('s*')
+ y = csbi[6, 2].unpack1('s*')
Reline::CursorPos.new(x, y)
end
@@ -312,6 +321,7 @@ class Reline::Windows
def self.move_cursor_down(val)
if val > 0
+ return unless csbi = get_console_screen_buffer_info
screen_height = get_screen_size.first
y = cursor_pos.y + val
y = screen_height - 1 if y > (screen_height - 1)
@@ -322,12 +332,12 @@ class Reline::Windows
end
def self.erase_after_cursor
- csbi = 0.chr * 24
- @@GetConsoleScreenBufferInfo.call(@@hConsoleHandle, csbi)
- cursor = csbi[4, 4].unpack('L').first
+ return unless csbi = get_console_screen_buffer_info
+ attributes = csbi[8, 2].unpack1('S')
+ cursor = csbi[4, 4].unpack1('L')
written = 0.chr * 4
@@FillConsoleOutputCharacter.call(@@hConsoleHandle, 0x20, get_screen_size.last - cursor_pos.x, cursor, written)
- @@FillConsoleOutputAttribute.call(@@hConsoleHandle, 0, get_screen_size.last - cursor_pos.x, cursor, written)
+ @@FillConsoleOutputAttribute.call(@@hConsoleHandle, attributes, get_screen_size.last - cursor_pos.x, cursor, written)
end
def self.scroll_down(val)
@@ -341,10 +351,9 @@ class Reline::Windows
end
def self.clear_screen
- csbi = 0.chr * 22
- return if @@GetConsoleScreenBufferInfo.call(@@hConsoleHandle, csbi) == 0
- buffer_width = csbi[0, 2].unpack('S').first
- attributes = csbi[8, 2].unpack('S').first
+ return unless csbi = get_console_screen_buffer_info
+ buffer_width = csbi[0, 2].unpack1('S')
+ attributes = csbi[8, 2].unpack1('S')
_window_left, window_top, _window_right, window_bottom = *csbi[10,8].unpack('S*')
fill_length = buffer_width * (window_bottom - window_top + 1)
screen_topleft = window_top * 65536
diff --git a/lib/rinda/rinda.gemspec b/lib/rinda/rinda.gemspec
index 1cc5a453d8f..0c13e3c2df1 100644
--- a/lib/rinda/rinda.gemspec
+++ b/lib/rinda/rinda.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |spec|
spec.name = "rinda"
- spec.version = "0.1.0"
+ spec.version = "0.1.1"
spec.authors = ["Masatoshi SEKI"]
spec.email = ["seki@ruby-lang.org"]
diff --git a/lib/rubygems.rb b/lib/rubygems.rb
index 80708e2aa00..8e050ef3c77 100644
--- a/lib/rubygems.rb
+++ b/lib/rubygems.rb
@@ -800,11 +800,11 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
##
# Safely write a file in binary mode on all platforms.
def self.write_binary(path, data)
+ File.open(path, File::RDWR | File::CREAT | File::BINARY | File::LOCK_EX) do |io|
+ io.write data
+ end
+ rescue *WRITE_BINARY_ERRORS
File.open(path, 'wb') do |io|
- begin
- io.flock(File::LOCK_EX)
- rescue *WRITE_BINARY_ERRORS
- end
io.write data
end
rescue Errno::ENOLCK # NFS
@@ -1327,22 +1327,6 @@ require_relative 'rubygems/exceptions'
# REFACTOR: This should be pulled out into some kind of hacks file.
begin
##
- # Defaults the operating system (or packager) wants to provide for RubyGems.
-
- require 'rubygems/defaults/operating_system'
-rescue LoadError
- # Ignored
-rescue StandardError => e
- msg = "#{e.message}\n" \
- "Loading the rubygems/defaults/operating_system.rb file caused an error. " \
- "This file is owned by your OS, not by rubygems upstream. " \
- "Please find out which OS package this file belongs to and follow the guidelines from your OS to report " \
- "the problem and ask for help."
- raise e.class, msg
-end
-
-begin
- ##
# Defaults the Ruby implementation wants to provide for RubyGems
require "rubygems/defaults/#{RUBY_ENGINE}"
@@ -1356,3 +1340,19 @@ Gem::Specification.load_defaults
require_relative 'rubygems/core_ext/kernel_gem'
require_relative 'rubygems/core_ext/kernel_require'
require_relative 'rubygems/core_ext/kernel_warn'
+
+begin
+ ##
+ # Defaults the operating system (or packager) wants to provide for RubyGems.
+
+ require 'rubygems/defaults/operating_system'
+rescue LoadError
+ # Ignored
+rescue StandardError => e
+ msg = "#{e.message}\n" \
+ "Loading the rubygems/defaults/operating_system.rb file caused an error. " \
+ "This file is owned by your OS, not by rubygems upstream. " \
+ "Please find out which OS package this file belongs to and follow the guidelines from your OS to report " \
+ "the problem and ask for help."
+ raise e.class, msg
+end
diff --git a/lib/rubygems/command.rb b/lib/rubygems/command.rb
index 303f54a7d79..abdaa8e7c60 100644
--- a/lib/rubygems/command.rb
+++ b/lib/rubygems/command.rb
@@ -5,7 +5,7 @@
# See LICENSE.txt for permissions.
#++
-require 'optparse'
+require_relative 'optparse'
require_relative 'requirement'
require_relative 'user_interaction'
@@ -19,7 +19,7 @@ require_relative 'user_interaction'
class Gem::Command
include Gem::UserInteraction
- OptionParser.accept Symbol do |value|
+ Gem::OptionParser.accept Symbol do |value|
value.to_sym
end
@@ -344,7 +344,7 @@ class Gem::Command
##
# Add a command-line option and handler to the command.
#
- # See OptionParser#make_switch for an explanation of +opts+.
+ # See Gem::OptionParser#make_switch for an explanation of +opts+.
#
# +handler+ will be called with two values, the value of the argument and
# the options hash.
@@ -540,7 +540,7 @@ class Gem::Command
# command.
def create_option_parser
- @parser = OptionParser.new
+ @parser = Gem::OptionParser.new
add_parser_options
diff --git a/lib/rubygems/command_manager.rb b/lib/rubygems/command_manager.rb
index 39bf8bd30d1..03cdd6a4bb9 100644
--- a/lib/rubygems/command_manager.rb
+++ b/lib/rubygems/command_manager.rb
@@ -73,7 +73,9 @@ class Gem::CommandManager
].freeze
ALIAS_COMMANDS = {
- 'i' => 'install',
+ 'i' => 'install',
+ 'login' => 'signin',
+ 'logout' => 'signout',
}.freeze
##
diff --git a/lib/rubygems/commands/cert_command.rb b/lib/rubygems/commands/cert_command.rb
index bdfeb0ba6e8..b59564d5759 100644
--- a/lib/rubygems/commands/cert_command.rb
+++ b/lib/rubygems/commands/cert_command.rb
@@ -43,10 +43,15 @@ class Gem::Commands::CertCommand < Gem::Command
options[:key] = open_private_key(key_file)
end
+ add_option('-A', '--key-algorithm ALGORITHM',
+ 'Select which key algorithm to use for --build') do |algorithm, options|
+ options[:key_algorithm] = algorithm
+ end
+
add_option('-s', '--sign CERT',
'Signs CERT with the key from -K',
'and the certificate from -C') do |cert_file, options|
- raise OptionParser::InvalidArgument, "#{cert_file}: does not exist" unless
+ raise Gem::OptionParser::InvalidArgument, "#{cert_file}: does not exist" unless
File.file? cert_file
options[:sign] << cert_file
@@ -80,23 +85,23 @@ class Gem::Commands::CertCommand < Gem::Command
check_openssl
OpenSSL::X509::Certificate.new File.read certificate_file
rescue Errno::ENOENT
- raise OptionParser::InvalidArgument, "#{certificate_file}: does not exist"
+ raise Gem::OptionParser::InvalidArgument, "#{certificate_file}: does not exist"
rescue OpenSSL::X509::CertificateError
- raise OptionParser::InvalidArgument,
+ raise Gem::OptionParser::InvalidArgument,
"#{certificate_file}: invalid X509 certificate"
end
def open_private_key(key_file)
check_openssl
passphrase = ENV['GEM_PRIVATE_KEY_PASSPHRASE']
- key = OpenSSL::PKey::RSA.new File.read(key_file), passphrase
- raise OptionParser::InvalidArgument,
+ key = OpenSSL::PKey.read File.read(key_file), passphrase
+ raise Gem::OptionParser::InvalidArgument,
"#{key_file}: private key not found" unless key.private?
key
rescue Errno::ENOENT
- raise OptionParser::InvalidArgument, "#{key_file}: does not exist"
- rescue OpenSSL::PKey::RSAError
- raise OptionParser::InvalidArgument, "#{key_file}: invalid RSA key"
+ raise Gem::OptionParser::InvalidArgument, "#{key_file}: does not exist"
+ rescue OpenSSL::PKey::PKeyError, ArgumentError
+ raise Gem::OptionParser::InvalidArgument, "#{key_file}: invalid RSA, DSA, or EC key"
end
def execute
@@ -170,7 +175,8 @@ class Gem::Commands::CertCommand < Gem::Command
raise Gem::CommandLineError,
"Passphrase and passphrase confirmation don't match" unless passphrase == passphrase_confirmation
- key = Gem::Security.create_key
+ algorithm = options[:key_algorithm] || Gem::Security::DEFAULT_KEY_ALGORITHM
+ key = Gem::Security.create_key(algorithm)
key_path = Gem::Security.write key, "gem-private_key.pem", 0600, passphrase
return key, key_path
@@ -255,13 +261,14 @@ For further reading on signing gems see `ri Gem::Security`.
key_file = File.join Gem.default_key_path
key = File.read key_file
passphrase = ENV['GEM_PRIVATE_KEY_PASSPHRASE']
- options[:key] = OpenSSL::PKey::RSA.new key, passphrase
+ options[:key] = OpenSSL::PKey.read key, passphrase
+
rescue Errno::ENOENT
alert_error \
"--private-key not specified and ~/.gem/gem-private_key.pem does not exist"
terminate_interaction 1
- rescue OpenSSL::PKey::RSAError
+ rescue OpenSSL::PKey::PKeyError
alert_error \
"--private-key not specified and ~/.gem/gem-private_key.pem is not valid"
diff --git a/lib/rubygems/commands/fetch_command.rb b/lib/rubygems/commands/fetch_command.rb
index 619f56a5da6..373851643d4 100644
--- a/lib/rubygems/commands/fetch_command.rb
+++ b/lib/rubygems/commands/fetch_command.rb
@@ -60,7 +60,7 @@ then repackaging it.
specs_and_sources = filtered unless filtered.empty?
end
- spec, source = specs_and_sources.max_by {|s,| s.version }
+ spec, source = specs_and_sources.max_by {|s,| s }
if spec.nil?
show_lookup_failure gem_name, version, errors, options[:domain]
diff --git a/lib/rubygems/commands/pristine_command.rb b/lib/rubygems/commands/pristine_command.rb
index 41547ce73bf..13979b0a590 100644
--- a/lib/rubygems/commands/pristine_command.rb
+++ b/lib/rubygems/commands/pristine_command.rb
@@ -50,6 +50,11 @@ class Gem::Commands::PristineCommand < Gem::Command
options[:env_shebang] = value
end
+ add_option('-i', '--install-dir DIR',
+ 'Gem repository to get binstubs and plugins installed') do |value, options|
+ options[:install_dir] = File.expand_path(value)
+ end
+
add_option('-n', '--bindir DIR',
'Directory where executables are',
'located') do |value, options|
@@ -163,11 +168,12 @@ extensions will be restored.
end
bin_dir = options[:bin_dir] if options[:bin_dir]
+ install_dir = options[:install_dir] if options[:install_dir]
installer_options = {
:wrappers => true,
:force => true,
- :install_dir => spec.base_dir,
+ :install_dir => install_dir || spec.base_dir,
:env_shebang => env_shebang,
:build_args => spec.build_args,
:bin_dir => bin_dir,
@@ -177,7 +183,7 @@ extensions will be restored.
installer = Gem::Installer.for_spec(spec, installer_options)
installer.generate_bin
elsif options[:only_plugins]
- installer = Gem::Installer.for_spec(spec)
+ installer = Gem::Installer.for_spec(spec, installer_options)
installer.generate_plugins
else
installer = Gem::Installer.at(gem, installer_options)
diff --git a/lib/rubygems/commands/server_command.rb b/lib/rubygems/commands/server_command.rb
index f3c08efb5eb..f8cad3b5db7 100644
--- a/lib/rubygems/commands/server_command.rb
+++ b/lib/rubygems/commands/server_command.rb
@@ -1,88 +1,25 @@
# frozen_string_literal: true
require_relative '../command'
-require_relative '../server'
-require_relative '../deprecate'
-class Gem::Commands::ServerCommand < Gem::Command
- extend Gem::Deprecate
- rubygems_deprecate_command
-
- def initialize
- super 'server', 'Documentation and gem repository HTTP server',
- :port => 8808, :gemdir => [], :daemon => false
-
- OptionParser.accept :Port do |port|
- if port =~ /\A\d+\z/
- port = Integer port
- raise OptionParser::InvalidArgument, "#{port}: not a port number" if
- port > 65535
-
- port
- else
- begin
- Socket.getservbyname port
- rescue SocketError
- raise OptionParser::InvalidArgument, "#{port}: no such named service"
- end
+unless defined? Gem::Commands::ServerCommand
+ class Gem::Commands::ServerCommand < Gem::Command
+ def initialize
+ super('server', 'Starts up a web server that hosts the RDoc (requires rubygems-server)')
+ begin
+ Gem::Specification.find_by_name('rubygems-server').activate
+ rescue Gem::LoadError
+ # no-op
end
end
- add_option '-p', '--port=PORT', :Port,
- 'port to listen on' do |port, options|
- options[:port] = port
- end
-
- add_option '-d', '--dir=GEMDIR',
- 'directories from which to serve gems',
- 'multiple directories may be provided' do |gemdir, options|
- options[:gemdir] << File.expand_path(gemdir)
+ def description # :nodoc:
+ <<-EOF
+The server command has been moved to the rubygems-server gem.
+ EOF
end
- add_option '--[no-]daemon', 'run as a daemon' do |daemon, options|
- options[:daemon] = daemon
+ def execute
+ alert_error "Install the rubygems-server gem for the server command"
end
-
- add_option '-b', '--bind=HOST,HOST',
- 'addresses to bind', Array do |address, options|
- options[:addresses] ||= []
- options[:addresses].push(*address)
- end
-
- add_option '-l', '--launch[=COMMAND]',
- 'launches a browser window',
- "COMMAND defaults to 'start' on Windows",
- "and 'open' on all other platforms" do |launch, options|
- launch ||= Gem.win_platform? ? 'start' : 'open'
- options[:launch] = launch
- end
- end
-
- def defaults_str # :nodoc:
- "--port 8808 --dir #{Gem.dir} --no-daemon"
- end
-
- def description # :nodoc:
- <<-EOF
-The server command starts up a web server that hosts the RDoc for your
-installed gems and can operate as a server for installation of gems on other
-machines.
-
-The cache files for installed gems must exist to use the server as a source
-for gem installation.
-
-To install gems from a running server, use `gem install GEMNAME --source
-http://gem_server_host:8808`
-
-You can set up a shortcut to gem server documentation using the URL:
-
- http://localhost:8808/rdoc?q=%s - Firefox
- http://localhost:8808/rdoc?q=* - LaunchBar
-
- EOF
- end
-
- def execute
- options[:gemdir] = Gem.path if options[:gemdir].empty?
- Gem::Server.run options
end
end
diff --git a/lib/rubygems/commands/setup_command.rb b/lib/rubygems/commands/setup_command.rb
index edb3498eec1..ed1fcaa4b89 100644
--- a/lib/rubygems/commands/setup_command.rb
+++ b/lib/rubygems/commands/setup_command.rb
@@ -149,13 +149,6 @@ By default, this RubyGems will install gem as:
def execute
@verbose = Gem.configuration.really_verbose
- install_destdir = options[:destdir]
-
- unless install_destdir.empty?
- ENV['GEM_HOME'] ||= File.join(install_destdir,
- Gem.default_dir.gsub(/^[a-zA-Z]:/, ''))
- end
-
check_ruby_version
require 'fileutils'
@@ -166,8 +159,8 @@ By default, this RubyGems will install gem as:
end
extend MakeDirs
- lib_dir, bin_dir = make_destination_dirs install_destdir
- man_dir = generate_default_man_dir install_destdir
+ lib_dir, bin_dir = make_destination_dirs
+ man_dir = generate_default_man_dir
install_lib lib_dir
@@ -189,8 +182,8 @@ By default, this RubyGems will install gem as:
say "RubyGems #{Gem::VERSION} installed"
- regenerate_binstubs if options[:regenerate_binstubs]
- regenerate_plugins if options[:regenerate_plugins]
+ regenerate_binstubs(bin_dir) if options[:regenerate_binstubs]
+ regenerate_plugins(bin_dir) if options[:regenerate_plugins]
uninstall_old_gemcutter
@@ -258,35 +251,32 @@ By default, this RubyGems will install gem as:
say "Installing #{tool} executable" if @verbose
Dir.chdir path do
- bin_files = Dir['*']
-
- bin_files -= %w[update_rubygems]
+ bin_file = "gem"
- bin_files.each do |bin_file|
- dest_file = target_bin_path(bin_dir, bin_file)
- bin_tmp_file = File.join Dir.tmpdir, "#{bin_file}.#{$$}"
+ dest_file = target_bin_path(bin_dir, bin_file)
+ bin_tmp_file = File.join Dir.tmpdir, "#{bin_file}.#{$$}"
- begin
- bin = File.readlines bin_file
- bin[0] = shebang
+ begin
+ bin = File.readlines bin_file
+ bin[0] = shebang
- File.open bin_tmp_file, 'w' do |fp|
- fp.puts bin.join
- end
-
- install bin_tmp_file, dest_file, :mode => prog_mode
- bin_file_names << dest_file
- ensure
- rm bin_tmp_file
+ File.open bin_tmp_file, 'w' do |fp|
+ fp.puts bin.join
end
- next unless Gem.win_platform?
+ install bin_tmp_file, dest_file, :mode => prog_mode
+ bin_file_names << dest_file
+ ensure
+ rm bin_tmp_file
+ end
+
+ next unless Gem.win_platform?
- begin
- bin_cmd_file = File.join Dir.tmpdir, "#{bin_file}.bat"
+ begin
+ bin_cmd_file = File.join Dir.tmpdir, "#{bin_file}.bat"
- File.open bin_cmd_file, 'w' do |file|
- file.puts <<-TEXT
+ File.open bin_cmd_file, 'w' do |file|
+ file.puts <<-TEXT
@ECHO OFF
IF NOT "%~f0" == "~f0" GOTO :WinNT
@"#{File.basename(Gem.ruby).chomp('"')}" "#{dest_file}" %1 %2 %3 %4 %5 %6 %7 %8 %9
@@ -294,12 +284,11 @@ By default, this RubyGems will install gem as:
:WinNT
@"#{File.basename(Gem.ruby).chomp('"')}" "%~dpn0" %*
TEXT
- end
-
- install bin_cmd_file, "#{dest_file}.bat", :mode => prog_mode
- ensure
- rm bin_cmd_file
end
+
+ install bin_cmd_file, "#{dest_file}.bat", :mode => prog_mode
+ ensure
+ rm bin_cmd_file
end
end
end
@@ -371,8 +360,7 @@ By default, this RubyGems will install gem as:
end
def install_default_bundler_gem(bin_dir)
- specs_dir = Gem.default_specifications_dir
- specs_dir = File.join(options[:destdir], specs_dir) unless Gem.win_platform?
+ specs_dir = File.join(default_dir, "specifications", "default")
mkdir_p specs_dir, :mode => 0755
bundler_spec = Dir.chdir("bundler") { Gem::Specification.load("bundler.gemspec") }
@@ -387,8 +375,20 @@ By default, this RubyGems will install gem as:
bundler_spec = Gem::Specification.load(default_spec_path)
+ # The base_dir value for a specification is inferred by walking up from the
+ # folder where the spec was `loaded_from`. In the case of default gems, we
+ # walk up two levels, because they live at `specifications/default/`, whereas
+ # in the case of regular gems we walk up just one level because they live at
+ # `specifications/`. However, in this case, the gem we are installing is
+ # misdetected as a regular gem, when it's a default gem in reality. This is
+ # because when there's a `:destdir`, the `loaded_from` path has changed and
+ # doesn't match `Gem.default_specifications_dir` which is the criteria to
+ # tag a gem as a default gem. So, in that case, write the correct
+ # `@base_dir` directly.
+ bundler_spec.instance_variable_set(:@base_dir, File.dirname(File.dirname(specs_dir)))
+
# Remove gemspec that was same version of vendored bundler.
- normal_gemspec = File.join(Gem.default_dir, "specifications", "bundler-#{bundler_spec.version}.gemspec")
+ normal_gemspec = File.join(default_dir, "specifications", "bundler-#{bundler_spec.version}.gemspec")
if File.file? normal_gemspec
File.delete normal_gemspec
end
@@ -401,7 +401,6 @@ By default, this RubyGems will install gem as:
end
bundler_bin_dir = bundler_spec.bin_dir
- bundler_bin_dir = File.join(options[:destdir], bundler_bin_dir) unless Gem.win_platform?
mkdir_p bundler_bin_dir, :mode => 0755
bundler_spec.executables.each do |e|
cp File.join("bundler", bundler_spec.bindir, e), File.join(bundler_bin_dir, e)
@@ -412,8 +411,16 @@ By default, this RubyGems will install gem as:
Dir.chdir("bundler") do
built_gem = Gem::Package.build(bundler_spec)
begin
- installer = Gem::Installer.at(built_gem, env_shebang: options[:env_shebang], format_executable: options[:format_executable], force: options[:force], install_as_default: true, bin_dir: bin_dir, wrappers: true)
- installer.install
+ Gem::Installer.at(
+ built_gem,
+ env_shebang: options[:env_shebang],
+ format_executable: options[:format_executable],
+ force: options[:force],
+ install_as_default: true,
+ bin_dir: bin_dir,
+ install_dir: default_dir,
+ wrappers: true
+ ).install
ensure
FileUtils.rm_f built_gem
end
@@ -424,11 +431,11 @@ By default, this RubyGems will install gem as:
say "Bundler #{bundler_spec.version} installed"
end
- def make_destination_dirs(install_destdir)
+ def make_destination_dirs
lib_dir, bin_dir = Gem.default_rubygems_dirs
unless lib_dir
- lib_dir, bin_dir = generate_default_dirs(install_destdir)
+ lib_dir, bin_dir = generate_default_dirs
end
mkdir_p lib_dir, :mode => 0755
@@ -437,7 +444,7 @@ By default, this RubyGems will install gem as:
return lib_dir, bin_dir
end
- def generate_default_man_dir(install_destdir)
+ def generate_default_man_dir
prefix = options[:prefix]
if prefix.empty?
@@ -447,14 +454,10 @@ By default, this RubyGems will install gem as:
man_dir = File.join prefix, 'man'
end
- unless install_destdir.empty?
- man_dir = File.join install_destdir, man_dir.gsub(/^[a-zA-Z]:/, '')
- end
-
- man_dir
+ prepend_destdir_if_present(man_dir)
end
- def generate_default_dirs(install_destdir)
+ def generate_default_dirs
prefix = options[:prefix]
site_or_vendor = options[:site_or_vendor]
@@ -466,12 +469,7 @@ By default, this RubyGems will install gem as:
bin_dir = File.join prefix, 'bin'
end
- unless install_destdir.empty?
- lib_dir = File.join install_destdir, lib_dir.gsub(/^[a-zA-Z]:/, '')
- bin_dir = File.join install_destdir, bin_dir.gsub(/^[a-zA-Z]:/, '')
- end
-
- [lib_dir, bin_dir]
+ [prepend_destdir_if_present(lib_dir), prepend_destdir_if_present(bin_dir)]
end
def files_in(dir)
@@ -592,11 +590,12 @@ abort "#{deprecation_message}"
rescue Gem::InstallError
end
- def regenerate_binstubs
+ def regenerate_binstubs(bindir)
require_relative "pristine_command"
say "Regenerating binstubs"
args = %w[--all --only-executables --silent]
+ args << "--bindir=#{bindir}"
if options[:env_shebang]
args << "--env-shebang"
end
@@ -605,11 +604,13 @@ abort "#{deprecation_message}"
command.invoke(*args)
end
- def regenerate_plugins
- require "rubygems/commands/pristine_command"
+ def regenerate_plugins(bindir)
+ require_relative "pristine_command"
say "Regenerating plugins"
args = %w[--all --only-plugins --silent]
+ args << "--bindir=#{bindir}"
+ args << "--install-dir=#{default_dir}"
command = Gem::Commands::PristineCommand.new
command.invoke(*args)
@@ -617,6 +618,25 @@ abort "#{deprecation_message}"
private
+ def default_dir
+ prefix = options[:prefix]
+
+ if prefix.empty?
+ dir = Gem.default_dir
+ else
+ dir = prefix
+ end
+
+ prepend_destdir_if_present(dir)
+ end
+
+ def prepend_destdir_if_present(path)
+ destdir = options[:destdir]
+ return path if destdir.empty?
+
+ File.join(options[:destdir], path.gsub(/^[a-zA-Z]:/, ''))
+ end
+
def install_file_list(files, dest_dir)
files.each do |file|
install_file file, dest_dir
diff --git a/lib/rubygems/commands/uninstall_command.rb b/lib/rubygems/commands/uninstall_command.rb
index 20781b224d5..467c8bf7ed6 100644
--- a/lib/rubygems/commands/uninstall_command.rb
+++ b/lib/rubygems/commands/uninstall_command.rb
@@ -81,7 +81,7 @@ class Gem::Commands::UninstallCommand < Gem::Command
'Uninstall gem from the vendor directory.',
'Only for use by gem repackagers.') do |value, options|
unless Gem.vendor_dir
- raise OptionParser::InvalidOption.new 'your platform is not supported'
+ raise Gem::OptionParser::InvalidOption.new 'your platform is not supported'
end
alert_warning 'Use your OS package manager to uninstall vendor gems'
diff --git a/lib/rubygems/commands/update_command.rb b/lib/rubygems/commands/update_command.rb
index d104488c943..513351d303f 100644
--- a/lib/rubygems/commands/update_command.rb
+++ b/lib/rubygems/commands/update_command.rb
@@ -29,7 +29,7 @@ class Gem::Commands::UpdateCommand < Gem::Command
add_install_update_options
- OptionParser.accept Gem::Version do |value|
+ Gem::OptionParser.accept Gem::Version do |value|
Gem::Version.new value
value
diff --git a/lib/rubygems/defaults.rb b/lib/rubygems/defaults.rb
index f29104a1b76..39b69ddb1c6 100644
--- a/lib/rubygems/defaults.rb
+++ b/lib/rubygems/defaults.rb
@@ -59,7 +59,7 @@ module Gem
# Path to specification files of default gems.
def self.default_specifications_dir
- File.join(Gem.default_dir, "specifications", "default")
+ @default_specifications_dir ||= File.join(Gem.default_dir, "specifications", "default")
end
##
diff --git a/lib/rubygems/dependency_list.rb b/lib/rubygems/dependency_list.rb
index 8f61869874d..10e08fc703c 100644
--- a/lib/rubygems/dependency_list.rb
+++ b/lib/rubygems/dependency_list.rb
@@ -5,7 +5,7 @@
# See LICENSE.txt for permissions.
#++
-require 'tsort'
+require_relative 'tsort'
require_relative 'deprecate'
##
@@ -20,7 +20,7 @@ class Gem::DependencyList
attr_reader :specs
include Enumerable
- include TSort
+ include Gem::TSort
##
# Allows enabling/disabling use of development dependencies
diff --git a/lib/rubygems/exceptions.rb b/lib/rubygems/exceptions.rb
index f0debb646ff..20e4049e488 100644
--- a/lib/rubygems/exceptions.rb
+++ b/lib/rubygems/exceptions.rb
@@ -284,3 +284,4 @@ end
# Backwards compatible typo'd exception class for early RubyGems 2.0.x
Gem::UnsatisfiableDepedencyError = Gem::UnsatisfiableDependencyError # :nodoc:
+Gem.deprecate_constant :UnsatisfiableDepedencyError
diff --git a/lib/rubygems/ext/builder.rb b/lib/rubygems/ext/builder.rb
index 7934309901c..6d32be6515b 100644
--- a/lib/rubygems/ext/builder.rb
+++ b/lib/rubygems/ext/builder.rb
@@ -24,13 +24,14 @@ class Gem::Ext::Builder
# try to find make program from Ruby configure arguments first
RbConfig::CONFIG['configure_args'] =~ /with-make-prog\=(\w+)/
- make_program = ENV['MAKE'] || ENV['make'] || $1
- unless make_program
- make_program = (/mswin/ =~ RUBY_PLATFORM) ? 'nmake' : 'make'
+ make_program_name = ENV['MAKE'] || ENV['make'] || $1
+ unless make_program_name
+ make_program_name = (/mswin/ =~ RUBY_PLATFORM) ? 'nmake' : 'make'
end
- make_program = Shellwords.split(make_program)
+ make_program = Shellwords.split(make_program_name)
- destdir = 'DESTDIR=%s' % ENV['DESTDIR']
+ # The installation of the bundled gems is failed when DESTDIR is empty in mswin platform.
+ destdir = (/\bnmake/i !~ make_program_name || ENV['DESTDIR'] && ENV['DESTDIR'] != "") ? 'DESTDIR=%s' % ENV['DESTDIR'] : ''
['clean', '', 'install'].each do |target|
# Pass DESTDIR via command line to override what's in MAKEFLAGS
diff --git a/lib/rubygems/ext/cmake_builder.rb b/lib/rubygems/ext/cmake_builder.rb
index 269e876cfac..e47cabef842 100644
--- a/lib/rubygems/ext/cmake_builder.rb
+++ b/lib/rubygems/ext/cmake_builder.rb
@@ -1,9 +1,9 @@
# frozen_string_literal: true
-require_relative '../command'
class Gem::Ext::CmakeBuilder < Gem::Ext::Builder
def self.build(extension, dest_path, results, args=[], lib_dir=nil, cmake_dir=Dir.pwd)
unless File.exist?(File.join(cmake_dir, 'Makefile'))
+ require_relative '../command'
cmd = ["cmake", ".", "-DCMAKE_INSTALL_PREFIX=#{dest_path}", *Gem::Command.build_args]
run cmd, results, class_name, cmake_dir
diff --git a/lib/rubygems/install_update_options.rb b/lib/rubygems/install_update_options.rb
index cafa63544f9..2203b17f8e2 100644
--- a/lib/rubygems/install_update_options.rb
+++ b/lib/rubygems/install_update_options.rb
@@ -51,7 +51,7 @@ module Gem::InstallUpdateOptions
'Install gem into the vendor directory.',
'Only for use by gem repackagers.') do |value, options|
unless Gem.vendor_dir
- raise OptionParser::InvalidOption.new 'your platform is not supported'
+ raise Gem::OptionParser::InvalidOption.new 'your platform is not supported'
end
options[:vendor] = true
@@ -143,7 +143,7 @@ module Gem::InstallUpdateOptions
unless v
message = v ? v : "(tried #{Gem::GEM_DEP_FILES.join ', '})"
- raise OptionParser::InvalidArgument,
+ raise Gem::OptionParser::InvalidArgument,
"cannot find gem dependencies file #{message}"
end
diff --git a/lib/rubygems/installer.rb b/lib/rubygems/installer.rb
index cf5ed7b5024..8e3965ef92d 100644
--- a/lib/rubygems/installer.rb
+++ b/lib/rubygems/installer.rb
@@ -5,7 +5,6 @@
# See LICENSE.txt for permissions.
#++
-require_relative 'command'
require_relative 'installer_uninstaller_utils'
require_relative 'exceptions'
require_relative 'deprecate'
@@ -68,19 +67,28 @@ class Gem::Installer
@path_warning = false
- @install_lock = Thread::Mutex.new
-
class << self
- ##
- # True if we've warned about PATH not including Gem.bindir
+ #
+ # Changes in rubygems to lazily loading `rubygems/command` (in order to
+ # lazily load `optparse` as a side effect) affect bundler's custom installer
+ # which uses `Gem::Command` without requiring it (up until bundler 2.2.29).
+ # This hook is to compensate for that missing require.
+ #
+ # TODO: Remove when rubygems no longer supports running on bundler older
+ # than 2.2.29.
- attr_accessor :path_warning
+ def inherited(klass)
+ if klass.name == "Bundler::RubyGemsGemInstaller"
+ require "rubygems/command"
+ end
+
+ super(klass)
+ end
##
- # Certain aspects of the install process are not thread-safe. This lock is
- # used to allow multiple threads to install Gems at the same time.
+ # True if we've warned about PATH not including Gem.bindir
- attr_reader :install_lock
+ attr_accessor :path_warning
##
# Overrides the executable format.
@@ -285,8 +293,6 @@ class Gem::Installer
def install
pre_install_checks
- FileUtils.rm_f File.join gem_home, 'specifications', spec.spec_name
-
run_pre_install_hooks
# Set loaded_from to ensure extension_dir is correct
@@ -326,7 +332,7 @@ class Gem::Installer
say spec.post_install_message if options[:post_install_message] && !spec.post_install_message.nil?
- Gem::Installer.install_lock.synchronize { Gem::Specification.reset }
+ Gem::Specification.reset
run_post_install_hooks
@@ -440,13 +446,9 @@ class Gem::Installer
# specifications directory.
def write_spec
- File.open spec_file, 'w' do |file|
- spec.installed_by_version = Gem.rubygems_version
+ spec.installed_by_version = Gem.rubygems_version
- file.puts spec.to_ruby_for_cache
-
- file.fsync rescue nil # for filesystems without fsync(2)
- end
+ Gem.write_binary(spec_file, spec.to_ruby_for_cache)
end
##
@@ -454,9 +456,7 @@ class Gem::Installer
# specifications/default directory.
def write_default_spec
- File.open(default_spec_file, "w") do |file|
- file.puts spec.to_ruby
- end
+ Gem.write_binary(default_spec_file, spec.to_ruby)
end
##
@@ -511,7 +511,7 @@ class Gem::Installer
end
def generate_plugins # :nodoc:
- latest = Gem::Installer.install_lock.synchronize { Gem::Specification.latest_spec_for(spec.name) }
+ latest = Gem::Specification.latest_spec_for(spec.name)
return if latest && latest.version > spec.version
ensure_writable_dir @plugins_dir
@@ -676,7 +676,7 @@ class Gem::Installer
@development = options[:development]
@build_root = options[:build_root]
- @build_args = options[:build_args] || Gem::Command.build_args
+ @build_args = options[:build_args]
unless @build_root.nil?
@bin_dir = File.join(@build_root, @bin_dir.gsub(/^[a-zA-Z]:/, ''))
@@ -832,7 +832,7 @@ TEXT
# configure scripts and rakefiles or mkrf_conf files.
def build_extensions
- builder = Gem::Ext::Builder.new spec, @build_args
+ builder = Gem::Ext::Builder.new spec, build_args
builder.build_extensions
end
@@ -919,7 +919,7 @@ TEXT
# extensions.
def write_build_info_file
- return if @build_args.empty?
+ return if build_args.empty?
build_info_dir = File.join gem_home, 'build_info'
@@ -929,7 +929,7 @@ TEXT
build_info_file = File.join build_info_dir, "#{spec.full_name}.info"
File.open build_info_file, 'w' do |io|
- @build_args.each do |arg|
+ build_args.each do |arg|
io.puts arg
end
end
@@ -954,4 +954,13 @@ TEXT
raise Gem::FilePermissionError.new(dir) unless File.writable? dir
end
+
+ private
+
+ def build_args
+ @build_args ||= begin
+ require_relative "command"
+ Gem::Command.build_args
+ end
+ end
end
diff --git a/lib/rubygems/local_remote_options.rb b/lib/rubygems/local_remote_options.rb
index 8acd98d2e42..0b8b0ee1a60 100644
--- a/lib/rubygems/local_remote_options.rb
+++ b/lib/rubygems/local_remote_options.rb
@@ -14,14 +14,14 @@ require_relative '../rubygems'
module Gem::LocalRemoteOptions
##
- # Allows OptionParser to handle HTTP URIs.
+ # Allows Gem::OptionParser to handle HTTP URIs.
def accept_uri_http
- OptionParser.accept URI::HTTP do |value|
+ Gem::OptionParser.accept URI::HTTP do |value|
begin
uri = URI.parse value
rescue URI::InvalidURIError
- raise OptionParser::InvalidArgument, value
+ raise Gem::OptionParser::InvalidArgument, value
end
valid_uri_schemes = ["http", "https", "file", "s3"]
diff --git a/lib/rubygems/optparse.rb b/lib/rubygems/optparse.rb
new file mode 100644
index 00000000000..65be9f6b74b
--- /dev/null
+++ b/lib/rubygems/optparse.rb
@@ -0,0 +1,3 @@
+# frozen_string_literal: true
+
+require_relative 'optparse/lib/optparse'
diff --git a/lib/rubygems/optparse/.document b/lib/rubygems/optparse/.document
new file mode 100644
index 00000000000..0c43bbd6b38
--- /dev/null
+++ b/lib/rubygems/optparse/.document
@@ -0,0 +1 @@
+# Vendored files do not need to be documented
diff --git a/lib/rubygems/optparse/lib/optionparser.rb b/lib/rubygems/optparse/lib/optionparser.rb
new file mode 100644
index 00000000000..4b9b40d82a7
--- /dev/null
+++ b/lib/rubygems/optparse/lib/optionparser.rb
@@ -0,0 +1,2 @@
+# frozen_string_literal: false
+require_relative 'optparse'
diff --git a/lib/rubygems/optparse/lib/optparse.rb b/lib/rubygems/optparse/lib/optparse.rb
new file mode 100644
index 00000000000..e4b1c61f79d
--- /dev/null
+++ b/lib/rubygems/optparse/lib/optparse.rb
@@ -0,0 +1,2230 @@
+# frozen_string_literal: true
+#
+# optparse.rb - command-line option analysis with the Gem::OptionParser class.
+#
+# Author:: Nobu Nakada
+# Documentation:: Nobu Nakada and Gavin Sinclair.
+#
+# See Gem::OptionParser for documentation.
+#
+
+
+#--
+# == Developer Documentation (not for RDoc output)
+#
+# === Class tree
+#
+# - Gem::OptionParser:: front end
+# - Gem::OptionParser::Switch:: each switches
+# - Gem::OptionParser::List:: options list
+# - Gem::OptionParser::ParseError:: errors on parsing
+# - Gem::OptionParser::AmbiguousOption
+# - Gem::OptionParser::NeedlessArgument
+# - Gem::OptionParser::MissingArgument
+# - Gem::OptionParser::InvalidOption
+# - Gem::OptionParser::InvalidArgument
+# - Gem::OptionParser::AmbiguousArgument
+#
+# === Object relationship diagram
+#
+# +--------------+
+# | Gem::OptionParser |<>-----+
+# +--------------+ | +--------+
+# | ,-| Switch |
+# on_head -------->+---------------+ / +--------+
+# accept/reject -->| List |<|>-
+# | |<|>- +----------+
+# on ------------->+---------------+ `-| argument |
+# : : | class |
+# +---------------+ |==========|
+# on_tail -------->| | |pattern |
+# +---------------+ |----------|
+# Gem::OptionParser.accept ->| DefaultList | |converter |
+# reject |(shared between| +----------+
+# | all instances)|
+# +---------------+
+#
+#++
+#
+# == Gem::OptionParser
+#
+# === New to \Gem::OptionParser?
+#
+# See the {Tutorial}[./doc/optparse/tutorial_rdoc.html].
+#
+# === Introduction
+#
+# Gem::OptionParser is a class for command-line option analysis. It is much more
+# advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented
+# solution.
+#
+# === Features
+#
+# 1. The argument specification and the code to handle it are written in the
+# same place.
+# 2. It can output an option summary; you don't need to maintain this string
+# separately.
+# 3. Optional and mandatory arguments are specified very gracefully.
+# 4. Arguments can be automatically converted to a specified class.
+# 5. Arguments can be restricted to a certain set.
+#
+# All of these features are demonstrated in the examples below. See
+# #make_switch for full documentation.
+#
+# === Minimal example
+#
+# require 'rubygems/optparse/lib/optparse'
+#
+# options = {}
+# Gem::OptionParser.new do |parser|
+# parser.banner = "Usage: example.rb [options]"
+#
+# parser.on("-v", "--[no-]verbose", "Run verbosely") do |v|
+# options[:verbose] = v
+# end
+# end.parse!
+#
+# p options
+# p ARGV
+#
+# === Generating Help
+#
+# Gem::OptionParser can be used to automatically generate help for the commands you
+# write:
+#
+# require 'rubygems/optparse/lib/optparse'
+#
+# Options = Struct.new(:name)
+#
+# class Parser
+# def self.parse(options)
+# args = Options.new("world")
+#
+# opt_parser = Gem::OptionParser.new do |parser|
+# parser.banner = "Usage: example.rb [options]"
+#
+# parser.on("-nNAME", "--name=NAME", "Name to say hello to") do |n|
+# args.name = n
+# end
+#
+# parser.on("-h", "--help", "Prints this help") do
+# puts parser
+# exit
+# end
+# end
+#
+# opt_parser.parse!(options)
+# return args
+# end
+# end
+# options = Parser.parse %w[--help]
+#
+# #=>
+# # Usage: example.rb [options]
+# # -n, --name=NAME Name to say hello to
+# # -h, --help Prints this help
+#
+# === Required Arguments
+#
+# For options that require an argument, option specification strings may include an
+# option name in all caps. If an option is used without the required argument,
+# an exception will be raised.
+#
+# require 'rubygems/optparse/lib/optparse'
+#
+# options = {}
+# Gem::OptionParser.new do |parser|
+# parser.on("-r", "--require LIBRARY",
+# "Require the LIBRARY before executing your script") do |lib|
+# puts "You required #{lib}!"
+# end
+# end.parse!
+#
+# Used:
+#
+# $ ruby optparse-test.rb -r
+# optparse-test.rb:9:in `<main>': missing argument: -r (Gem::OptionParser::MissingArgument)
+# $ ruby optparse-test.rb -r my-library
+# You required my-library!
+#
+# === Type Coercion
+#
+# Gem::OptionParser supports the ability to coerce command line arguments
+# into objects for us.
+#
+# Gem::OptionParser comes with a few ready-to-use kinds of type
+# coercion. They are:
+#
+# - Date -- Anything accepted by +Date.parse+
+# - DateTime -- Anything accepted by +DateTime.parse+
+# - Time -- Anything accepted by +Time.httpdate+ or +Time.parse+
+# - URI -- Anything accepted by +URI.parse+
+# - Shellwords -- Anything accepted by +Shellwords.shellwords+
+# - String -- Any non-empty string
+# - Integer -- Any integer. Will convert octal. (e.g. 124, -3, 040)
+# - Float -- Any float. (e.g. 10, 3.14, -100E+13)
+# - Numeric -- Any integer, float, or rational (1, 3.4, 1/3)
+# - DecimalInteger -- Like +Integer+, but no octal format.
+# - OctalInteger -- Like +Integer+, but no decimal format.
+# - DecimalNumeric -- Decimal integer or float.
+# - TrueClass -- Accepts '+, yes, true, -, no, false' and
+# defaults as +true+
+# - FalseClass -- Same as +TrueClass+, but defaults to +false+
+# - Array -- Strings separated by ',' (e.g. 1,2,3)
+# - Regexp -- Regular expressions. Also includes options.
+#
+# We can also add our own coercions, which we will cover below.
+#
+# ==== Using Built-in Conversions
+#
+# As an example, the built-in +Time+ conversion is used. The other built-in
+# conversions behave in the same way.
+# Gem::OptionParser will attempt to parse the argument
+# as a +Time+. If it succeeds, that time will be passed to the
+# handler block. Otherwise, an exception will be raised.
+#
+# require 'rubygems/optparse/lib/optparse'
+# require 'rubygems/optparse/lib/optparse/time'
+# Gem::OptionParser.new do |parser|
+# parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
+# p time
+# end
+# end.parse!
+#
+# Used:
+#
+# $ ruby optparse-test.rb -t nonsense
+# ... invalid argument: -t nonsense (Gem::OptionParser::InvalidArgument)
+# $ ruby optparse-test.rb -t 10-11-12
+# 2010-11-12 00:00:00 -0500
+# $ ruby optparse-test.rb -t 9:30
+# 2014-08-13 09:30:00 -0400
+#
+# ==== Creating Custom Conversions
+#
+# The +accept+ method on Gem::OptionParser may be used to create converters.
+# It specifies which conversion block to call whenever a class is specified.
+# The example below uses it to fetch a +User+ object before the +on+ handler receives it.
+#
+# require 'rubygems/optparse/lib/optparse'
+#
+# User = Struct.new(:id, :name)
+#
+# def find_user id
+# not_found = ->{ raise "No User Found for id #{id}" }
+# [ User.new(1, "Sam"),
+# User.new(2, "Gandalf") ].find(not_found) do |u|
+# u.id == id
+# end
+# end
+#
+# op = Gem::OptionParser.new
+# op.accept(User) do |user_id|
+# find_user user_id.to_i
+# end
+#
+# op.on("--user ID", User) do |user|
+# puts user
+# end
+#
+# op.parse!
+#
+# Used:
+#
+# $ ruby optparse-test.rb --user 1
+# #<struct User id=1, name="Sam">
+# $ ruby optparse-test.rb --user 2
+# #<struct User id=2, name="Gandalf">
+# $ ruby optparse-test.rb --user 3
+# optparse-test.rb:15:in `block in find_user': No User Found for id 3 (RuntimeError)
+#
+# === Store options to a Hash
+#
+# The +into+ option of +order+, +parse+ and so on methods stores command line options into a Hash.
+#
+# require 'rubygems/optparse/lib/optparse'
+#
+# options = {}
+# Gem::OptionParser.new do |parser|
+# parser.on('-a')
+# parser.on('-b NUM', Integer)
+# parser.on('-v', '--verbose')
+# end.parse!(into: options)
+#
+# p options
+#
+# Used:
+#
+# $ ruby optparse-test.rb -a
+# {:a=>true}
+# $ ruby optparse-test.rb -a -v
+# {:a=>true, :verbose=>true}
+# $ ruby optparse-test.rb -a -b 100
+# {:a=>true, :b=>100}
+#
+# === Complete example
+#
+# The following example is a complete Ruby program. You can run it and see the
+# effect of specifying various options. This is probably the best way to learn
+# the features of +optparse+.
+#
+# require 'rubygems/optparse/lib/optparse'
+# require 'rubygems/optparse/lib/optparse/time'
+# require 'ostruct'
+# require 'pp'
+#
+# class OptparseExample
+# Version = '1.0.0'
+#
+# CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary]
+# CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
+#
+# class ScriptOptions
+# attr_accessor :library, :inplace, :encoding, :transfer_type,
+# :verbose, :extension, :delay, :time, :record_separator,
+# :list
+#
+# def initialize
+# self.library = []
+# self.inplace = false
+# self.encoding = "utf8"
+# self.transfer_type = :auto
+# self.verbose = false
+# end
+#
+# def define_options(parser)
+# parser.banner = "Usage: example.rb [options]"
+# parser.separator ""
+# parser.separator "Specific options:"
+#
+# # add additional options
+# perform_inplace_option(parser)
+# delay_execution_option(parser)
+# execute_at_time_option(parser)
+# specify_record_separator_option(parser)
+# list_example_option(parser)
+# specify_encoding_option(parser)
+# optional_option_argument_with_keyword_completion_option(parser)
+# boolean_verbose_option(parser)
+#
+# parser.separator ""
+# parser.separator "Common options:"
+# # No argument, shows at tail. This will print an options summary.
+# # Try it and see!
+# parser.on_tail("-h", "--help", "Show this message") do
+# puts parser
+# exit
+# end
+# # Another typical switch to print the version.
+# parser.on_tail("--version", "Show version") do
+# puts Version
+# exit
+# end
+# end
+#
+# def perform_inplace_option(parser)
+# # Specifies an optional option argument
+# parser.on("-i", "--inplace [EXTENSION]",
+# "Edit ARGV files in place",
+# "(make backup if EXTENSION supplied)") do |ext|
+# self.inplace = true
+# self.extension = ext || ''
+# self.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot.
+# end
+# end
+#
+# def delay_execution_option(parser)
+# # Cast 'delay' argument to a Float.
+# parser.on("--delay N", Float, "Delay N seconds before executing") do |n|
+# self.delay = n
+# end
+# end
+#
+# def execute_at_time_option(parser)
+# # Cast 'time' argument to a Time object.
+# parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
+# self.time = time
+# end
+# end
+#
+# def specify_record_separator_option(parser)
+# # Cast to octal integer.
+# parser.on("-F", "--irs [OCTAL]", Gem::OptionParser::OctalInteger,
+# "Specify record separator (default \\0)") do |rs|
+# self.record_separator = rs
+# end
+# end
+#
+# def list_example_option(parser)
+# # List of arguments.
+# parser.on("--list x,y,z", Array, "Example 'list' of arguments") do |list|
+# self.list = list
+# end
+# end
+#
+# def specify_encoding_option(parser)
+# # Keyword completion. We are specifying a specific set of arguments (CODES
+# # and CODE_ALIASES - notice the latter is a Hash), and the user may provide
+# # the shortest unambiguous text.
+# code_list = (CODE_ALIASES.keys + CODES).join(', ')
+# parser.on("--code CODE", CODES, CODE_ALIASES, "Select encoding",
+# "(#{code_list})") do |encoding|
+# self.encoding = encoding
+# end
+# end
+#
+# def optional_option_argument_with_keyword_completion_option(parser)
+# # Optional '--type' option argument with keyword completion.
+# parser.on("--type [TYPE]", [:text, :binary, :auto],
+# "Select transfer type (text, binary, auto)") do |t|
+# self.transfer_type = t
+# end
+# end
+#
+# def boolean_verbose_option(parser)
+# # Boolean switch.
+# parser.on("-v", "--[no-]verbose", "Run verbosely") do |v|
+# self.verbose = v
+# end
+# end
+# end
+#
+# #
+# # Return a structure describing the options.
+# #
+# def parse(args)
+# # The options specified on the command line will be collected in
+# # *options*.
+#
+# @options = ScriptOptions.new
+# @args = Gem::OptionParser.new do |parser|
+# @options.define_options(parser)
+# parser.parse!(args)
+# end
+# @options
+# end
+#
+# attr_reader :parser, :options
+# end # class OptparseExample
+#
+# example = OptparseExample.new
+# options = example.parse(ARGV)
+# pp options # example.options
+# pp ARGV
+#
+# === Shell Completion
+#
+# For modern shells (e.g. bash, zsh, etc.), you can use shell
+# completion for command line options.
+#
+# === Further documentation
+#
+# The above examples, along with the accompanying
+# {Tutorial}[./doc/optparse/tutorial_rdoc.html],
+# should be enough to learn how to use this class.
+# If you have any questions, file a ticket at http://bugs.ruby-lang.org.
+#
+class Gem::OptionParser
+ Gem::OptionParser::Version = "0.2.0"
+
+ # :stopdoc:
+ NoArgument = [NO_ARGUMENT = :NONE, nil].freeze
+ RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze
+ OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze
+ # :startdoc:
+
+ #
+ # Keyword completion module. This allows partial arguments to be specified
+ # and resolved against a list of acceptable values.
+ #
+ module Completion
+ def self.regexp(key, icase)
+ Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'), icase)
+ end
+
+ def self.candidate(key, icase = false, pat = nil, &block)
+ pat ||= Completion.regexp(key, icase)
+ candidates = []
+ block.call do |k, *v|
+ (if Regexp === k
+ kn = ""
+ k === key
+ else
+ kn = defined?(k.id2name) ? k.id2name : k
+ pat === kn
+ end) or next
+ v << k if v.empty?
+ candidates << [k, v, kn]
+ end
+ candidates
+ end
+
+ def candidate(key, icase = false, pat = nil)
+ Completion.candidate(key, icase, pat, &method(:each))
+ end
+
+ public
+ def complete(key, icase = false, pat = nil)
+ candidates = candidate(key, icase, pat, &method(:each)).sort_by {|k, v, kn| kn.size}
+ if candidates.size == 1
+ canon, sw, * = candidates[0]
+ elsif candidates.size > 1
+ canon, sw, cn = candidates.shift
+ candidates.each do |k, v, kn|
+ next if sw == v
+ if String === cn and String === kn
+ if cn.rindex(kn, 0)
+ canon, sw, cn = k, v, kn
+ next
+ elsif kn.rindex(cn, 0)
+ next
+ end
+ end
+ throw :ambiguous, key
+ end
+ end
+ if canon
+ block_given? or return key, *sw
+ yield(key, *sw)
+ end
+ end
+
+ def convert(opt = nil, val = nil, *)
+ val
+ end
+ end
+
+
+ #
+ # Map from option/keyword string to object with completion.
+ #
+ class OptionMap < Hash
+ include Completion
+ end
+
+
+ #
+ # Individual switch class. Not important to the user.
+ #
+ # Defined within Switch are several Switch-derived classes: NoArgument,
+ # RequiredArgument, etc.
+ #
+ class Switch
+ attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block
+
+ #
+ # Guesses argument style from +arg+. Returns corresponding
+ # Gem::OptionParser::Switch class (OptionalArgument, etc.).
+ #
+ def self.guess(arg)
+ case arg
+ when ""
+ t = self
+ when /\A=?\[/
+ t = Switch::OptionalArgument
+ when /\A\s+\[/
+ t = Switch::PlacedArgument
+ else
+ t = Switch::RequiredArgument
+ end
+ self >= t or incompatible_argument_styles(arg, t)
+ t
+ end
+
+ def self.incompatible_argument_styles(arg, t)
+ raise(ArgumentError, "#{arg}: incompatible argument styles\n #{self}, #{t}",
+ ParseError.filter_backtrace(caller(2)))
+ end
+
+ def self.pattern
+ NilClass
+ end
+
+ def initialize(pattern = nil, conv = nil,
+ short = nil, long = nil, arg = nil,
+ desc = ([] if short or long), block = nil, &_block)
+ raise if Array === pattern
+ block ||= _block
+ @pattern, @conv, @short, @long, @arg, @desc, @block =
+ pattern, conv, short, long, arg, desc, block
+ end
+
+ #
+ # Parses +arg+ and returns rest of +arg+ and matched portion to the
+ # argument pattern. Yields when the pattern doesn't match substring.
+ #
+ def parse_arg(arg) # :nodoc:
+ pattern or return nil, [arg]
+ unless m = pattern.match(arg)
+ yield(InvalidArgument, arg)
+ return arg, []
+ end
+ if String === m
+ m = [s = m]
+ else
+ m = m.to_a
+ s = m[0]
+ return nil, m unless String === s
+ end
+ raise InvalidArgument, arg unless arg.rindex(s, 0)
+ return nil, m if s.length == arg.length
+ yield(InvalidArgument, arg) # didn't match whole arg
+ return arg[s.length..-1], m
+ end
+ private :parse_arg
+
+ #
+ # Parses argument, converts and returns +arg+, +block+ and result of
+ # conversion. Yields at semi-error condition instead of raising an
+ # exception.
+ #
+ def conv_arg(arg, val = []) # :nodoc:
+ if conv
+ val = conv.call(*val)
+ else
+ val = proc {|v| v}.call(*val)
+ end
+ return arg, block, val
+ end
+ private :conv_arg
+
+ #
+ # Produces the summary text. Each line of the summary is yielded to the
+ # block (without newline).
+ #
+ # +sdone+:: Already summarized short style options keyed hash.
+ # +ldone+:: Already summarized long style options keyed hash.
+ # +width+:: Width of left side (option part). In other words, the right
+ # side (description part) starts after +width+ columns.
+ # +max+:: Maximum width of left side -> the options are filled within
+ # +max+ columns.
+ # +indent+:: Prefix string indents all summarized lines.
+ #
+ def summarize(sdone = {}, ldone = {}, width = 1, max = width - 1, indent = "")
+ sopts, lopts = [], [], nil
+ @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
+ @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
+ return if sopts.empty? and lopts.empty? # completely hidden
+
+ left = [sopts.join(', ')]
+ right = desc.dup
+
+ while s = lopts.shift
+ l = left[-1].length + s.length
+ l += arg.length if left.size == 1 && arg
+ l < max or sopts.empty? or left << +''
+ left[-1] << (left[-1].empty? ? ' ' * 4 : ', ') << s
+ end
+
+ if arg
+ left[0] << (left[1] ? arg.sub(/\A(\[?)=/, '\1') + ',' : arg)
+ end
+ mlen = left.collect {|ss| ss.length}.max.to_i
+ while mlen > width and l = left.shift
+ mlen = left.collect {|ss| ss.length}.max.to_i if l.length == mlen
+ if l.length < width and (r = right[0]) and !r.empty?
+ l = l.to_s.ljust(width) + ' ' + r
+ right.shift
+ end
+ yield(indent + l)
+ end
+
+ while begin l = left.shift; r = right.shift; l or r end
+ l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
+ yield(indent + l)
+ end
+
+ self
+ end
+
+ def add_banner(to) # :nodoc:
+ unless @short or @long
+ s = desc.join
+ to << " [" + s + "]..." unless s.empty?
+ end
+ to
+ end
+
+ def match_nonswitch?(str) # :nodoc:
+ @pattern =~ str unless @short or @long
+ end
+
+ #
+ # Main name of the switch.
+ #
+ def switch_name
+ (long.first || short.first).sub(/\A-+(?:\[no-\])?/, '')
+ end
+
+ def compsys(sdone, ldone) # :nodoc:
+ sopts, lopts = [], []
+ @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
+ @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
+ return if sopts.empty? and lopts.empty? # completely hidden
+
+ (sopts+lopts).each do |opt|
+ # "(-x -c -r)-l[left justify]"
+ if /^--\[no-\](.+)$/ =~ opt
+ o = $1
+ yield("--#{o}", desc.join(""))
+ yield("--no-#{o}", desc.join(""))
+ else
+ yield("#{opt}", desc.join(""))
+ end
+ end
+ end
+
+ #
+ # Switch that takes no arguments.
+ #
+ class NoArgument < self
+
+ #
+ # Raises an exception if any arguments given.
+ #
+ def parse(arg, argv)
+ yield(NeedlessArgument, arg) if arg
+ conv_arg(arg)
+ end
+
+ def self.incompatible_argument_styles(*)
+ end
+
+ def self.pattern
+ Object
+ end
+ end
+
+ #
+ # Switch that takes an argument.
+ #
+ class RequiredArgument < self
+
+ #
+ # Raises an exception if argument is not present.
+ #
+ def parse(arg, argv)
+ unless arg
+ raise MissingArgument if argv.empty?
+ arg = argv.shift
+ end
+ conv_arg(*parse_arg(arg, &method(:raise)))
+ end
+ end
+
+ #
+ # Switch that can omit argument.
+ #
+ class OptionalArgument < self
+
+ #
+ # Parses argument if given, or uses default value.
+ #
+ def parse(arg, argv, &error)
+ if arg
+ conv_arg(*parse_arg(arg, &error))
+ else
+ conv_arg(arg)
+ end
+ end
+ end
+
+ #
+ # Switch that takes an argument, which does not begin with '-'.
+ #
+ class PlacedArgument < self
+
+ #
+ # Returns nil if argument is not present or begins with '-'.
+ #
+ def parse(arg, argv, &error)
+ if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
+ return nil, block, nil
+ end
+ opt = (val = parse_arg(val, &error))[1]
+ val = conv_arg(*val)
+ if opt and !arg
+ argv.shift
+ else
+ val[0] = nil
+ end
+ val
+ end
+ end
+ end
+
+ #
+ # Simple option list providing mapping from short and/or long option
+ # string to Gem::OptionParser::Switch and mapping from acceptable argument to
+ # matching pattern and converter pair. Also provides summary feature.
+ #
+ class List
+ # Map from acceptable argument types to pattern and converter pairs.
+ attr_reader :atype
+
+ # Map from short style option switches to actual switch objects.
+ attr_reader :short
+
+ # Map from long style option switches to actual switch objects.
+ attr_reader :long
+
+ # List of all switches and summary string.
+ attr_reader :list
+
+ #
+ # Just initializes all instance variables.
+ #
+ def initialize
+ @atype = {}
+ @short = OptionMap.new
+ @long = OptionMap.new
+ @list = []
+ end
+
+ #
+ # See Gem::OptionParser.accept.
+ #
+ def accept(t, pat = /.*/m, &block)
+ if pat
+ pat.respond_to?(:match) or
+ raise TypeError, "has no `match'", ParseError.filter_backtrace(caller(2))
+ else
+ pat = t if t.respond_to?(:match)
+ end
+ unless block
+ block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
+ end
+ @atype[t] = [pat, block]
+ end
+
+ #
+ # See Gem::OptionParser.reject.
+ #
+ def reject(t)
+ @atype.delete(t)
+ end
+
+ #
+ # Adds +sw+ according to +sopts+, +lopts+ and +nlopts+.
+ #
+ # +sw+:: Gem::OptionParser::Switch instance to be added.
+ # +sopts+:: Short style option list.
+ # +lopts+:: Long style option list.
+ # +nlopts+:: Negated long style options list.
+ #
+ def update(sw, sopts, lopts, nsw = nil, nlopts = nil) # :nodoc:
+ sopts.each {|o| @short[o] = sw} if sopts
+ lopts.each {|o| @long[o] = sw} if lopts
+ nlopts.each {|o| @long[o] = nsw} if nsw and nlopts
+ used = @short.invert.update(@long.invert)
+ @list.delete_if {|o| Switch === o and !used[o]}
+ end
+ private :update
+
+ #
+ # Inserts +switch+ at the head of the list, and associates short, long
+ # and negated long options. Arguments are:
+ #
+ # +switch+:: Gem::OptionParser::Switch instance to be inserted.
+ # +short_opts+:: List of short style options.
+ # +long_opts+:: List of long style options.
+ # +nolong_opts+:: List of long style options with "no-" prefix.
+ #
+ # prepend(switch, short_opts, long_opts, nolong_opts)
+ #
+ def prepend(*args)
+ update(*args)
+ @list.unshift(args[0])
+ end
+
+ #
+ # Appends +switch+ at the tail of the list, and associates short, long
+ # and negated long options. Arguments are:
+ #
+ # +switch+:: Gem::OptionParser::Switch instance to be inserted.
+ # +short_opts+:: List of short style options.
+ # +long_opts+:: List of long style options.
+ # +nolong_opts+:: List of long style options with "no-" prefix.
+ #
+ # append(switch, short_opts, long_opts, nolong_opts)
+ #
+ def append(*args)
+ update(*args)
+ @list.push(args[0])
+ end
+
+ #
+ # Searches +key+ in +id+ list. The result is returned or yielded if a
+ # block is given. If it isn't found, nil is returned.
+ #
+ def search(id, key)
+ if list = __send__(id)
+ val = list.fetch(key) {return nil}
+ block_given? ? yield(val) : val
+ end
+ end
+
+ #
+ # Searches list +id+ for +opt+ and the optional patterns for completion
+ # +pat+. If +icase+ is true, the search is case insensitive. The result
+ # is returned or yielded if a block is given. If it isn't found, nil is
+ # returned.
+ #
+ def complete(id, opt, icase = false, *pat, &block)
+ __send__(id).complete(opt, icase, *pat, &block)
+ end
+
+ def get_candidates(id)
+ yield __send__(id).keys
+ end
+
+ #
+ # Iterates over each option, passing the option to the +block+.
+ #
+ def each_option(&block)
+ list.each(&block)
+ end
+
+ #
+ # Creates the summary table, passing each line to the +block+ (without
+ # newline). The arguments +args+ are passed along to the summarize
+ # method which is called on every option.
+ #
+ def summarize(*args, &block)
+ sum = []
+ list.reverse_each do |opt|
+ if opt.respond_to?(:summarize) # perhaps Gem::OptionParser::Switch
+ s = []
+ opt.summarize(*args) {|l| s << l}
+ sum.concat(s.reverse)
+ elsif !opt or opt.empty?
+ sum << ""
+ elsif opt.respond_to?(:each_line)
+ sum.concat([*opt.each_line].reverse)
+ else
+ sum.concat([*opt.each].reverse)
+ end
+ end
+ sum.reverse_each(&block)
+ end
+
+ def add_banner(to) # :nodoc:
+ list.each do |opt|
+ if opt.respond_to?(:add_banner)
+ opt.add_banner(to)
+ end
+ end
+ to
+ end
+
+ def compsys(*args, &block) # :nodoc:
+ list.each do |opt|
+ if opt.respond_to?(:compsys)
+ opt.compsys(*args, &block)
+ end
+ end
+ end
+ end
+
+ #
+ # Hash with completion search feature. See Gem::OptionParser::Completion.
+ #
+ class CompletingHash < Hash
+ include Completion
+
+ #
+ # Completion for hash key.
+ #
+ def match(key)
+ *values = fetch(key) {
+ raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
+ }
+ return key, *values
+ end
+ end
+
+ # :stopdoc:
+
+ #
+ # Enumeration of acceptable argument styles. Possible values are:
+ #
+ # NO_ARGUMENT:: The switch takes no arguments. (:NONE)
+ # REQUIRED_ARGUMENT:: The switch requires an argument. (:REQUIRED)
+ # OPTIONAL_ARGUMENT:: The switch requires an optional argument. (:OPTIONAL)
+ #
+ # Use like --switch=argument (long style) or -Xargument (short style). For
+ # short style, only portion matched to argument pattern is treated as
+ # argument.
+ #
+ ArgumentStyle = {}
+ NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument}
+ RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument}
+ OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument}
+ ArgumentStyle.freeze
+
+ #
+ # Switches common used such as '--', and also provides default
+ # argument classes
+ #
+ DefaultList = List.new
+ DefaultList.short['-'] = Switch::NoArgument.new {}
+ DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}
+
+
+ COMPSYS_HEADER = <<'XXX' # :nodoc:
+
+typeset -A opt_args
+local context state line
+
+_arguments -s -S \
+XXX
+
+ def compsys(to, name = File.basename($0)) # :nodoc:
+ to << "#compdef #{name}\n"
+ to << COMPSYS_HEADER
+ visit(:compsys, {}, {}) {|o, d|
+ to << %Q[ "#{o}[#{d.gsub(/[\"\[\]]/, '\\\\\&')}]" \\\n]
+ }
+ to << " '*:file:_files' && return 0\n"
+ end
+
+ #
+ # Default options for ARGV, which never appear in option summary.
+ #
+ Officious = {}
+
+ #
+ # --help
+ # Shows option summary.
+ #
+ Officious['help'] = proc do |parser|
+ Switch::NoArgument.new do |arg|
+ puts parser.help
+ exit
+ end
+ end
+
+ #
+ # --*-completion-bash=WORD
+ # Shows candidates for command line completion.
+ #
+ Officious['*-completion-bash'] = proc do |parser|
+ Switch::RequiredArgument.new do |arg|
+ puts parser.candidate(arg)
+ exit
+ end
+ end
+
+ #
+ # --*-completion-zsh[=NAME:FILE]
+ # Creates zsh completion file.
+ #
+ Officious['*-completion-zsh'] = proc do |parser|
+ Switch::OptionalArgument.new do |arg|
+ parser.compsys(STDOUT, arg)
+ exit
+ end
+ end
+
+ #
+ # --version
+ # Shows version string if Version is defined.
+ #
+ Officious['version'] = proc do |parser|
+ Switch::OptionalArgument.new do |pkg|
+ if pkg
+ begin
+ require 'rubygems/optparse/lib/optparse/version'
+ rescue LoadError
+ else
+ show_version(*pkg.split(/,/)) or
+ abort("#{parser.program_name}: no version found in package #{pkg}")
+ exit
+ end
+ end
+ v = parser.ver or abort("#{parser.program_name}: version unknown")
+ puts v
+ exit
+ end
+ end
+
+ # :startdoc:
+
+ #
+ # Class methods
+ #
+
+ #
+ # Initializes a new instance and evaluates the optional block in context
+ # of the instance. Arguments +args+ are passed to #new, see there for
+ # description of parameters.
+ #
+ # This method is *deprecated*, its behavior corresponds to the older #new
+ # method.
+ #
+ def self.with(*args, &block)
+ opts = new(*args)
+ opts.instance_eval(&block)
+ opts
+ end
+
+ #
+ # Returns an incremented value of +default+ according to +arg+.
+ #
+ def self.inc(arg, default = nil)
+ case arg
+ when Integer
+ arg.nonzero?
+ when nil
+ default.to_i + 1
+ end
+ end
+ def inc(*args)
+ self.class.inc(*args)
+ end
+
+ #
+ # Initializes the instance and yields itself if called with a block.
+ #
+ # +banner+:: Banner message.
+ # +width+:: Summary width.
+ # +indent+:: Summary indent.
+ #
+ def initialize(banner = nil, width = 32, indent = ' ' * 4)
+ @stack = [DefaultList, List.new, List.new]
+ @program_name = nil
+ @banner = banner
+ @summary_width = width
+ @summary_indent = indent
+ @default_argv = ARGV
+ @require_exact = false
+ add_officious
+ yield self if block_given?
+ end
+
+ def add_officious # :nodoc:
+ list = base()
+ Officious.each do |opt, block|
+ list.long[opt] ||= block.call(self)
+ end
+ end
+
+ #
+ # Terminates option parsing. Optional parameter +arg+ is a string pushed
+ # back to be the first non-option argument.
+ #
+ def terminate(arg = nil)
+ self.class.terminate(arg)
+ end
+ def self.terminate(arg = nil)
+ throw :terminate, arg
+ end
+
+ @stack = [DefaultList]
+ def self.top() DefaultList end
+
+ #
+ # Directs to accept specified class +t+. The argument string is passed to
+ # the block in which it should be converted to the desired class.
+ #
+ # +t+:: Argument class specifier, any object including Class.
+ # +pat+:: Pattern for argument, defaults to +t+ if it responds to match.
+ #
+ # accept(t, pat, &block)
+ #
+ def accept(*args, &blk) top.accept(*args, &blk) end
+ #
+ # See #accept.
+ #
+ def self.accept(*args, &blk) top.accept(*args, &blk) end
+
+ #
+ # Directs to reject specified class argument.
+ #
+ # +t+:: Argument class specifier, any object including Class.
+ #
+ # reject(t)
+ #
+ def reject(*args, &blk) top.reject(*args, &blk) end
+ #
+ # See #reject.
+ #
+ def self.reject(*args, &blk) top.reject(*args, &blk) end
+
+ #
+ # Instance methods
+ #
+
+ # Heading banner preceding summary.
+ attr_writer :banner
+
+ # Program name to be emitted in error message and default banner,
+ # defaults to $0.
+ attr_writer :program_name
+
+ # Width for option list portion of summary. Must be Numeric.
+ attr_accessor :summary_width
+
+ # Indentation for summary. Must be String (or have + String method).
+ attr_accessor :summary_indent
+
+ # Strings to be parsed in default.
+ attr_accessor :default_argv
+
+ # Whether to require that options match exactly (disallows providing
+ # abbreviated long option as short option).
+ attr_accessor :require_exact
+
+ #
+ # Heading banner preceding summary.
+ #
+ def banner
+ unless @banner
+ @banner = +"Usage: #{program_name} [options]"
+ visit(:add_banner, @banner)
+ end
+ @banner
+ end
+
+ #
+ # Program name to be emitted in error message and default banner, defaults
+ # to $0.
+ #
+ def program_name
+ @program_name || File.basename($0, '.*')
+ end
+
+ # for experimental cascading :-)
+ alias set_banner banner=
+ alias set_program_name program_name=
+ alias set_summary_width summary_width=
+ alias set_summary_indent summary_indent=
+
+ # Version
+ attr_writer :version
+ # Release code
+ attr_writer :release
+
+ #
+ # Version
+ #
+ def version
+ (defined?(@version) && @version) || (defined?(::Version) && ::Version)
+ end
+
+ #
+ # Release code
+ #
+ def release
+ (defined?(@release) && @release) || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
+ end
+
+ #
+ # Returns version string from program_name, version and release.
+ #
+ def ver
+ if v = version
+ str = +"#{program_name} #{[v].join('.')}"
+ str << " (#{v})" if v = release
+ str
+ end
+ end
+
+ def warn(mesg = $!)
+ super("#{program_name}: #{mesg}")
+ end
+
+ def abort(mesg = $!)
+ super("#{program_name}: #{mesg}")
+ end
+
+ #
+ # Subject of #on / #on_head, #accept / #reject
+ #
+ def top
+ @stack[-1]
+ end
+
+ #
+ # Subject of #on_tail.
+ #
+ def base
+ @stack[1]
+ end
+
+ #
+ # Pushes a new List.
+ #
+ def new
+ @stack.push(List.new)
+ if block_given?
+ yield self
+ else
+ self
+ end
+ end
+
+ #
+ # Removes the last List.
+ #
+ def remove
+ @stack.pop
+ end
+
+ #
+ # Puts option summary into +to+ and returns +to+. Yields each line if
+ # a block is given.
+ #
+ # +to+:: Output destination, which must have method <<. Defaults to [].
+ # +width+:: Width of left side, defaults to @summary_width.
+ # +max+:: Maximum length allowed for left side, defaults to +width+ - 1.
+ # +indent+:: Indentation, defaults to @summary_indent.
+ #
+ def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
+ nl = "\n"
+ blk ||= proc {|l| to << (l.index(nl, -1) ? l : l + nl)}
+ visit(:summarize, {}, {}, width, max, indent, &blk)
+ to
+ end
+
+ #
+ # Returns option summary string.
+ #
+ def help; summarize("#{banner}".sub(/\n?\z/, "\n")) end
+ alias to_s help
+
+ #
+ # Returns option summary list.
+ #
+ def to_a; summarize("#{banner}".split(/^/)) end
+
+ #
+ # Checks if an argument is given twice, in which case an ArgumentError is
+ # raised. Called from Gem::OptionParser#switch only.
+ #
+ # +obj+:: New argument.
+ # +prv+:: Previously specified argument.
+ # +msg+:: Exception message.
+ #
+ def notwice(obj, prv, msg) # :nodoc:
+ unless !prv or prv == obj
+ raise(ArgumentError, "argument #{msg} given twice: #{obj}",
+ ParseError.filter_backtrace(caller(2)))
+ end
+ obj
+ end
+ private :notwice
+
+ SPLAT_PROC = proc {|*a| a.length <= 1 ? a.first : a} # :nodoc:
+
+ # :call-seq:
+ # make_switch(params, block = nil)
+ #
+ # :include: ../doc/optparse/creates_option.rdoc
+ #
+ def make_switch(opts, block = nil)
+ short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
+ ldesc, sdesc, desc, arg = [], [], []
+ default_style = Switch::NoArgument
+ default_pattern = nil
+ klass = nil
+ q, a = nil
+ has_arg = false
+
+ opts.each do |o|
+ # argument class
+ next if search(:atype, o) do |pat, c|
+ klass = notwice(o, klass, 'type')
+ if not_style and not_style != Switch::NoArgument
+ not_pattern, not_conv = pat, c
+ else
+ default_pattern, conv = pat, c
+ end
+ end
+
+ # directly specified pattern(any object possible to match)
+ if (!(String === o || Symbol === o)) and o.respond_to?(:match)
+ pattern = notwice(o, pattern, 'pattern')
+ if pattern.respond_to?(:convert)
+ conv = pattern.method(:convert).to_proc
+ else
+ conv = SPLAT_PROC
+ end
+ next
+ end
+
+ # anything others
+ case o
+ when Proc, Method
+ block = notwice(o, block, 'block')
+ when Array, Hash
+ case pattern
+ when CompletingHash
+ when nil
+ pattern = CompletingHash.new
+ conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
+ else
+ raise ArgumentError, "argument pattern given twice"
+ end
+ o.each {|pat, *v| pattern[pat] = v.fetch(0) {pat}}
+ when Module
+ raise ArgumentError, "unsupported argument type: #{o}", ParseError.filter_backtrace(caller(4))
+ when *ArgumentStyle.keys
+ style = notwice(ArgumentStyle[o], style, 'style')
+ when /^--no-([^\[\]=\s]*)(.+)?/
+ q, a = $1, $2
+ o = notwice(a ? Object : TrueClass, klass, 'type')
+ not_pattern, not_conv = search(:atype, o) unless not_style
+ not_style = (not_style || default_style).guess(arg = a) if a
+ default_style = Switch::NoArgument
+ default_pattern, conv = search(:atype, FalseClass) unless default_pattern
+ ldesc << "--no-#{q}"
+ (q = q.downcase).tr!('_', '-')
+ long << "no-#{q}"
+ nolong << q
+ when /^--\[no-\]([^\[\]=\s]*)(.+)?/
+ q, a = $1, $2
+ o = notwice(a ? Object : TrueClass, klass, 'type')
+ if a
+ default_style = default_style.guess(arg = a)
+ default_pattern, conv = search(:atype, o) unless default_pattern
+ end
+ ldesc << "--[no-]#{q}"
+ (o = q.downcase).tr!('_', '-')
+ long << o
+ not_pattern, not_conv = search(:atype, FalseClass) unless not_style
+ not_style = Switch::NoArgument
+ nolong << "no-#{o}"
+ when /^--([^\[\]=\s]*)(.+)?/
+ q, a = $1, $2
+ if a
+ o = notwice(NilClass, klass, 'type')
+ default_style = default_style.guess(arg = a)
+ default_pattern, conv = search(:atype, o) unless default_pattern
+ end
+ ldesc << "--#{q}"
+ (o = q.downcase).tr!('_', '-')
+ long << o
+ when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
+ q, a = $1, $2
+ o = notwice(Object, klass, 'type')
+ if a
+ default_style = default_style.guess(arg = a)
+ default_pattern, conv = search(:atype, o) unless default_pattern
+ else
+ has_arg = true
+ end
+ sdesc << "-#{q}"
+ short << Regexp.new(q)
+ when /^-(.)(.+)?/
+ q, a = $1, $2
+ if a
+ o = notwice(NilClass, klass, 'type')
+ default_style = default_style.guess(arg = a)
+ default_pattern, conv = search(:atype, o) unless default_pattern
+ end
+ sdesc << "-#{q}"
+ short << q
+ when /^=/
+ style = notwice(default_style.guess(arg = o), style, 'style')
+ default_pattern, conv = search(:atype, Object) unless default_pattern
+ else
+ desc.push(o)
+ end
+ end
+
+ default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern
+ if !(short.empty? and long.empty?)
+ if has_arg and default_style == Switch::NoArgument
+ default_style = Switch::RequiredArgument
+ end
+ s = (style || default_style).new(pattern || default_pattern,
+ conv, sdesc, ldesc, arg, desc, block)
+ elsif !block
+ if style or pattern
+ raise ArgumentError, "no switch given", ParseError.filter_backtrace(caller)
+ end
+ s = desc
+ else
+ short << pattern
+ s = (style || default_style).new(pattern,
+ conv, nil, nil, arg, desc, block)
+ end
+ return s, short, long,
+ (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
+ nolong
+ end
+
+ # :call-seq:
+ # define(*params, &block)
+ #
+ # :include: ../doc/optparse/creates_option.rdoc
+ #
+ def define(*opts, &block)
+ top.append(*(sw = make_switch(opts, block)))
+ sw[0]
+ end
+
+ # :call-seq:
+ # on(*params, &block)
+ #
+ # :include: ../doc/optparse/creates_option.rdoc
+ #
+ def on(*opts, &block)
+ define(*opts, &block)
+ self
+ end
+ alias def_option define
+
+ # :call-seq:
+ # define_head(*params, &block)
+ #
+ # :include: ../doc/optparse/creates_option.rdoc
+ #
+ def define_head(*opts, &block)
+ top.prepend(*(sw = make_switch(opts, block)))
+ sw[0]
+ end
+
+ # :call-seq:
+ # on_head(*params, &block)
+ #
+ # :include: ../doc/optparse/creates_option.rdoc
+ #
+ # The new option is added at the head of the summary.
+ #
+ def on_head(*opts, &block)
+ define_head(*opts, &block)
+ self
+ end
+ alias def_head_option define_head
+
+ # :call-seq:
+ # define_tail(*params, &block)
+ #
+ # :include: ../doc/optparse/creates_option.rdoc
+ #
+ def define_tail(*opts, &block)
+ base.append(*(sw = make_switch(opts, block)))
+ sw[0]
+ end
+
+ #
+ # :call-seq:
+ # on_tail(*params, &block)
+ #
+ # :include: ../doc/optparse/creates_option.rdoc
+ #
+ # The new option is added at the tail of the summary.
+ #
+ def on_tail(*opts, &block)
+ define_tail(*opts, &block)
+ self
+ end
+ alias def_tail_option define_tail
+
+ #
+ # Add separator in summary.
+ #
+ def separator(string)
+ top.append(string, nil, nil)
+ end
+
+ #
+ # Parses command line arguments +argv+ in order. When a block is given,
+ # each non-option argument is yielded. When optional +into+ keyword
+ # argument is provided, the parsed option values are stored there via
+ # <code>[]=</code> method (so it can be Hash, or OpenStruct, or other
+ # similar object).
+ #
+ # Returns the rest of +argv+ left unparsed.
+ #
+ def order(*argv, into: nil, &nonopt)
+ argv = argv[0].dup if argv.size == 1 and Array === argv[0]
+ order!(argv, into: into, &nonopt)
+ end
+
+ #
+ # Same as #order, but removes switches destructively.
+ # Non-option arguments remain in +argv+.
+ #
+ def order!(argv = default_argv, into: nil, &nonopt)
+ setter = ->(name, val) {into[name.to_sym] = val} if into
+ parse_in_order(argv, setter, &nonopt)
+ end
+
+ def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
+ opt, arg, val, rest = nil
+ nonopt ||= proc {|a| throw :terminate, a}
+ argv.unshift(arg) if arg = catch(:terminate) {
+ while arg = argv.shift
+ case arg
+ # long option
+ when /\A--([^=]*)(?:=(.*))?/m
+ opt, rest = $1, $2
+ opt.tr!('_', '-')
+ begin
+ sw, = complete(:long, opt, true)
+ if require_exact && !sw.long.include?(arg)
+ raise InvalidOption, arg
+ end
+ rescue ParseError
+ raise $!.set_option(arg, true)
+ end
+ begin
+ opt, cb, val = sw.parse(rest, argv) {|*exc| raise(*exc)}
+ val = cb.call(val) if cb
+ setter.call(sw.switch_name, val) if setter
+ rescue ParseError
+ raise $!.set_option(arg, rest)
+ end
+
+ # short option
+ when /\A-(.)((=).*|.+)?/m
+ eq, rest, opt = $3, $2, $1
+ has_arg, val = eq, rest
+ begin
+ sw, = search(:short, opt)
+ unless sw
+ begin
+ sw, = complete(:short, opt)
+ # short option matched.
+ val = arg.delete_prefix('-')
+ has_arg = true
+ rescue InvalidOption
+ raise if require_exact
+ # if no short options match, try completion with long
+ # options.
+ sw, = complete(:long, opt)
+ eq ||= !rest
+ end
+ end
+ rescue ParseError
+ raise $!.set_option(arg, true)
+ end
+ begin
+ opt, cb, val = sw.parse(val, argv) {|*exc| raise(*exc) if eq}
+ rescue ParseError
+ raise $!.set_option(arg, arg.length > 2)
+ else
+ raise InvalidOption, arg if has_arg and !eq and arg == "-#{opt}"
+ end
+ begin
+ argv.unshift(opt) if opt and (!rest or (opt = opt.sub(/\A-*/, '-')) != '-')
+ val = cb.call(val) if cb
+ setter.call(sw.switch_name, val) if setter
+ rescue ParseError
+ raise $!.set_option(arg, arg.length > 2)
+ end
+
+ # non-option argument
+ else
+ catch(:prune) do
+ visit(:each_option) do |sw0|
+ sw = sw0
+ sw.block.call(arg) if Switch === sw and sw.match_nonswitch?(arg)
+ end
+ nonopt.call(arg)
+ end
+ end
+ end
+
+ nil
+ }
+
+ visit(:search, :short, nil) {|sw| sw.block.call(*argv) if !sw.pattern}
+
+ argv
+ end
+ private :parse_in_order
+
+ #
+ # Parses command line arguments +argv+ in permutation mode and returns
+ # list of non-option arguments. When optional +into+ keyword
+ # argument is provided, the parsed option values are stored there via
+ # <code>[]=</code> method (so it can be Hash, or OpenStruct, or other
+ # similar object).
+ #
+ def permute(*argv, into: nil)
+ argv = argv[0].dup if argv.size == 1 and Array === argv[0]
+ permute!(argv, into: into)
+ end
+
+ #
+ # Same as #permute, but removes switches destructively.
+ # Non-option arguments remain in +argv+.
+ #
+ def permute!(argv = default_argv, into: nil)
+ nonopts = []
+ order!(argv, into: into, &nonopts.method(:<<))
+ argv[0, 0] = nonopts
+ argv
+ end
+
+ #
+ # Parses command line arguments +argv+ in order when environment variable
+ # POSIXLY_CORRECT is set, and in permutation mode otherwise.
+ # When optional +into+ keyword argument is provided, the parsed option
+ # values are stored there via <code>[]=</code> method (so it can be Hash,
+ # or OpenStruct, or other similar object).
+ #
+ def parse(*argv, into: nil)
+ argv = argv[0].dup if argv.size == 1 and Array === argv[0]
+ parse!(argv, into: into)
+ end
+
+ #
+ # Same as #parse, but removes switches destructively.
+ # Non-option arguments remain in +argv+.
+ #
+ def parse!(argv = default_argv, into: nil)
+ if ENV.include?('POSIXLY_CORRECT')
+ order!(argv, into: into)
+ else
+ permute!(argv, into: into)
+ end
+ end
+
+ #
+ # Wrapper method for getopts.rb.
+ #
+ # params = ARGV.getopts("ab:", "foo", "bar:", "zot:Z;zot option")
+ # # params["a"] = true # -a
+ # # params["b"] = "1" # -b1
+ # # params["foo"] = "1" # --foo
+ # # params["bar"] = "x" # --bar x
+ # # params["zot"] = "z" # --zot Z
+ #
+ def getopts(*args)
+ argv = Array === args.first ? args.shift : default_argv
+ single_options, *long_options = *args
+
+ result = {}
+
+ single_options.scan(/(.)(:)?/) do |opt, val|
+ if val
+ result[opt] = nil
+ define("-#{opt} VAL")
+ else
+ result[opt] = false
+ define("-#{opt}")
+ end
+ end if single_options
+
+ long_options.each do |arg|
+ arg, desc = arg.split(';', 2)
+ opt, val = arg.split(':', 2)
+ if val
+ result[opt] = val.empty? ? nil : val
+ define("--#{opt}=#{result[opt] || "VAL"}", *[desc].compact)
+ else
+ result[opt] = false
+ define("--#{opt}", *[desc].compact)
+ end
+ end
+
+ parse_in_order(argv, result.method(:[]=))
+ result
+ end
+
+ #
+ # See #getopts.
+ #
+ def self.getopts(*args)
+ new.getopts(*args)
+ end
+
+ #
+ # Traverses @stack, sending each element method +id+ with +args+ and
+ # +block+.
+ #
+ def visit(id, *args, &block) # :nodoc:
+ @stack.reverse_each do |el|
+ el.__send__(id, *args, &block)
+ end
+ nil
+ end
+ private :visit
+
+ #
+ # Searches +key+ in @stack for +id+ hash and returns or yields the result.
+ #
+ def search(id, key) # :nodoc:
+ block_given = block_given?
+ visit(:search, id, key) do |k|
+ return block_given ? yield(k) : k
+ end
+ end
+ private :search
+
+ #
+ # Completes shortened long style option switch and returns pair of
+ # canonical switch and switch descriptor Gem::OptionParser::Switch.
+ #
+ # +typ+:: Searching table.
+ # +opt+:: Searching key.
+ # +icase+:: Search case insensitive if true.
+ # +pat+:: Optional pattern for completion.
+ #
+ def complete(typ, opt, icase = false, *pat) # :nodoc:
+ if pat.empty?
+ search(typ, opt) {|sw| return [sw, opt]} # exact match or...
+ end
+ ambiguous = catch(:ambiguous) {
+ visit(:complete, typ, opt, icase, *pat) {|o, *sw| return sw}
+ }
+ exc = ambiguous ? AmbiguousOption : InvalidOption
+ raise exc.new(opt, additional: self.method(:additional_message).curry[typ])
+ end
+ private :complete
+
+ #
+ # Returns additional info.
+ #
+ def additional_message(typ, opt)
+ return unless typ and opt and defined?(DidYouMean::SpellChecker)
+ all_candidates = []
+ visit(:get_candidates, typ) do |candidates|
+ all_candidates.concat(candidates)
+ end
+ all_candidates.select! {|cand| cand.is_a?(String) }
+ checker = DidYouMean::SpellChecker.new(dictionary: all_candidates)
+ suggestions = all_candidates & checker.correct(opt)
+ if DidYouMean.respond_to?(:formatter)
+ DidYouMean.formatter.message_for(suggestions)
+ else
+ "\nDid you mean? #{suggestions.join("\n ")}"
+ end
+ end
+
+ def candidate(word)
+ list = []
+ case word
+ when '-'
+ long = short = true
+ when /\A--/
+ word, arg = word.split(/=/, 2)
+ argpat = Completion.regexp(arg, false) if arg and !arg.empty?
+ long = true
+ when /\A-/
+ short = true
+ end
+ pat = Completion.regexp(word, long)
+ visit(:each_option) do |opt|
+ next unless Switch === opt
+ opts = (long ? opt.long : []) + (short ? opt.short : [])
+ opts = Completion.candidate(word, true, pat, &opts.method(:each)).map(&:first) if pat
+ if /\A=/ =~ opt.arg
+ opts.map! {|sw| sw + "="}
+ if arg and CompletingHash === opt.pattern
+ if opts = opt.pattern.candidate(arg, false, argpat)
+ opts.map!(&:last)
+ end
+ end
+ end
+ list.concat(opts)
+ end
+ list
+ end
+
+ #
+ # Loads options from file names as +filename+. Does nothing when the file
+ # is not present. Returns whether successfully loaded.
+ #
+ # +filename+ defaults to basename of the program without suffix in a
+ # directory ~/.options, then the basename with '.options' suffix
+ # under XDG and Haiku standard places.
+ #
+ def load(filename = nil)
+ unless filename
+ basename = File.basename($0, '.*')
+ return true if load(File.expand_path(basename, '~/.options')) rescue nil
+ basename << ".options"
+ return [
+ # XDG
+ ENV['XDG_CONFIG_HOME'],
+ '~/.config',
+ *ENV['XDG_CONFIG_DIRS']&.split(File::PATH_SEPARATOR),
+
+ # Haiku
+ '~/config/settings',
+ ].any? {|dir|
+ next if !dir or dir.empty?
+ load(File.expand_path(basename, dir)) rescue nil
+ }
+ end
+ begin
+ parse(*IO.readlines(filename).each {|s| s.chomp!})
+ true
+ rescue Errno::ENOENT, Errno::ENOTDIR
+ false
+ end
+ end
+
+ #
+ # Parses environment variable +env+ or its uppercase with splitting like a
+ # shell.
+ #
+ # +env+ defaults to the basename of the program.
+ #
+ def environment(env = File.basename($0, '.*'))
+ env = ENV[env] || ENV[env.upcase] or return
+ require 'shellwords'
+ parse(*Shellwords.shellwords(env))
+ end
+
+ #
+ # Acceptable argument classes
+ #
+
+ #
+ # Any string and no conversion. This is fall-back.
+ #
+ accept(Object) {|s,|s or s.nil?}
+
+ accept(NilClass) {|s,|s}
+
+ #
+ # Any non-empty string, and no conversion.
+ #
+ accept(String, /.+/m) {|s,*|s}
+
+ #
+ # Ruby/C-like integer, octal for 0-7 sequence, binary for 0b, hexadecimal
+ # for 0x, and decimal for others; with optional sign prefix. Converts to
+ # Integer.
+ #
+ decimal = '\d+(?:_\d+)*'
+ binary = 'b[01]+(?:_[01]+)*'
+ hex = 'x[\da-f]+(?:_[\da-f]+)*'
+ octal = "0(?:[0-7]+(?:_[0-7]+)*|#{binary}|#{hex})?"
+ integer = "#{octal}|#{decimal}"
+
+ accept(Integer, %r"\A[-+]?(?:#{integer})\z"io) {|s,|
+ begin
+ Integer(s)
+ rescue ArgumentError
+ raise Gem::OptionParser::InvalidArgument, s
+ end if s
+ }
+
+ #
+ # Float number format, and converts to Float.
+ #
+ float = "(?:#{decimal}(?=(.)?)(?:\\.(?:#{decimal})?)?|\\.#{decimal})(?:E[-+]?#{decimal})?"
+ floatpat = %r"\A[-+]?#{float}\z"io
+ accept(Float, floatpat) {|s,| s.to_f if s}
+
+ #
+ # Generic numeric format, converts to Integer for integer format, Float
+ # for float format, and Rational for rational format.
+ #
+ real = "[-+]?(?:#{octal}|#{float})"
+ accept(Numeric, /\A(#{real})(?:\/(#{real}))?\z/io) {|s, d, f, n,|
+ if n
+ Rational(d, n)
+ elsif f
+ Float(s)
+ else
+ Integer(s)
+ end
+ }
+
+ #
+ # Decimal integer format, to be converted to Integer.
+ #
+ DecimalInteger = /\A[-+]?#{decimal}\z/io
+ accept(DecimalInteger, DecimalInteger) {|s,|
+ begin
+ Integer(s, 10)
+ rescue ArgumentError
+ raise Gem::OptionParser::InvalidArgument, s
+ end if s
+ }
+
+ #
+ # Ruby/C like octal/hexadecimal/binary integer format, to be converted to
+ # Integer.
+ #
+ OctalInteger = /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))\z/io
+ accept(OctalInteger, OctalInteger) {|s,|
+ begin
+ Integer(s, 8)
+ rescue ArgumentError
+ raise Gem::OptionParser::InvalidArgument, s
+ end if s
+ }
+
+ #
+ # Decimal integer/float number format, to be converted to Integer for
+ # integer format, Float for float format.
+ #
+ DecimalNumeric = floatpat # decimal integer is allowed as float also.
+ accept(DecimalNumeric, floatpat) {|s, f|
+ begin
+ if f
+ Float(s)
+ else
+ Integer(s)
+ end
+ rescue ArgumentError
+ raise Gem::OptionParser::InvalidArgument, s
+ end if s
+ }
+
+ #
+ # Boolean switch, which means whether it is present or not, whether it is
+ # absent or not with prefix no-, or it takes an argument
+ # yes/no/true/false/+/-.
+ #
+ yesno = CompletingHash.new
+ %w[- no false].each {|el| yesno[el] = false}
+ %w[+ yes true].each {|el| yesno[el] = true}
+ yesno['nil'] = false # should be nil?
+ accept(TrueClass, yesno) {|arg, val| val == nil or val}
+ #
+ # Similar to TrueClass, but defaults to false.
+ #
+ accept(FalseClass, yesno) {|arg, val| val != nil and val}
+
+ #
+ # List of strings separated by ",".
+ #
+ accept(Array) do |s, |
+ if s
+ s = s.split(',').collect {|ss| ss unless ss.empty?}
+ end
+ s
+ end
+
+ #
+ # Regular expression with options.
+ #
+ accept(Regexp, %r"\A/((?:\\.|[^\\])*)/([[:alpha:]]+)?\z|.*") do |all, s, o|
+ f = 0
+ if o
+ f |= Regexp::IGNORECASE if /i/ =~ o
+ f |= Regexp::MULTILINE if /m/ =~ o
+ f |= Regexp::EXTENDED if /x/ =~ o
+ k = o.delete("imx")
+ k = nil if k.empty?
+ end
+ Regexp.new(s || all, f, k)
+ end
+
+ #
+ # Exceptions
+ #
+
+ #
+ # Base class of exceptions from Gem::OptionParser.
+ #
+ class ParseError < RuntimeError
+ # Reason which caused the error.
+ Reason = 'parse error'
+
+ def initialize(*args, additional: nil)
+ @additional = additional
+ @arg0, = args
+ @args = args
+ @reason = nil
+ end
+
+ attr_reader :args
+ attr_writer :reason
+ attr_accessor :additional
+
+ #
+ # Pushes back erred argument(s) to +argv+.
+ #
+ def recover(argv)
+ argv[0, 0] = @args
+ argv
+ end
+
+ def self.filter_backtrace(array)
+ unless $DEBUG
+ array.delete_if(&%r"\A#{Regexp.quote(__FILE__)}:"o.method(:=~))
+ end
+ array
+ end
+
+ def set_backtrace(array)
+ super(self.class.filter_backtrace(array))
+ end
+
+ def set_option(opt, eq)
+ if eq
+ @args[0] = opt
+ else
+ @args.unshift(opt)
+ end
+ self
+ end
+
+ #
+ # Returns error reason. Override this for I18N.
+ #
+ def reason
+ @reason || self.class::Reason
+ end
+
+ def inspect
+ "#<#{self.class}: #{args.join(' ')}>"
+ end
+
+ #
+ # Default stringizing method to emit standard error message.
+ #
+ def message
+ "#{reason}: #{args.join(' ')}#{additional[@arg0] if additional}"
+ end
+
+ alias to_s message
+ end
+
+ #
+ # Raises when ambiguously completable string is encountered.
+ #
+ class AmbiguousOption < ParseError
+ const_set(:Reason, 'ambiguous option')
+ end
+
+ #
+ # Raises when there is an argument for a switch which takes no argument.
+ #
+ class NeedlessArgument < ParseError
+ const_set(:Reason, 'needless argument')
+ end
+
+ #
+ # Raises when a switch with mandatory argument has no argument.
+ #
+ class MissingArgument < ParseError
+ const_set(:Reason, 'missing argument')
+ end
+
+ #
+ # Raises when switch is undefined.
+ #
+ class InvalidOption < ParseError
+ const_set(:Reason, 'invalid option')
+ end
+
+ #
+ # Raises when the given argument does not match required format.
+ #
+ class InvalidArgument < ParseError
+ const_set(:Reason, 'invalid argument')
+ end
+
+ #
+ # Raises when the given argument word can't be completed uniquely.
+ #
+ class AmbiguousArgument < InvalidArgument
+ const_set(:Reason, 'ambiguous argument')
+ end
+
+ #
+ # Miscellaneous
+ #
+
+ #
+ # Extends command line arguments array (ARGV) to parse itself.
+ #
+ module Arguable
+
+ #
+ # Sets Gem::OptionParser object, when +opt+ is +false+ or +nil+, methods
+ # Gem::OptionParser::Arguable#options and Gem::OptionParser::Arguable#options= are
+ # undefined. Thus, there is no ways to access the Gem::OptionParser object
+ # via the receiver object.
+ #
+ def options=(opt)
+ unless @optparse = opt
+ class << self
+ undef_method(:options)
+ undef_method(:options=)
+ end
+ end
+ end
+
+ #
+ # Actual Gem::OptionParser object, automatically created if nonexistent.
+ #
+ # If called with a block, yields the Gem::OptionParser object and returns the
+ # result of the block. If an Gem::OptionParser::ParseError exception occurs
+ # in the block, it is rescued, a error message printed to STDERR and
+ # +nil+ returned.
+ #
+ def options
+ @optparse ||= Gem::OptionParser.new
+ @optparse.default_argv = self
+ block_given? or return @optparse
+ begin
+ yield @optparse
+ rescue ParseError
+ @optparse.warn $!
+ nil
+ end
+ end
+
+ #
+ # Parses +self+ destructively in order and returns +self+ containing the
+ # rest arguments left unparsed.
+ #
+ def order!(&blk) options.order!(self, &blk) end
+
+ #
+ # Parses +self+ destructively in permutation mode and returns +self+
+ # containing the rest arguments left unparsed.
+ #
+ def permute!() options.permute!(self) end
+
+ #
+ # Parses +self+ destructively and returns +self+ containing the
+ # rest arguments left unparsed.
+ #
+ def parse!() options.parse!(self) end
+
+ #
+ # Substitution of getopts is possible as follows. Also see
+ # Gem::OptionParser#getopts.
+ #
+ # def getopts(*args)
+ # ($OPT = ARGV.getopts(*args)).each do |opt, val|
+ # eval "$OPT_#{opt.gsub(/[^A-Za-z0-9_]/, '_')} = val"
+ # end
+ # rescue Gem::OptionParser::ParseError
+ # end
+ #
+ def getopts(*args)
+ options.getopts(self, *args)
+ end
+
+ #
+ # Initializes instance variable.
+ #
+ def self.extend_object(obj)
+ super
+ obj.instance_eval {@optparse = nil}
+ end
+ def initialize(*args)
+ super
+ @optparse = nil
+ end
+ end
+
+ #
+ # Acceptable argument classes. Now contains DecimalInteger, OctalInteger
+ # and DecimalNumeric. See Acceptable argument classes (in source code).
+ #
+ module Acceptables
+ const_set(:DecimalInteger, Gem::OptionParser::DecimalInteger)
+ const_set(:OctalInteger, Gem::OptionParser::OctalInteger)
+ const_set(:DecimalNumeric, Gem::OptionParser::DecimalNumeric)
+ end
+end
+
+# ARGV is arguable by Gem::OptionParser
+ARGV.extend(Gem::OptionParser::Arguable)
diff --git a/lib/rubygems/optparse/lib/optparse/ac.rb b/lib/rubygems/optparse/lib/optparse/ac.rb
new file mode 100644
index 00000000000..ff2f4c2dc3e
--- /dev/null
+++ b/lib/rubygems/optparse/lib/optparse/ac.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: false
+require 'rubygems/optparse/lib/optparse'
+
+class Gem::OptionParser::AC < Gem::OptionParser
+ private
+
+ def _check_ac_args(name, block)
+ unless /\A\w[-\w]*\z/ =~ name
+ raise ArgumentError, name
+ end
+ unless block
+ raise ArgumentError, "no block given", ParseError.filter_backtrace(caller)
+ end
+ end
+
+ ARG_CONV = proc {|val| val.nil? ? true : val}
+
+ def _ac_arg_enable(prefix, name, help_string, block)
+ _check_ac_args(name, block)
+
+ sdesc = []
+ ldesc = ["--#{prefix}-#{name}"]
+ desc = [help_string]
+ q = name.downcase
+ ac_block = proc {|val| block.call(ARG_CONV.call(val))}
+ enable = Switch::PlacedArgument.new(nil, ARG_CONV, sdesc, ldesc, nil, desc, ac_block)
+ disable = Switch::NoArgument.new(nil, proc {false}, sdesc, ldesc, nil, desc, ac_block)
+ top.append(enable, [], ["enable-" + q], disable, ['disable-' + q])
+ enable
+ end
+
+ public
+
+ def ac_arg_enable(name, help_string, &block)
+ _ac_arg_enable("enable", name, help_string, block)
+ end
+
+ def ac_arg_disable(name, help_string, &block)
+ _ac_arg_enable("disable", name, help_string, block)
+ end
+
+ def ac_arg_with(name, help_string, &block)
+ _check_ac_args(name, block)
+
+ sdesc = []
+ ldesc = ["--with-#{name}"]
+ desc = [help_string]
+ q = name.downcase
+ with = Switch::PlacedArgument.new(*search(:atype, String), sdesc, ldesc, nil, desc, block)
+ without = Switch::NoArgument.new(nil, proc {}, sdesc, ldesc, nil, desc, block)
+ top.append(with, [], ["with-" + q], without, ['without-' + q])
+ with
+ end
+end
diff --git a/lib/rubygems/optparse/lib/optparse/date.rb b/lib/rubygems/optparse/lib/optparse/date.rb
new file mode 100644
index 00000000000..11131e92c22
--- /dev/null
+++ b/lib/rubygems/optparse/lib/optparse/date.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: false
+require 'rubygems/optparse/lib/optparse'
+require 'date'
+
+Gem::OptionParser.accept(DateTime) do |s,|
+ begin
+ DateTime.parse(s) if s
+ rescue ArgumentError
+ raise Gem::OptionParser::InvalidArgument, s
+ end
+end
+Gem::OptionParser.accept(Date) do |s,|
+ begin
+ Date.parse(s) if s
+ rescue ArgumentError
+ raise Gem::OptionParser::InvalidArgument, s
+ end
+end
diff --git a/lib/rubygems/optparse/lib/optparse/kwargs.rb b/lib/rubygems/optparse/lib/optparse/kwargs.rb
new file mode 100644
index 00000000000..9290344c39a
--- /dev/null
+++ b/lib/rubygems/optparse/lib/optparse/kwargs.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+require 'rubygems/optparse/lib/optparse'
+
+class Gem::OptionParser
+ # :call-seq:
+ # define_by_keywords(options, method, **params)
+ #
+ # :include: ../../doc/optparse/creates_option.rdoc
+ #
+ def define_by_keywords(options, meth, **opts)
+ meth.parameters.each do |type, name|
+ case type
+ when :key, :keyreq
+ op, cl = *(type == :key ? %w"[ ]" : ["", ""])
+ define("--#{name}=#{op}#{name.upcase}#{cl}", *opts[name]) do |o|
+ options[name] = o
+ end
+ end
+ end
+ options
+ end
+end
diff --git a/lib/rubygems/optparse/lib/optparse/shellwords.rb b/lib/rubygems/optparse/lib/optparse/shellwords.rb
new file mode 100644
index 00000000000..60dd91990c1
--- /dev/null
+++ b/lib/rubygems/optparse/lib/optparse/shellwords.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: false
+# -*- ruby -*-
+
+require 'shellwords'
+require 'rubygems/optparse/lib/optparse'
+
+Gem::OptionParser.accept(Shellwords) {|s,| Shellwords.shellwords(s)}
diff --git a/lib/rubygems/optparse/lib/optparse/time.rb b/lib/rubygems/optparse/lib/optparse/time.rb
new file mode 100644
index 00000000000..cb19f6e998e
--- /dev/null
+++ b/lib/rubygems/optparse/lib/optparse/time.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: false
+require 'rubygems/optparse/lib/optparse'
+require 'time'
+
+Gem::OptionParser.accept(Time) do |s,|
+ begin
+ (Time.httpdate(s) rescue Time.parse(s)) if s
+ rescue
+ raise Gem::OptionParser::InvalidArgument, s
+ end
+end
diff --git a/lib/rubygems/optparse/lib/optparse/uri.rb b/lib/rubygems/optparse/lib/optparse/uri.rb
new file mode 100644
index 00000000000..088f309992f
--- /dev/null
+++ b/lib/rubygems/optparse/lib/optparse/uri.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: false
+# -*- ruby -*-
+
+require 'rubygems/optparse/lib/optparse'
+require 'uri'
+
+Gem::OptionParser.accept(URI) {|s,| URI.parse(s) if s}
diff --git a/lib/rubygems/optparse/lib/optparse/version.rb b/lib/rubygems/optparse/lib/optparse/version.rb
new file mode 100644
index 00000000000..5d79e9db44d
--- /dev/null
+++ b/lib/rubygems/optparse/lib/optparse/version.rb
@@ -0,0 +1,71 @@
+# frozen_string_literal: false
+# Gem::OptionParser internal utility
+
+class << Gem::OptionParser
+ def show_version(*pkgs)
+ progname = ARGV.options.program_name
+ result = false
+ show = proc do |klass, cname, version|
+ str = "#{progname}"
+ unless klass == ::Object and cname == :VERSION
+ version = version.join(".") if Array === version
+ str << ": #{klass}" unless klass == Object
+ str << " version #{version}"
+ end
+ [:Release, :RELEASE].find do |rel|
+ if klass.const_defined?(rel)
+ str << " (#{klass.const_get(rel)})"
+ end
+ end
+ puts str
+ result = true
+ end
+ if pkgs.size == 1 and pkgs[0] == "all"
+ self.search_const(::Object, /\AV(?:ERSION|ersion)\z/) do |klass, cname, version|
+ unless cname[1] == ?e and klass.const_defined?(:Version)
+ show.call(klass, cname.intern, version)
+ end
+ end
+ else
+ pkgs.each do |pkg|
+ begin
+ pkg = pkg.split(/::|\//).inject(::Object) {|m, c| m.const_get(c)}
+ v = case
+ when pkg.const_defined?(:Version)
+ pkg.const_get(n = :Version)
+ when pkg.const_defined?(:VERSION)
+ pkg.const_get(n = :VERSION)
+ else
+ n = nil
+ "unknown"
+ end
+ show.call(pkg, n, v)
+ rescue NameError
+ end
+ end
+ end
+ result
+ end
+
+ def each_const(path, base = ::Object)
+ path.split(/::|\//).inject(base) do |klass, name|
+ raise NameError, path unless Module === klass
+ klass.constants.grep(/#{name}/i) do |c|
+ klass.const_defined?(c) or next
+ klass.const_get(c)
+ end
+ end
+ end
+
+ def search_const(klass, name)
+ klasses = [klass]
+ while klass = klasses.shift
+ klass.constants.each do |cname|
+ klass.const_defined?(cname) or next
+ const = klass.const_get(cname)
+ yield klass, cname, const if name === cname
+ klasses << const if Module === const and const != ::Object
+ end
+ end
+ end
+end
diff --git a/lib/rubygems/package.rb b/lib/rubygems/package.rb
index c4b29e4176d..94705914af5 100644
--- a/lib/rubygems/package.rb
+++ b/lib/rubygems/package.rb
@@ -71,6 +71,13 @@ class Gem::Package
end
end
+ class SymlinkError < Error
+ def initialize(name, destination, destination_dir)
+ super "installing symlink '%s' pointing to parent path %s of %s is not allowed" %
+ [name, destination, destination_dir]
+ end
+ end
+
class NonSeekableIO < Error; end
class TooLongFileName < Error; end
@@ -400,13 +407,21 @@ EOM
# extracted.
def extract_tar_gz(io, destination_dir, pattern = "*") # :nodoc:
- directories = [] if dir_mode
+ directories = []
open_tar_gz io do |tar|
tar.each do |entry|
next unless File.fnmatch pattern, entry.full_name, File::FNM_DOTMATCH
destination = install_location entry.full_name, destination_dir
+ if entry.symlink?
+ link_target = entry.header.linkname
+ real_destination = link_target.start_with?("/") ? link_target : File.expand_path(link_target, File.dirname(destination))
+
+ raise Gem::Package::SymlinkError.new(entry.full_name, real_destination, destination_dir) unless
+ normalize_path(real_destination).start_with? normalize_path(destination_dir + '/')
+ end
+
FileUtils.rm_rf destination
mkdir_options = {}
@@ -417,9 +432,11 @@ EOM
else
File.dirname destination
end
- directories << mkdir if directories
- mkdir_p_safe mkdir, mkdir_options, destination_dir, entry.full_name
+ unless directories.include?(mkdir)
+ FileUtils.mkdir_p mkdir, **mkdir_options
+ directories << mkdir
+ end
File.open destination, 'wb' do |out|
out.write entry.read
@@ -432,8 +449,7 @@ EOM
end
end
- if directories
- directories.uniq!
+ if dir_mode
File.chmod(dir_mode, *directories)
end
end
@@ -466,21 +482,11 @@ EOM
raise Gem::Package::PathError.new(filename, destination_dir) if
filename.start_with? '/'
- destination_dir = File.expand_path(File.realpath(destination_dir))
- destination = File.expand_path(File.join(destination_dir, filename))
+ destination_dir = File.realpath(destination_dir)
+ destination = File.expand_path(filename, destination_dir)
raise Gem::Package::PathError.new(destination, destination_dir) unless
- destination.start_with? destination_dir + '/'
-
- begin
- real_destination = File.expand_path(File.realpath(destination))
- rescue
- # it's fine if the destination doesn't exist, because rm -rf'ing it can't cause any damage
- nil
- else
- raise Gem::Package::PathError.new(real_destination, destination_dir) unless
- real_destination.start_with? destination_dir + '/'
- end
+ normalize_path(destination).start_with? normalize_path(destination_dir + '/')
destination.tap(&Gem::UNTAINT)
destination
@@ -494,22 +500,6 @@ EOM
end
end
- def mkdir_p_safe(mkdir, mkdir_options, destination_dir, file_name)
- destination_dir = File.realpath(File.expand_path(destination_dir))
- parts = mkdir.split(File::SEPARATOR)
- parts.reduce do |path, basename|
- path = File.realpath(path) unless path == ""
- path = File.expand_path(path + File::SEPARATOR + basename)
- lstat = File.lstat path rescue nil
- if !lstat || !lstat.directory?
- unless normalize_path(path).start_with? normalize_path(destination_dir) and (FileUtils.mkdir path, **mkdir_options rescue false)
- raise Gem::Package::PathError.new(file_name, destination_dir)
- end
- end
- path
- end
- end
-
##
# Loads a Gem::Specification from the TarEntry +entry+
diff --git a/lib/rubygems/query_utils.rb b/lib/rubygems/query_utils.rb
index ea0f260ab4e..0acd5bf9c83 100644
--- a/lib/rubygems/query_utils.rb
+++ b/lib/rubygems/query_utils.rb
@@ -1,9 +1,9 @@
# frozen_string_literal: true
-require 'rubygems/local_remote_options'
-require 'rubygems/spec_fetcher'
-require 'rubygems/version_option'
-require 'rubygems/text'
+require_relative 'local_remote_options'
+require_relative 'spec_fetcher'
+require_relative 'version_option'
+require_relative 'text'
module Gem::QueryUtils
diff --git a/lib/rubygems/remote_fetcher.rb b/lib/rubygems/remote_fetcher.rb
index 0724a51ee0b..bd8165e3c79 100644
--- a/lib/rubygems/remote_fetcher.rb
+++ b/lib/rubygems/remote_fetcher.rb
@@ -72,7 +72,7 @@ class Gem::RemoteFetcher
# fetching the gem.
def initialize(proxy=nil, dns=nil, headers={})
- require 'rubygems/core_ext/tcpsocket_init' if Gem.configuration.ipv4_fallback_enabled
+ require_relative 'core_ext/tcpsocket_init' if Gem.configuration.ipv4_fallback_enabled
require 'net/http'
require 'stringio'
require 'uri'
diff --git a/lib/rubygems/request.rb b/lib/rubygems/request.rb
index 72e25e20abe..d6100c914b0 100644
--- a/lib/rubygems/request.rb
+++ b/lib/rubygems/request.rb
@@ -96,8 +96,10 @@ class Gem::Request
return unless cert
case error_number
when OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED then
+ require 'time'
"Certificate #{cert.subject} expired at #{cert.not_after.iso8601}"
when OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID then
+ require 'time'
"Certificate #{cert.subject} not valid until #{cert.not_before.iso8601}"
when OpenSSL::X509::V_ERR_CERT_REJECTED then
"Certificate #{cert.subject} is rejected"
diff --git a/lib/rubygems/request_set.rb b/lib/rubygems/request_set.rb
index 9286c542219..01b01599a8f 100644
--- a/lib/rubygems/request_set.rb
+++ b/lib/rubygems/request_set.rb
@@ -1,5 +1,5 @@
# frozen_string_literal: true
-require 'tsort'
+require_relative 'tsort'
##
# A RequestSet groups a request to activate a set of dependencies.
@@ -15,7 +15,7 @@ require 'tsort'
# #=> ["nokogiri-1.6.0", "mini_portile-0.5.1", "pg-0.17.0"]
class Gem::RequestSet
- include TSort
+ include Gem::TSort
##
# Array of gems to install even if already installed
diff --git a/lib/rubygems/resolver/molinillo/lib/molinillo/dependency_graph.rb b/lib/rubygems/resolver/molinillo/lib/molinillo/dependency_graph.rb
index 16430a79f5b..95f8416b967 100644
--- a/lib/rubygems/resolver/molinillo/lib/molinillo/dependency_graph.rb
+++ b/lib/rubygems/resolver/molinillo/lib/molinillo/dependency_graph.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'tsort'
+require_relative '../../../../tsort'
require_relative 'dependency_graph/log'
require_relative 'dependency_graph/vertex'
@@ -17,7 +17,7 @@ module Gem::Resolver::Molinillo
vertices.values.each { |v| yield v }
end
- include TSort
+ include Gem::TSort
# @!visibility private
alias tsort_each_node each
diff --git a/lib/rubygems/s3_uri_signer.rb b/lib/rubygems/s3_uri_signer.rb
index bba9afc9ffa..4d1deee9972 100644
--- a/lib/rubygems/s3_uri_signer.rb
+++ b/lib/rubygems/s3_uri_signer.rb
@@ -1,5 +1,4 @@
-require 'digest'
-require 'rubygems/openssl'
+require_relative 'openssl'
##
# S3URISigner implements AWS SigV4 for S3 Source to avoid a dependency on the aws-sdk-* gems
@@ -87,7 +86,7 @@ class Gem::S3URISigner
"AWS4-HMAC-SHA256",
date_time,
credential_info,
- Digest::SHA256.hexdigest(canonical_request),
+ OpenSSL::Digest::SHA256.hexdigest(canonical_request),
].join("\n")
end
@@ -140,8 +139,8 @@ class Gem::S3URISigner
def ec2_metadata_credentials_json
require 'net/http'
- require 'rubygems/request'
- require 'rubygems/request/connection_pools'
+ require_relative 'request'
+ require_relative 'request/connection_pools'
require 'json'
iam_info = ec2_metadata_request(EC2_IAM_INFO)
diff --git a/lib/rubygems/security.rb b/lib/rubygems/security.rb
index 28f705549c8..22759972070 100644
--- a/lib/rubygems/security.rb
+++ b/lib/rubygems/security.rb
@@ -152,6 +152,7 @@ require_relative 'openssl'
# certificate for EMAIL_ADDR
# -C, --certificate CERT Signing certificate for --sign
# -K, --private-key KEY Key for --sign or --build
+# -A, --key-algorithm ALGORITHM Select key algorithm for --build from RSA, DSA, or EC. Defaults to RSA.
# -s, --sign CERT Signs CERT with the key from -K
# and the certificate from -C
# -d, --days NUMBER_OF_DAYS Days before the certificate expires
@@ -317,7 +318,6 @@ require_relative 'openssl'
# * Honor extension restrictions
# * Might be better to store the certificate chain as a PKCS#7 or PKCS#12
# file, instead of an array embedded in the metadata.
-# * Flexible signature and key algorithms, not hard-coded to RSA and SHA1.
#
# == Original author
#
@@ -337,17 +337,19 @@ module Gem::Security
DIGEST_NAME = 'SHA256' # :nodoc:
##
- # Algorithm for creating the key pair used to sign gems
+ # Length of keys created by RSA and DSA keys
- KEY_ALGORITHM =
- if defined?(OpenSSL::PKey::RSA)
- OpenSSL::PKey::RSA
- end
+ RSA_DSA_KEY_LENGTH = 3072
##
- # Length of keys created by KEY_ALGORITHM
+ # Default algorithm to use when building a key pair
- KEY_LENGTH = 3072
+ DEFAULT_KEY_ALGORITHM = 'RSA'
+
+ ##
+ # Named curve used for Elliptic Curve
+
+ EC_NAME = 'secp384r1'
##
# Cipher used to encrypt the key pair used to sign gems.
@@ -400,7 +402,7 @@ module Gem::Security
serial = 1)
cert = OpenSSL::X509::Certificate.new
- cert.public_key = key.public_key
+ cert.public_key = get_public_key(key)
cert.version = 2
cert.serial = serial
@@ -419,6 +421,24 @@ module Gem::Security
end
##
+ # Gets the right public key from a PKey instance
+
+ def self.get_public_key(key)
+ return key.public_key unless key.is_a?(OpenSSL::PKey::EC)
+
+ ec_key = OpenSSL::PKey::EC.new(key.group.curve_name)
+ ec_key.public_key = key.public_key
+ ec_key
+ end
+
+ ##
+ # In Ruby 2.3 EC doesn't implement the private_key? but not the private? method
+
+ if defined?(OpenSSL::PKey::EC) && Gem::Version.new(String.new(RUBY_VERSION)) < Gem::Version.new("2.4.0")
+ OpenSSL::PKey::EC.send(:alias_method, :private?, :private_key?)
+ end
+
+ ##
# Creates a self-signed certificate with an issuer and subject from +email+,
# a subject alternative name of +email+ and the given +extensions+ for the
# +key+.
@@ -459,11 +479,25 @@ module Gem::Security
end
##
- # Creates a new key pair of the specified +length+ and +algorithm+. The
- # default is a 3072 bit RSA key.
-
- def self.create_key(length = KEY_LENGTH, algorithm = KEY_ALGORITHM)
- algorithm.new length
+ # Creates a new key pair of the specified +algorithm+. RSA, DSA, and EC
+ # are supported.
+
+ def self.create_key(algorithm)
+ if defined?(OpenSSL::PKey)
+ case algorithm.downcase
+ when 'dsa'
+ OpenSSL::PKey::DSA.new(RSA_DSA_KEY_LENGTH)
+ when 'rsa'
+ OpenSSL::PKey::RSA.new(RSA_DSA_KEY_LENGTH)
+ when 'ec'
+ domain_key = OpenSSL::PKey::EC.new(EC_NAME)
+ domain_key.generate_key
+ domain_key
+ else
+ raise Gem::Security::Exception,
+ "#{algorithm} algorithm not found. RSA, DSA, and EC algorithms are supported."
+ end
+ end
end
##
@@ -476,9 +510,10 @@ module Gem::Security
dcs = dcs.split '.'
- name = "CN=#{cn}/#{dcs.map {|dc| "DC=#{dc}" }.join '/'}"
-
- OpenSSL::X509::Name.parse name
+ OpenSSL::X509::Name.new([
+ ["CN", cn],
+ *dcs.map {|dc| ["DC", dc] },
+ ])
end
##
@@ -492,7 +527,7 @@ module Gem::Security
raise Gem::Security::Exception,
"incorrect signing key for re-signing " +
"#{expired_certificate.subject}" unless
- expired_certificate.public_key.to_pem == private_key.public_key.to_pem
+ expired_certificate.public_key.to_pem == get_public_key(private_key).to_pem
unless expired_certificate.subject.to_s ==
expired_certificate.issuer.to_s
diff --git a/lib/rubygems/security/policy.rb b/lib/rubygems/security/policy.rb
index 9683e55b327..3c3cb647ee3 100644
--- a/lib/rubygems/security/policy.rb
+++ b/lib/rubygems/security/policy.rb
@@ -115,9 +115,11 @@ class Gem::Security::Policy
raise Gem::Security::Exception, 'missing key or signature'
end
+ public_key = Gem::Security.get_public_key(key)
+
raise Gem::Security::Exception,
"certificate #{signer.subject} does not match the signing key" unless
- signer.public_key.to_pem == key.public_key.to_pem
+ signer.public_key.to_pem == public_key.to_pem
true
end
@@ -164,9 +166,9 @@ class Gem::Security::Policy
end
save_cert = OpenSSL::X509::Certificate.new File.read path
- save_dgst = digester.digest save_cert.public_key.to_s
+ save_dgst = digester.digest save_cert.public_key.to_pem
- pkey_str = root.public_key.to_s
+ pkey_str = root.public_key.to_pem
cert_dgst = digester.digest pkey_str
raise Gem::Security::Exception,
diff --git a/lib/rubygems/security/signer.rb b/lib/rubygems/security/signer.rb
index c5c2c4f2200..968cf889730 100644
--- a/lib/rubygems/security/signer.rb
+++ b/lib/rubygems/security/signer.rb
@@ -83,8 +83,8 @@ class Gem::Security::Signer
@digest_name = Gem::Security::DIGEST_NAME
@digest_algorithm = Gem::Security.create_digest(@digest_name)
- if @key && !@key.is_a?(OpenSSL::PKey::RSA)
- @key = OpenSSL::PKey::RSA.new(File.read(@key), @passphrase)
+ if @key && !@key.is_a?(OpenSSL::PKey::PKey)
+ @key = OpenSSL::PKey.read(File.read(@key), @passphrase)
end
if @cert_chain
@@ -177,8 +177,7 @@ class Gem::Security::Signer
disk_cert = File.read(disk_cert_path) rescue nil
disk_key_path = File.join(Gem.default_key_path)
- disk_key =
- OpenSSL::PKey::RSA.new(File.read(disk_key_path), @passphrase) rescue nil
+ disk_key = OpenSSL::PKey.read(File.read(disk_key_path), @passphrase) rescue nil
return unless disk_key
diff --git a/lib/rubygems/security_option.rb b/lib/rubygems/security_option.rb
index 6c75d6ecb4f..a4c570ded5c 100644
--- a/lib/rubygems/security_option.rb
+++ b/lib/rubygems/security_option.rb
@@ -19,16 +19,16 @@ end
module Gem::SecurityOption
def add_security_option
- OptionParser.accept Gem::Security::Policy do |value|
+ Gem::OptionParser.accept Gem::Security::Policy do |value|
require_relative 'security'
- raise OptionParser::InvalidArgument, 'OpenSSL not installed' unless
+ raise Gem::OptionParser::InvalidArgument, 'OpenSSL not installed' unless
defined?(Gem::Security::HighSecurity)
policy = Gem::Security::Policies[value]
unless policy
valid = Gem::Security::Policies.keys.sort
- raise OptionParser::InvalidArgument, "#{value} (#{valid.join ', '} are valid)"
+ raise Gem::OptionParser::InvalidArgument, "#{value} (#{valid.join ', '} are valid)"
end
policy
end
diff --git a/lib/rubygems/server.rb b/lib/rubygems/server.rb
deleted file mode 100644
index 45be05bcda7..00000000000
--- a/lib/rubygems/server.rb
+++ /dev/null
@@ -1,882 +0,0 @@
-# frozen_string_literal: true
-require 'zlib'
-require 'erb'
-require 'uri'
-
-require_relative '../rubygems'
-require_relative 'rdoc'
-
-##
-# Gem::Server and allows users to serve gems for consumption by
-# `gem --remote-install`.
-#
-# gem_server starts an HTTP server on the given port and serves the following:
-# * "/" - Browsing of gem spec files for installed gems
-# * "/specs.#{Gem.marshal_version}.gz" - specs name/version/platform index
-# * "/latest_specs.#{Gem.marshal_version}.gz" - latest specs
-# name/version/platform index
-# * "/quick/" - Individual gemspecs
-# * "/gems" - Direct access to download the installable gems
-# * "/rdoc?q=" - Search for installed rdoc documentation
-#
-# == Usage
-#
-# gem_server = Gem::Server.new Gem.dir, 8089, false
-# gem_server.run
-#
-#--
-# TODO Refactor into a real WEBrick servlet to remove code duplication.
-
-class Gem::Server
- attr_reader :spec_dirs
-
- include ERB::Util
- include Gem::UserInteraction
-
- SEARCH = <<-ERB.freeze
- <form class="headerSearch" name="headerSearchForm" method="get" action="/rdoc">
- <div id="search" style="float:right">
- <label for="q">Filter/Search</label>
- <input id="q" type="text" style="width:10em" name="q">
- <button type="submit" style="display:none"></button>
- </div>
- </form>
- ERB
-
- DOC_TEMPLATE = <<-'ERB'.freeze
- <?xml version="1.0" encoding="iso-8859-1"?>
- <!DOCTYPE html
- PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <title>RubyGems Documentation Index</title>
- <link rel="stylesheet" href="gem-server-rdoc-style.css" type="text/css" media="screen" />
- </head>
- <body>
- <div id="fileHeader">
-<%= SEARCH %>
- <h1>RubyGems Documentation Index</h1>
- </div>
- <!-- banner header -->
-
- <div id="bodyContent">
- <div id="contextContent">
- <div id="description">
- <h1>Summary</h1>
- <p>There are <%=values["gem_count"]%> gems installed:</p>
- <p>
- <%= values["specs"].map { |v| "<a href=\"##{u v["name"]}\">#{h v["name"]}</a>" }.join ', ' %>.
- <h1>Gems</h1>
-
- <dl>
- <% values["specs"].each do |spec| %>
- <dt>
- <% if spec["first_name_entry"] then %>
- <a name="<%=h spec["name"]%>"></a>
- <% end %>
-
- <b><%=h spec["name"]%> <%=h spec["version"]%></b>
-
- <% if spec["ri_installed"] || spec["rdoc_installed"] then %>
- <a href="<%=spec["doc_path"]%>">[rdoc]</a>
- <% else %>
- <span title="rdoc not installed">[rdoc]</span>
- <% end %>
-
- <% if spec["homepage"] then %>
- <a href="<%=uri_encode spec["homepage"]%>" title="<%=h spec["homepage"]%>">[www]</a>
- <% else %>
- <span title="no homepage available">[www]</span>
- <% end %>
-
- <% if spec["has_deps"] then %>
- - depends on
- <%= spec["dependencies"].map { |v| "<a href=\"##{u v["name"]}\">#{h v["name"]}</a>" }.join ', ' %>.
- <% end %>
- </dt>
- <dd>
- <%=spec["summary"]%>
- <% if spec["executables"] then %>
- <br/>
-
- <% if spec["only_one_executable"] then %>
- Executable is
- <% else %>
- Executables are
- <%end%>
-
- <%= spec["executables"].map { |v| "<span class=\"context-item-name\">#{h v["executable"]}</span>"}.join ', ' %>.
-
- <%end%>
- <br/>
- <br/>
- </dd>
- <% end %>
- </dl>
-
- </div>
- </div>
- </div>
- <div id="validator-badges">
- <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
- </div>
- </body>
- </html>
- ERB
-
- # CSS is copy & paste from rdoc-style.css, RDoc V1.0.1 - 20041108
- RDOC_CSS = <<-CSS.freeze
-body {
- font-family: Verdana,Arial,Helvetica,sans-serif;
- font-size: 90%;
- margin: 0;
- margin-left: 40px;
- padding: 0;
- background: white;
-}
-
-h1,h2,h3,h4 { margin: 0; color: #efefef; background: transparent; }
-h1 { font-size: 150%; }
-h2,h3,h4 { margin-top: 1em; }
-
-a { background: #eef; color: #039; text-decoration: none; }
-a:hover { background: #039; color: #eef; }
-
-/* Override the base stylesheets Anchor inside a table cell */
-td > a {
- background: transparent;
- color: #039;
- text-decoration: none;
-}
-
-/* and inside a section title */
-.section-title > a {
- background: transparent;
- color: #eee;
- text-decoration: none;
-}
-
-/* === Structural elements =================================== */
-
-div#index {
- margin: 0;
- margin-left: -40px;
- padding: 0;
- font-size: 90%;
-}
-
-
-div#index a {
- margin-left: 0.7em;
-}
-
-div#index .section-bar {
- margin-left: 0px;
- padding-left: 0.7em;
- background: #ccc;
- font-size: small;
-}
-
-
-div#classHeader, div#fileHeader {
- width: auto;
- color: white;
- padding: 0.5em 1.5em 0.5em 1.5em;
- margin: 0;
- margin-left: -40px;
- border-bottom: 3px solid #006;
-}
-
-div#classHeader a, div#fileHeader a {
- background: inherit;
- color: white;
-}
-
-div#classHeader td, div#fileHeader td {
- background: inherit;
- color: white;
-}
-
-
-div#fileHeader {
- background: #057;
-}
-
-div#classHeader {
- background: #048;
-}
-
-
-.class-name-in-header {
- font-size: 180%;
- font-weight: bold;
-}
-
-
-div#bodyContent {
- padding: 0 1.5em 0 1.5em;
-}
-
-div#description {
- padding: 0.5em 1.5em;
- background: #efefef;
- border: 1px dotted #999;
-}
-
-div#description h1,h2,h3,h4,h5,h6 {
- color: #125;;
- background: transparent;
-}
-
-div#validator-badges {
- text-align: center;
-}
-div#validator-badges img { border: 0; }
-
-div#copyright {
- color: #333;
- background: #efefef;
- font: 0.75em sans-serif;
- margin-top: 5em;
- margin-bottom: 0;
- padding: 0.5em 2em;
-}
-
-
-/* === Classes =================================== */
-
-table.header-table {
- color: white;
- font-size: small;
-}
-
-.type-note {
- font-size: small;
- color: #DEDEDE;
-}
-
-.xxsection-bar {
- background: #eee;
- color: #333;
- padding: 3px;
-}
-
-.section-bar {
- color: #333;
- border-bottom: 1px solid #999;
- margin-left: -20px;
-}
-
-
-.section-title {
- background: #79a;
- color: #eee;
- padding: 3px;
- margin-top: 2em;
- margin-left: -30px;
- border: 1px solid #999;
-}
-
-.top-aligned-row { vertical-align: top }
-.bottom-aligned-row { vertical-align: bottom }
-
-/* --- Context section classes ----------------------- */
-
-.context-row { }
-.context-item-name { font-family: monospace; font-weight: bold; color: black; }
-.context-item-value { font-size: small; color: #448; }
-.context-item-desc { color: #333; padding-left: 2em; }
-
-/* --- Method classes -------------------------- */
-.method-detail {
- background: #efefef;
- padding: 0;
- margin-top: 0.5em;
- margin-bottom: 1em;
- border: 1px dotted #ccc;
-}
-.method-heading {
- color: black;
- background: #ccc;
- border-bottom: 1px solid #666;
- padding: 0.2em 0.5em 0 0.5em;
-}
-.method-signature { color: black; background: inherit; }
-.method-name { font-weight: bold; }
-.method-args { font-style: italic; }
-.method-description { padding: 0 0.5em 0 0.5em; }
-
-/* --- Source code sections -------------------- */
-
-a.source-toggle { font-size: 90%; }
-div.method-source-code {
- background: #262626;
- color: #ffdead;
- margin: 1em;
- padding: 0.5em;
- border: 1px dashed #999;
- overflow: hidden;
-}
-
-div.method-source-code pre { color: #ffdead; overflow: hidden; }
-
-/* --- Ruby keyword styles --------------------- */
-
-.standalone-code { background: #221111; color: #ffdead; overflow: hidden; }
-
-.ruby-constant { color: #7fffd4; background: transparent; }
-.ruby-keyword { color: #00ffff; background: transparent; }
-.ruby-ivar { color: #eedd82; background: transparent; }
-.ruby-operator { color: #00ffee; background: transparent; }
-.ruby-identifier { color: #ffdead; background: transparent; }
-.ruby-node { color: #ffa07a; background: transparent; }
-.ruby-comment { color: #b22222; font-weight: bold; background: transparent; }
-.ruby-regexp { color: #ffa07a; background: transparent; }
-.ruby-value { color: #7fffd4; background: transparent; }
- CSS
-
- RDOC_NO_DOCUMENTATION = <<-'ERB'.freeze
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <title>Found documentation</title>
- <link rel="stylesheet" href="gem-server-rdoc-style.css" type="text/css" media="screen" />
- </head>
- <body>
- <div id="fileHeader">
-<%= SEARCH %>
- <h1>No documentation found</h1>
- </div>
-
- <div id="bodyContent">
- <div id="contextContent">
- <div id="description">
- <p>No gems matched <%= h query.inspect %></p>
-
- <p>
- Back to <a href="/">complete gem index</a>
- </p>
-
- </div>
- </div>
- </div>
- <div id="validator-badges">
- <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
- </div>
- </body>
-</html>
- ERB
-
- RDOC_SEARCH_TEMPLATE = <<-'ERB'.freeze
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <title>Found documentation</title>
- <link rel="stylesheet" href="gem-server-rdoc-style.css" type="text/css" media="screen" />
- </head>
- <body>
- <div id="fileHeader">
-<%= SEARCH %>
- <h1>Found documentation</h1>
- </div>
- <!-- banner header -->
-
- <div id="bodyContent">
- <div id="contextContent">
- <div id="description">
- <h1>Summary</h1>
- <p><%=doc_items.length%> documentation topics found.</p>
- <h1>Topics</h1>
-
- <dl>
- <% doc_items.each do |doc_item| %>
- <dt>
- <b><%=doc_item[:name]%></b>
- <a href="<%=u doc_item[:url]%>">[rdoc]</a>
- </dt>
- <dd>
- <%=h doc_item[:summary]%>
- <br/>
- <br/>
- </dd>
- <% end %>
- </dl>
-
- <p>
- Back to <a href="/">complete gem index</a>
- </p>
-
- </div>
- </div>
- </div>
- <div id="validator-badges">
- <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
- </div>
- </body>
-</html>
- ERB
-
- def self.run(options)
- new(options[:gemdir], options[:port], options[:daemon],
- options[:launch], options[:addresses]).run
- end
-
- def initialize(gem_dirs, port, daemon, launch = nil, addresses = nil)
- begin
- require 'webrick'
- rescue LoadError
- abort "webrick is not found. You may need to `gem install webrick` to install webrick."
- end
-
- Gem::RDoc.load_rdoc
- Socket.do_not_reverse_lookup = true
-
- @gem_dirs = Array gem_dirs
- @port = port
- @daemon = daemon
- @launch = launch
- @addresses = addresses
-
- logger = WEBrick::Log.new nil, WEBrick::BasicLog::FATAL
- @server = WEBrick::HTTPServer.new :DoNotListen => true, :Logger => logger
-
- @spec_dirs = @gem_dirs.map {|gem_dir| File.join gem_dir, 'specifications' }
- @spec_dirs.reject! {|spec_dir| !File.directory? spec_dir }
-
- reset_gems
-
- @have_rdoc_4_plus = nil
- end
-
- def add_date(res)
- res['date'] = @spec_dirs.map do |spec_dir|
- File.stat(spec_dir).mtime
- end.max
- end
-
- def uri_encode(str)
- str.gsub(URI::UNSAFE) do |match|
- match.each_byte.map {|c| sprintf('%%%02X', c.ord) }.join
- end
- end
-
- def doc_root(gem_name)
- if have_rdoc_4_plus?
- "/doc_root/#{u gem_name}/"
- else
- "/doc_root/#{u gem_name}/rdoc/index.html"
- end
- end
-
- def have_rdoc_4_plus?
- @have_rdoc_4_plus ||=
- Gem::Requirement.new('>= 4.0.0.preview2').satisfied_by? Gem::RDoc.rdoc_version
- end
-
- def latest_specs(req, res)
- reset_gems
-
- res['content-type'] = 'application/x-gzip'
-
- add_date res
-
- latest_specs = Gem::Specification.latest_specs
-
- specs = latest_specs.sort.map do |spec|
- platform = spec.original_platform || Gem::Platform::RUBY
- [spec.name, spec.version, platform]
- end
-
- specs = Marshal.dump specs
-
- if req.path =~ /\.gz$/
- specs = Gem::Util.gzip specs
- res['content-type'] = 'application/x-gzip'
- else
- res['content-type'] = 'application/octet-stream'
- end
-
- if req.request_method == 'HEAD'
- res['content-length'] = specs.length
- else
- res.body << specs
- end
- end
-
- ##
- # Creates server sockets based on the addresses option. If no addresses
- # were given a server socket for all interfaces is created.
-
- def listen(addresses = @addresses)
- addresses = [nil] unless addresses
-
- listeners = 0
-
- addresses.each do |address|
- begin
- @server.listen address, @port
- @server.listeners[listeners..-1].each do |listener|
- host, port = listener.addr.values_at 2, 1
- host = "[#{host}]" if host =~ /:/ # we don't reverse lookup
- say "Server started at http://#{host}:#{port}"
- end
-
- listeners = @server.listeners.length
- rescue SystemCallError
- next
- end
- end
-
- if @server.listeners.empty?
- say "Unable to start a server."
- say "Check for running servers or your --bind and --port arguments"
- terminate_interaction 1
- end
- end
-
- def prerelease_specs(req, res)
- reset_gems
-
- res['content-type'] = 'application/x-gzip'
-
- add_date res
-
- specs = Gem::Specification.select do |spec|
- spec.version.prerelease?
- end.sort.map do |spec|
- platform = spec.original_platform || Gem::Platform::RUBY
- [spec.name, spec.version, platform]
- end
-
- specs = Marshal.dump specs
-
- if req.path =~ /\.gz$/
- specs = Gem::Util.gzip specs
- res['content-type'] = 'application/x-gzip'
- else
- res['content-type'] = 'application/octet-stream'
- end
-
- if req.request_method == 'HEAD'
- res['content-length'] = specs.length
- else
- res.body << specs
- end
- end
-
- def quick(req, res)
- reset_gems
-
- res['content-type'] = 'text/plain'
- add_date res
-
- case req.request_uri.path
- when %r{^/quick/(Marshal.#{Regexp.escape Gem.marshal_version}/)?(.*?)\.gemspec\.rz$} then
- marshal_format, full_name = $1, $2
- specs = Gem::Specification.find_all_by_full_name(full_name)
-
- selector = full_name.inspect
-
- if specs.empty?
- res.status = 404
- res.body = "No gems found matching #{selector}"
- elsif specs.length > 1
- res.status = 500
- res.body = "Multiple gems found matching #{selector}"
- elsif marshal_format
- res['content-type'] = 'application/x-deflate'
- res.body << Gem.deflate(Marshal.dump(specs.first))
- end
- else
- raise WEBrick::HTTPStatus::NotFound, "`#{req.path}' not found."
- end
- end
-
- def root(req, res)
- reset_gems
-
- add_date res
-
- raise WEBrick::HTTPStatus::NotFound, "`#{req.path}' not found." unless
- req.path == '/'
-
- specs = []
- total_file_count = 0
-
- Gem::Specification.each do |spec|
- total_file_count += spec.files.size
- deps = spec.dependencies.map do |dep|
- {
- "name" => dep.name,
- "type" => dep.type,
- "version" => dep.requirement.to_s,
- }
- end
-
- deps = deps.sort_by {|dep| [dep["name"].downcase, dep["version"]] }
- deps.last["is_last"] = true unless deps.empty?
-
- # executables
- executables = spec.executables.sort.collect {|exec| {"executable" => exec} }
- executables = nil if executables.empty?
- executables.last["is_last"] = true if executables
-
- # Pre-process spec homepage for safety reasons
- begin
- homepage_uri = URI.parse(spec.homepage)
- if [URI::HTTP, URI::HTTPS].member? homepage_uri.class
- homepage_uri = spec.homepage
- else
- homepage_uri = "."
- end
- rescue URI::InvalidURIError
- homepage_uri = "."
- end
-
- specs << {
- "authors" => spec.authors.sort.join(", "),
- "date" => spec.date.to_s,
- "dependencies" => deps,
- "doc_path" => doc_root(spec.full_name),
- "executables" => executables,
- "only_one_executable" => (executables && executables.size == 1),
- "full_name" => spec.full_name,
- "has_deps" => !deps.empty?,
- "homepage" => homepage_uri,
- "name" => spec.name,
- "rdoc_installed" => Gem::RDoc.new(spec).rdoc_installed?,
- "ri_installed" => Gem::RDoc.new(spec).ri_installed?,
- "summary" => spec.summary,
- "version" => spec.version.to_s,
- }
- end
-
- specs << {
- "authors" => "Chad Fowler, Rich Kilmer, Jim Weirich, Eric Hodel and others",
- "dependencies" => [],
- "doc_path" => doc_root("rubygems-#{Gem::VERSION}"),
- "executables" => [{"executable" => 'gem', "is_last" => true}],
- "only_one_executable" => true,
- "full_name" => "rubygems-#{Gem::VERSION}",
- "has_deps" => false,
- "homepage" => "https://guides.rubygems.org/",
- "name" => 'rubygems',
- "ri_installed" => true,
- "summary" => "RubyGems itself",
- "version" => Gem::VERSION,
- }
-
- specs = specs.sort_by {|spec| [spec["name"].downcase, spec["version"]] }
- specs.last["is_last"] = true
-
- # tag all specs with first_name_entry
- last_spec = nil
- specs.each do |spec|
- is_first = last_spec.nil? || (last_spec["name"].downcase != spec["name"].downcase)
- spec["first_name_entry"] = is_first
- last_spec = spec
- end
-
- # create page from template
- template = ERB.new(DOC_TEMPLATE)
- res['content-type'] = 'text/html'
-
- values = { "gem_count" => specs.size.to_s, "specs" => specs,
- "total_file_count" => total_file_count.to_s }
-
- # suppress 1.9.3dev warning about unused variable
- values = values
-
- result = template.result binding
- res.body = result
- end
-
- ##
- # Can be used for quick navigation to the rdoc documentation. You can then
- # define a search shortcut for your browser. E.g. in Firefox connect
- # 'shortcut:rdoc' to http://localhost:8808/rdoc?q=%s template. Then you can
- # directly open the ActionPack documentation by typing 'rdoc actionp'. If
- # there are multiple hits for the search term, they are presented as a list
- # with links.
- #
- # Search algorithm aims for an intuitive search:
- # 1. first try to find the gems and documentation folders which name
- # starts with the search term
- # 2. search for entries, that *contain* the search term
- # 3. show all the gems
- #
- # If there is only one search hit, user is immediately redirected to the
- # documentation for the particular gem, otherwise a list with results is
- # shown.
- #
- # === Additional trick - install documentation for Ruby core
- #
- # Note: please adjust paths accordingly use for example 'locate yaml.rb' and
- # 'gem environment' to identify directories, that are specific for your
- # local installation
- #
- # 1. install Ruby sources
- # cd /usr/src
- # sudo apt-get source ruby
- #
- # 2. generate documentation
- # rdoc -o /usr/lib/ruby/gems/1.8/doc/core/rdoc \
- # /usr/lib/ruby/1.8 ruby1.8-1.8.7.72
- #
- # By typing 'rdoc core' you can now access the core documentation
-
- def rdoc(req, res)
- query = req.query['q']
- show_rdoc_for_pattern("#{query}*", res) && return
- show_rdoc_for_pattern("*#{query}*", res) && return
-
- template = ERB.new RDOC_NO_DOCUMENTATION
-
- res['content-type'] = 'text/html'
- res.body = template.result binding
- end
-
- ##
- # Updates the server to use the latest installed gems.
-
- def reset_gems # :nodoc:
- Gem::Specification.dirs = @gem_dirs
- end
-
- ##
- # Returns true and prepares http response, if rdoc for the requested gem
- # name pattern was found.
- #
- # The search is based on the file system content, not on the gems metadata.
- # This allows additional documentation folders like 'core' for the Ruby core
- # documentation - just put it underneath the main doc folder.
-
- def show_rdoc_for_pattern(pattern, res)
- found_gems = Dir.glob("{#{@gem_dirs.join ','}}/doc/#{pattern}").select do |path|
- File.exist? File.join(path, 'rdoc/index.html')
- end
- case found_gems.length
- when 0
- return false
- when 1
- new_path = File.basename(found_gems[0])
- res.status = 302
- res['Location'] = doc_root new_path
- return true
- else
- doc_items = []
- found_gems.each do |file_name|
- base_name = File.basename(file_name)
- doc_items << {
- :name => base_name,
- :url => doc_root(new_path),
- :summary => '',
- }
- end
-
- template = ERB.new(RDOC_SEARCH_TEMPLATE)
- res['content-type'] = 'text/html'
- result = template.result binding
- res.body = result
- return true
- end
- end
-
- def run
- listen
-
- WEBrick::Daemon.start if @daemon
-
- @server.mount_proc "/specs.#{Gem.marshal_version}", method(:specs)
- @server.mount_proc "/specs.#{Gem.marshal_version}.gz", method(:specs)
-
- @server.mount_proc "/latest_specs.#{Gem.marshal_version}",
- method(:latest_specs)
- @server.mount_proc "/latest_specs.#{Gem.marshal_version}.gz",
- method(:latest_specs)
-
- @server.mount_proc "/prerelease_specs.#{Gem.marshal_version}",
- method(:prerelease_specs)
- @server.mount_proc "/prerelease_specs.#{Gem.marshal_version}.gz",
- method(:prerelease_specs)
-
- @server.mount_proc "/quick/", method(:quick)
-
- @server.mount_proc("/gem-server-rdoc-style.css") do |req, res|
- res['content-type'] = 'text/css'
- add_date res
- res.body << RDOC_CSS
- end
-
- @server.mount_proc "/", method(:root)
-
- @server.mount_proc "/rdoc", method(:rdoc)
-
- file_handlers = {
- '/gems' => '/cache/',
- }
-
- if have_rdoc_4_plus?
- @server.mount '/doc_root', RDoc::Servlet, '/doc_root'
- else
- file_handlers['/doc_root'] = '/doc/'
- end
-
- @gem_dirs.each do |gem_dir|
- file_handlers.each do |mount_point, mount_dir|
- @server.mount(mount_point, WEBrick::HTTPServlet::FileHandler,
- File.join(gem_dir, mount_dir), true)
- end
- end
-
- trap("INT") { @server.shutdown; exit! }
- trap("TERM") { @server.shutdown; exit! }
-
- launch if @launch
-
- @server.start
- end
-
- def specs(req, res)
- reset_gems
-
- add_date res
-
- specs = Gem::Specification.sort_by(&:sort_obj).map do |spec|
- platform = spec.original_platform || Gem::Platform::RUBY
- [spec.name, spec.version, platform]
- end
-
- specs = Marshal.dump specs
-
- if req.path =~ /\.gz$/
- specs = Gem::Util.gzip specs
- res['content-type'] = 'application/x-gzip'
- else
- res['content-type'] = 'application/octet-stream'
- end
-
- if req.request_method == 'HEAD'
- res['content-length'] = specs.length
- else
- res.body << specs
- end
- end
-
- def launch
- listeners = @server.listeners.map{|l| l.addr[2] }
-
- # TODO: 0.0.0.0 == any, not localhost.
- host = listeners.any?{|l| l == '0.0.0.0' } ? 'localhost' : listeners.first
-
- say "Launching browser to http://#{host}:#{@port}"
-
- system("#{@launch} http://#{host}:#{@port}")
- end
-end
diff --git a/lib/rubygems/source.rb b/lib/rubygems/source.rb
index a9d91ed18ee..f03e09872ca 100644
--- a/lib/rubygems/source.rb
+++ b/lib/rubygems/source.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require "rubygems/text"
+require_relative "text"
##
# A Source knows how to list and fetch gems from a RubyGems marshal index.
#
diff --git a/lib/rubygems/source/git.rb b/lib/rubygems/source/git.rb
index 9876adc24e9..cda5aa80738 100644
--- a/lib/rubygems/source/git.rb
+++ b/lib/rubygems/source/git.rb
@@ -225,7 +225,7 @@ class Gem::Source::Git < Gem::Source
# A hash for the git gem based on the git repository URI.
def uri_hash # :nodoc:
- require 'digest' # required here to avoid deadlocking in Gem.activate_bin_path (because digest is a gem on 2.5+)
+ require_relative '../openssl'
normalized =
if @repository =~ %r{^\w+://(\w+@)?}
@@ -235,6 +235,6 @@ class Gem::Source::Git < Gem::Source
@repository
end
- Digest::SHA1.hexdigest normalized
+ OpenSSL::Digest::SHA1.hexdigest normalized
end
end
diff --git a/lib/rubygems/specification.rb b/lib/rubygems/specification.rb
index 7ed963430f6..40a5bddff6a 100644
--- a/lib/rubygems/specification.rb
+++ b/lib/rubygems/specification.rb
@@ -102,12 +102,8 @@ class Gem::Specification < Gem::BasicSpecification
today = Time.now.utc
TODAY = Time.utc(today.year, today.month, today.day) # :nodoc:
- # rubocop:disable Style/MutableConstant
- LOAD_CACHE = {} # :nodoc:
- # rubocop:enable Style/MutableConstant
- LOAD_CACHE_MUTEX = Thread::Mutex.new
-
- private_constant :LOAD_CACHE if defined? private_constant
+ @load_cache = {} # :nodoc:
+ @load_cache_mutex = Thread::Mutex.new
VALID_NAME_PATTERN = /\A[a-zA-Z0-9\.\-\_]+\z/.freeze # :nodoc:
@@ -182,13 +178,23 @@ class Gem::Specification < Gem::BasicSpecification
@@default_value[k].nil?
end
- @@stubs = nil
- @@stubs_by_name = {}
+ def self.clear_specs # :nodoc:
+ @@all_specs_mutex.synchronize do
+ @@all = nil
+ @@stubs = nil
+ @@stubs_by_name = {}
+ @@spec_with_requirable_file = {}
+ @@active_stub_with_requirable_file = {}
+ end
+ end
+ private_class_method :clear_specs
+
+ @@all_specs_mutex = Thread::Mutex.new
+
+ clear_specs
# Sentinel object to represent "not found" stubs
NOT_FOUND = Struct.new(:to_spec, :this).new # :nodoc:
- @@spec_with_requirable_file = {}
- @@active_stub_with_requirable_file = {}
# Tracking removed method calls to warn users during build time.
REMOVED_METHODS = [:rubyforge_project=].freeze # :nodoc:
@@ -282,6 +288,15 @@ class Gem::Specification < Gem::BasicSpecification
# :section: Recommended gemspec attributes
##
+ # The version of Ruby required by this gem
+ #
+ # Usage:
+ #
+ # spec.required_ruby_version = '>= 2.7.0'
+
+ attr_reader :required_ruby_version
+
+ ##
# A long description of this gem
#
# The description should be more detailed than the summary but not
@@ -324,17 +339,21 @@ class Gem::Specification < Gem::BasicSpecification
# This should just be the name of your license. The full text of the license
# should be inside of the gem (at the top level) when you build it.
#
- # The simplest way, is to specify the standard SPDX ID
+ # The simplest way is to specify the standard SPDX ID
# https://spdx.org/licenses/ for the license.
- # Ideally you should pick one that is OSI (Open Source Initiative)
+ # Ideally, you should pick one that is OSI (Open Source Initiative)
# http://opensource.org/licenses/alphabetical approved.
#
- # The most commonly used OSI approved licenses are MIT and Apache-2.0.
+ # The most commonly used OSI-approved licenses are MIT and Apache-2.0.
# GitHub also provides a license picker at http://choosealicense.com/.
#
+ # You can also use a custom license file along with your gemspec and specify
+ # a LicenseRef-<idstring>, where idstring is the name of the file containing
+ # the license text.
+ #
# You should specify a license for your gem so that people know how they are
- # permitted to use it, and any restrictions you're placing on it. Not
- # specifying a license means all rights are reserved; others have no rights
+ # permitted to use it and any restrictions you're placing on it. Not
+ # specifying a license means all rights are reserved; others have no right
# to use the code for any purpose.
#
# You can set multiple licenses with #licenses=
@@ -513,11 +532,6 @@ class Gem::Specification < Gem::BasicSpecification
end
##
- # The version of Ruby required by this gem
-
- attr_reader :required_ruby_version
-
- ##
# The RubyGems version required by this gem
attr_reader :required_rubygems_version
@@ -744,23 +758,15 @@ class Gem::Specification < Gem::BasicSpecification
attr_accessor :specification_version
def self._all # :nodoc:
- unless defined?(@@all) && @@all
- @@all = stubs.map(&:to_spec)
-
- # After a reset, make sure already loaded specs
- # are still marked as activated.
- specs = {}
- Gem.loaded_specs.each_value{|s| specs[s] = true }
- @@all.each{|s| s.activated = true if specs[s] }
- end
- @@all
+ @@all_specs_mutex.synchronize { @@all ||= Gem.loaded_specs.values | stubs.map(&:to_spec) }
end
- def self._clear_load_cache # :nodoc:
- LOAD_CACHE_MUTEX.synchronize do
- LOAD_CACHE.clear
+ def self.clear_load_cache # :nodoc:
+ @load_cache_mutex.synchronize do
+ @load_cache.clear
end
end
+ private_class_method :clear_load_cache
def self.each_gemspec(dirs) # :nodoc:
dirs.each do |dir|
@@ -1108,7 +1114,7 @@ class Gem::Specification < Gem::BasicSpecification
def self.load(file)
return unless file
- _spec = LOAD_CACHE_MUTEX.synchronize { LOAD_CACHE[file] }
+ _spec = @load_cache_mutex.synchronize { @load_cache[file] }
return _spec if _spec
file = file.dup.tap(&Gem::UNTAINT)
@@ -1123,12 +1129,12 @@ class Gem::Specification < Gem::BasicSpecification
if Gem::Specification === _spec
_spec.loaded_from = File.expand_path file.to_s
- LOAD_CACHE_MUTEX.synchronize do
- prev = LOAD_CACHE[file]
+ @load_cache_mutex.synchronize do
+ prev = @load_cache[file]
if prev
_spec = prev
else
- LOAD_CACHE[file] = _spec
+ @load_cache[file] = _spec
end
end
return _spec
@@ -1226,12 +1232,8 @@ class Gem::Specification < Gem::BasicSpecification
def self.reset
@@dirs = nil
Gem.pre_reset_hooks.each {|hook| hook.call }
- @@all = nil
- @@stubs = nil
- @@stubs_by_name = {}
- @@spec_with_requirable_file = {}
- @@active_stub_with_requirable_file = {}
- _clear_load_cache
+ clear_specs
+ clear_load_cache
unresolved = unresolved_deps
unless unresolved.empty?
w = "W" + "ARN"
@@ -1556,8 +1558,8 @@ class Gem::Specification < Gem::BasicSpecification
# the gem.build_complete file is missing.
def build_extensions # :nodoc:
- return if default_gem?
return if extensions.empty?
+ return if default_gem?
return if File.exist? gem_build_complete_path
return if !File.writable?(base_dir)
return if !File.exist?(File.join(base_dir, 'extensions'))
@@ -2120,8 +2122,8 @@ class Gem::Specification < Gem::BasicSpecification
# probably want to build_extensions
def missing_extensions?
- return false if default_gem?
return false if extensions.empty?
+ return false if default_gem?
return false if File.exist? gem_build_complete_path
true
diff --git a/lib/rubygems/tsort.rb b/lib/rubygems/tsort.rb
new file mode 100644
index 00000000000..ebe7c3364b7
--- /dev/null
+++ b/lib/rubygems/tsort.rb
@@ -0,0 +1,3 @@
+# frozen_string_literal: true
+
+require_relative 'tsort/lib/tsort'
diff --git a/lib/rubygems/tsort/.document b/lib/rubygems/tsort/.document
new file mode 100644
index 00000000000..0c43bbd6b38
--- /dev/null
+++ b/lib/rubygems/tsort/.document
@@ -0,0 +1 @@
+# Vendored files do not need to be documented
diff --git a/lib/rubygems/tsort/lib/tsort.rb b/lib/rubygems/tsort/lib/tsort.rb
new file mode 100644
index 00000000000..f68c5947d30
--- /dev/null
+++ b/lib/rubygems/tsort/lib/tsort.rb
@@ -0,0 +1,454 @@
+# frozen_string_literal: true
+
+#--
+# tsort.rb - provides a module for topological sorting and strongly connected components.
+#++
+#
+
+#
+# Gem::TSort implements topological sorting using Tarjan's algorithm for
+# strongly connected components.
+#
+# Gem::TSort is designed to be able to be used with any object which can be
+# interpreted as a directed graph.
+#
+# Gem::TSort requires two methods to interpret an object as a graph,
+# tsort_each_node and tsort_each_child.
+#
+# * tsort_each_node is used to iterate for all nodes over a graph.
+# * tsort_each_child is used to iterate for child nodes of a given node.
+#
+# The equality of nodes are defined by eql? and hash since
+# Gem::TSort uses Hash internally.
+#
+# == A Simple Example
+#
+# The following example demonstrates how to mix the Gem::TSort module into an
+# existing class (in this case, Hash). Here, we're treating each key in
+# the hash as a node in the graph, and so we simply alias the required
+# #tsort_each_node method to Hash's #each_key method. For each key in the
+# hash, the associated value is an array of the node's child nodes. This
+# choice in turn leads to our implementation of the required #tsort_each_child
+# method, which fetches the array of child nodes and then iterates over that
+# array using the user-supplied block.
+#
+# require 'rubygems/tsort/lib/tsort'
+#
+# class Hash
+# include Gem::TSort
+# alias tsort_each_node each_key
+# def tsort_each_child(node, &block)
+# fetch(node).each(&block)
+# end
+# end
+#
+# {1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort
+# #=> [3, 2, 1, 4]
+#
+# {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components
+# #=> [[4], [2, 3], [1]]
+#
+# == A More Realistic Example
+#
+# A very simple `make' like tool can be implemented as follows:
+#
+# require 'rubygems/tsort/lib/tsort'
+#
+# class Make
+# def initialize
+# @dep = {}
+# @dep.default = []
+# end
+#
+# def rule(outputs, inputs=[], &block)
+# triple = [outputs, inputs, block]
+# outputs.each {|f| @dep[f] = [triple]}
+# @dep[triple] = inputs
+# end
+#
+# def build(target)
+# each_strongly_connected_component_from(target) {|ns|
+# if ns.length != 1
+# fs = ns.delete_if {|n| Array === n}
+# raise Gem::TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}")
+# end
+# n = ns.first
+# if Array === n
+# outputs, inputs, block = n
+# inputs_time = inputs.map {|f| File.mtime f}.max
+# begin
+# outputs_time = outputs.map {|f| File.mtime f}.min
+# rescue Errno::ENOENT
+# outputs_time = nil
+# end
+# if outputs_time == nil ||
+# inputs_time != nil && outputs_time <= inputs_time
+# sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i
+# block.call
+# end
+# end
+# }
+# end
+#
+# def tsort_each_child(node, &block)
+# @dep[node].each(&block)
+# end
+# include Gem::TSort
+# end
+#
+# def command(arg)
+# print arg, "\n"
+# system arg
+# end
+#
+# m = Make.new
+# m.rule(%w[t1]) { command 'date > t1' }
+# m.rule(%w[t2]) { command 'date > t2' }
+# m.rule(%w[t3]) { command 'date > t3' }
+# m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' }
+# m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' }
+# m.build('t5')
+#
+# == Bugs
+#
+# * 'tsort.rb' is wrong name because this library uses
+# Tarjan's algorithm for strongly connected components.
+# Although 'strongly_connected_components.rb' is correct but too long.
+#
+# == References
+#
+# R. E. Tarjan, "Depth First Search and Linear Graph Algorithms",
+# <em>SIAM Journal on Computing</em>, Vol. 1, No. 2, pp. 146-160, June 1972.
+#
+
+module Gem
+ module TSort
+ class Cyclic < StandardError
+ end
+
+ # Returns a topologically sorted array of nodes.
+ # The array is sorted from children to parents, i.e.
+ # the first element has no child and the last node has no parent.
+ #
+ # If there is a cycle, Gem::TSort::Cyclic is raised.
+ #
+ # class G
+ # include Gem::TSort
+ # def initialize(g)
+ # @g = g
+ # end
+ # def tsort_each_child(n, &b) @g[n].each(&b) end
+ # def tsort_each_node(&b) @g.each_key(&b) end
+ # end
+ #
+ # graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
+ # p graph.tsort #=> [4, 2, 3, 1]
+ #
+ # graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
+ # p graph.tsort # raises Gem::TSort::Cyclic
+ #
+ def tsort
+ each_node = method(:tsort_each_node)
+ each_child = method(:tsort_each_child)
+ Gem::TSort.tsort(each_node, each_child)
+ end
+
+ # Returns a topologically sorted array of nodes.
+ # The array is sorted from children to parents, i.e.
+ # the first element has no child and the last node has no parent.
+ #
+ # The graph is represented by _each_node_ and _each_child_.
+ # _each_node_ should have +call+ method which yields for each node in the graph.
+ # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
+ #
+ # If there is a cycle, Gem::TSort::Cyclic is raised.
+ #
+ # g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # p Gem::TSort.tsort(each_node, each_child) #=> [4, 2, 3, 1]
+ #
+ # g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # p Gem::TSort.tsort(each_node, each_child) # raises Gem::TSort::Cyclic
+ #
+ def TSort.tsort(each_node, each_child)
+ Gem::TSort.tsort_each(each_node, each_child).to_a
+ end
+
+ # The iterator version of the #tsort method.
+ # <tt><em>obj</em>.tsort_each</tt> is similar to <tt><em>obj</em>.tsort.each</tt>, but
+ # modification of _obj_ during the iteration may lead to unexpected results.
+ #
+ # #tsort_each returns +nil+.
+ # If there is a cycle, Gem::TSort::Cyclic is raised.
+ #
+ # class G
+ # include Gem::TSort
+ # def initialize(g)
+ # @g = g
+ # end
+ # def tsort_each_child(n, &b) @g[n].each(&b) end
+ # def tsort_each_node(&b) @g.each_key(&b) end
+ # end
+ #
+ # graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
+ # graph.tsort_each {|n| p n }
+ # #=> 4
+ # # 2
+ # # 3
+ # # 1
+ #
+ def tsort_each(&block) # :yields: node
+ each_node = method(:tsort_each_node)
+ each_child = method(:tsort_each_child)
+ Gem::TSort.tsort_each(each_node, each_child, &block)
+ end
+
+ # The iterator version of the Gem::TSort.tsort method.
+ #
+ # The graph is represented by _each_node_ and _each_child_.
+ # _each_node_ should have +call+ method which yields for each node in the graph.
+ # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
+ #
+ # g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # Gem::TSort.tsort_each(each_node, each_child) {|n| p n }
+ # #=> 4
+ # # 2
+ # # 3
+ # # 1
+ #
+ def TSort.tsort_each(each_node, each_child) # :yields: node
+ return to_enum(__method__, each_node, each_child) unless block_given?
+
+ Gem::TSort.each_strongly_connected_component(each_node, each_child) {|component|
+ if component.size == 1
+ yield component.first
+ else
+ raise Cyclic.new("topological sort failed: #{component.inspect}")
+ end
+ }
+ end
+
+ # Returns strongly connected components as an array of arrays of nodes.
+ # The array is sorted from children to parents.
+ # Each elements of the array represents a strongly connected component.
+ #
+ # class G
+ # include Gem::TSort
+ # def initialize(g)
+ # @g = g
+ # end
+ # def tsort_each_child(n, &b) @g[n].each(&b) end
+ # def tsort_each_node(&b) @g.each_key(&b) end
+ # end
+ #
+ # graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
+ # p graph.strongly_connected_components #=> [[4], [2], [3], [1]]
+ #
+ # graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
+ # p graph.strongly_connected_components #=> [[4], [2, 3], [1]]
+ #
+ def strongly_connected_components
+ each_node = method(:tsort_each_node)
+ each_child = method(:tsort_each_child)
+ Gem::TSort.strongly_connected_components(each_node, each_child)
+ end
+
+ # Returns strongly connected components as an array of arrays of nodes.
+ # The array is sorted from children to parents.
+ # Each elements of the array represents a strongly connected component.
+ #
+ # The graph is represented by _each_node_ and _each_child_.
+ # _each_node_ should have +call+ method which yields for each node in the graph.
+ # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
+ #
+ # g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # p Gem::TSort.strongly_connected_components(each_node, each_child)
+ # #=> [[4], [2], [3], [1]]
+ #
+ # g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # p Gem::TSort.strongly_connected_components(each_node, each_child)
+ # #=> [[4], [2, 3], [1]]
+ #
+ def TSort.strongly_connected_components(each_node, each_child)
+ Gem::TSort.each_strongly_connected_component(each_node, each_child).to_a
+ end
+
+ # The iterator version of the #strongly_connected_components method.
+ # <tt><em>obj</em>.each_strongly_connected_component</tt> is similar to
+ # <tt><em>obj</em>.strongly_connected_components.each</tt>, but
+ # modification of _obj_ during the iteration may lead to unexpected results.
+ #
+ # #each_strongly_connected_component returns +nil+.
+ #
+ # class G
+ # include Gem::TSort
+ # def initialize(g)
+ # @g = g
+ # end
+ # def tsort_each_child(n, &b) @g[n].each(&b) end
+ # def tsort_each_node(&b) @g.each_key(&b) end
+ # end
+ #
+ # graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
+ # graph.each_strongly_connected_component {|scc| p scc }
+ # #=> [4]
+ # # [2]
+ # # [3]
+ # # [1]
+ #
+ # graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
+ # graph.each_strongly_connected_component {|scc| p scc }
+ # #=> [4]
+ # # [2, 3]
+ # # [1]
+ #
+ def each_strongly_connected_component(&block) # :yields: nodes
+ each_node = method(:tsort_each_node)
+ each_child = method(:tsort_each_child)
+ Gem::TSort.each_strongly_connected_component(each_node, each_child, &block)
+ end
+
+ # The iterator version of the Gem::TSort.strongly_connected_components method.
+ #
+ # The graph is represented by _each_node_ and _each_child_.
+ # _each_node_ should have +call+ method which yields for each node in the graph.
+ # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
+ #
+ # g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # Gem::TSort.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
+ # #=> [4]
+ # # [2]
+ # # [3]
+ # # [1]
+ #
+ # g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
+ # each_node = lambda {|&b| g.each_key(&b) }
+ # each_child = lambda {|n, &b| g[n].each(&b) }
+ # Gem::TSort.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
+ # #=> [4]
+ # # [2, 3]
+ # # [1]
+ #
+ def TSort.each_strongly_connected_component(each_node, each_child) # :yields: nodes
+ return to_enum(__method__, each_node, each_child) unless block_given?
+
+ id_map = {}
+ stack = []
+ each_node.call {|node|
+ unless id_map.include? node
+ Gem::TSort.each_strongly_connected_component_from(node, each_child, id_map, stack) {|c|
+ yield c
+ }
+ end
+ }
+ nil
+ end
+
+ # Iterates over strongly connected component in the subgraph reachable from
+ # _node_.
+ #
+ # Return value is unspecified.
+ #
+ # #each_strongly_connected_component_from doesn't call #tsort_each_node.
+ #
+ # class G
+ # include Gem::TSort
+ # def initialize(g)
+ # @g = g
+ # end
+ # def tsort_each_child(n, &b) @g[n].each(&b) end
+ # def tsort_each_node(&b) @g.each_key(&b) end
+ # end
+ #
+ # graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
+ # graph.each_strongly_connected_component_from(2) {|scc| p scc }
+ # #=> [4]
+ # # [2]
+ #
+ # graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
+ # graph.each_strongly_connected_component_from(2) {|scc| p scc }
+ # #=> [4]
+ # # [2, 3]
+ #
+ def each_strongly_connected_component_from(node, id_map={}, stack=[], &block) # :yields: nodes
+ Gem::TSort.each_strongly_connected_component_from(node, method(:tsort_each_child), id_map, stack, &block)
+ end
+
+ # Iterates over strongly connected components in a graph.
+ # The graph is represented by _node_ and _each_child_.
+ #
+ # _node_ is the first node.
+ # _each_child_ should have +call+ method which takes a node argument
+ # and yields for each child node.
+ #
+ # Return value is unspecified.
+ #
+ # #Gem::TSort.each_strongly_connected_component_from is a class method and
+ # it doesn't need a class to represent a graph which includes Gem::TSort.
+ #
+ # graph = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
+ # each_child = lambda {|n, &b| graph[n].each(&b) }
+ # Gem::TSort.each_strongly_connected_component_from(1, each_child) {|scc|
+ # p scc
+ # }
+ # #=> [4]
+ # # [2, 3]
+ # # [1]
+ #
+ def TSort.each_strongly_connected_component_from(node, each_child, id_map={}, stack=[]) # :yields: nodes
+ return to_enum(__method__, node, each_child, id_map, stack) unless block_given?
+
+ minimum_id = node_id = id_map[node] = id_map.size
+ stack_length = stack.length
+ stack << node
+
+ each_child.call(node) {|child|
+ if id_map.include? child
+ child_id = id_map[child]
+ minimum_id = child_id if child_id && child_id < minimum_id
+ else
+ sub_minimum_id =
+ Gem::TSort.each_strongly_connected_component_from(child, each_child, id_map, stack) {|c|
+ yield c
+ }
+ minimum_id = sub_minimum_id if sub_minimum_id < minimum_id
+ end
+ }
+
+ if node_id == minimum_id
+ component = stack.slice!(stack_length .. -1)
+ component.each {|n| id_map[n] = nil}
+ yield component
+ end
+
+ minimum_id
+ end
+
+ # Should be implemented by a extended class.
+ #
+ # #tsort_each_node is used to iterate for all nodes over a graph.
+ #
+ def tsort_each_node # :yields: node
+ raise NotImplementedError.new
+ end
+
+ # Should be implemented by a extended class.
+ #
+ # #tsort_each_child is used to iterate for child nodes of _node_.
+ #
+ def tsort_each_child(node) # :yields: child
+ raise NotImplementedError.new
+ end
+ end
+end
diff --git a/lib/rubygems/util.rb b/lib/rubygems/util.rb
index 2a55305172e..4363c5adce0 100644
--- a/lib/rubygems/util.rb
+++ b/lib/rubygems/util.rb
@@ -1,5 +1,5 @@
# frozen_string_literal: true
-require 'rubygems/deprecate'
+require_relative 'deprecate'
##
# This module contains various utility methods as module methods.
diff --git a/lib/rubygems/util/licenses.rb b/lib/rubygems/util/licenses.rb
index 8de5b11ae38..3f4178c6e05 100644
--- a/lib/rubygems/util/licenses.rb
+++ b/lib/rubygems/util/licenses.rb
@@ -5,6 +5,7 @@ class Gem::Licenses
extend Gem::Text
NONSTANDARD = 'Nonstandard'.freeze
+ LICENSE_REF = 'LicenseRef-.+'.freeze
# Software Package Data Exchange (SPDX) standard open-source software
# license identifiers
@@ -523,6 +524,7 @@ class Gem::Licenses
\+?
(?:\s WITH \s #{Regexp.union(EXCEPTION_IDENTIFIERS)})?
| #{NONSTANDARD}
+ | #{LICENSE_REF}
)
\Z
}ox.freeze
diff --git a/lib/rubygems/version.rb b/lib/rubygems/version.rb
index 20bbff4fdd5..37fd71edc06 100644
--- a/lib/rubygems/version.rb
+++ b/lib/rubygems/version.rb
@@ -149,6 +149,15 @@
# For the last example, single-digit versions are automatically extended with
# a zero to give a sensible result.
+# Our code style opens classes directly without opening the intermediate
+# modules. This works because tha main entrypoint `rubygems.rb`, which defines
+# the root `Gem` module, is usually required first. But in this case we want to
+# allow using `Gem::Version` without loading the rest of rubygems, so we
+# explicit define the `Gem` placeholder module first.
+module Gem; end
+
+require_relative "deprecate"
+
class Gem::Version
autoload :Requirement, File.expand_path('requirement', __dir__)
diff --git a/lib/rubygems/version_option.rb b/lib/rubygems/version_option.rb
index eabe4fdb576..1db382fa7f9 100644
--- a/lib/rubygems/version_option.rb
+++ b/lib/rubygems/version_option.rb
@@ -16,7 +16,7 @@ module Gem::VersionOption
# Add the --platform option to the option parser.
def add_platform_option(task = command, *wrap)
- OptionParser.accept Gem::Platform do |value|
+ Gem::OptionParser.accept Gem::Platform do |value|
if value == Gem::Platform::RUBY
value
else
@@ -51,7 +51,7 @@ module Gem::VersionOption
# Add the --version option to the option parser.
def add_version_option(task = command, *wrap)
- OptionParser.accept Gem::Requirement do |value|
+ Gem::OptionParser.accept Gem::Requirement do |value|
Gem::Requirement.new(*value.split(/\s*,\s*/))
end
diff --git a/lib/securerandom.gemspec b/lib/securerandom.gemspec
index 358dc580568..522fbaced79 100644
--- a/lib/securerandom.gemspec
+++ b/lib/securerandom.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |spec|
spec.name = "securerandom"
- spec.version = "0.1.0"
+ spec.version = "0.1.1"
spec.authors = ["Tanaka Akira"]
spec.email = ["akr@fsij.org"]
diff --git a/lib/set/set.gemspec b/lib/set/set.gemspec
index d14febaad4a..83100df7850 100644
--- a/lib/set/set.gemspec
+++ b/lib/set/set.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |spec|
spec.name = "set"
- spec.version = "1.0.1"
+ spec.version = "1.0.2"
spec.authors = ["Akinori MUSHA"]
spec.email = ["knu@idaemons.org"]
diff --git a/lib/tempfile.gemspec b/lib/tempfile.gemspec
index 4917b997e7f..c4f28b2ef70 100644
--- a/lib/tempfile.gemspec
+++ b/lib/tempfile.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |spec|
spec.name = "tempfile"
- spec.version = "0.1.1"
+ spec.version = "0.1.2"
spec.authors = ["Yukihiro Matsumoto"]
spec.email = ["matz@ruby-lang.org"]
diff --git a/lib/time.gemspec b/lib/time.gemspec
index 040b9f34cf4..72fba34204b 100644
--- a/lib/time.gemspec
+++ b/lib/time.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |spec|
spec.name = "time"
- spec.version = "0.1.0"
+ spec.version = "0.2.0"
spec.authors = ["Tanaka Akira"]
spec.email = ["akr@fsij.org"]
diff --git a/lib/timeout.rb b/lib/timeout.rb
index 6a7f538f994..f50e706d4b8 100644
--- a/lib/timeout.rb
+++ b/lib/timeout.rb
@@ -23,7 +23,7 @@
# Copyright:: (C) 2000 Information-technology Promotion Agency, Japan
module Timeout
- VERSION = "0.1.1".freeze
+ VERSION = "0.2.0".freeze
# Raised by Timeout.timeout when the block times out.
class Error < RuntimeError
diff --git a/lib/tmpdir.rb b/lib/tmpdir.rb
index bf7db5282ac..3b671640392 100644
--- a/lib/tmpdir.rb
+++ b/lib/tmpdir.rb
@@ -69,7 +69,7 @@ class Dir
#
# Dir.mktmpdir {|dir|
# # use the directory...
- # open("#{dir}/foo", "w") { ... }
+ # open("#{dir}/foo", "w") { something using the file }
# }
#
# If a block is not given,
@@ -79,7 +79,7 @@ class Dir
# dir = Dir.mktmpdir
# begin
# # use the directory...
- # open("#{dir}/foo", "w") { ... }
+ # open("#{dir}/foo", "w") { something using the file }
# ensure
# # remove the directory.
# FileUtils.remove_entry dir
diff --git a/lib/uri/http.rb b/lib/uri/http.rb
index 6e9c963ef10..306daf19656 100644
--- a/lib/uri/http.rb
+++ b/lib/uri/http.rb
@@ -80,6 +80,45 @@ module URI
url = @query ? "#@path?#@query" : @path.dup
url.start_with?(?/.freeze) ? url : ?/ + url
end
+
+ #
+ # == Description
+ #
+ # Returns the authority for an HTTP uri, as defined in
+ # https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.
+ #
+ #
+ # Example:
+ #
+ # URI::HTTP.build(host: 'www.example.com', path: '/foo/bar').authority #=> "www.example.com"
+ # URI::HTTP.build(host: 'www.example.com', port: 8000, path: '/foo/bar').authority #=> "www.example.com:8000"
+ # URI::HTTP.build(host: 'www.example.com', port: 80, path: '/foo/bar').authority #=> "www.example.com"
+ #
+ def authority
+ if port == default_port
+ host
+ else
+ "#{host}:#{port}"
+ end
+ end
+
+ #
+ # == Description
+ #
+ # Returns the origin for an HTTP uri, as defined in
+ # https://datatracker.ietf.org/doc/html/rfc6454.
+ #
+ #
+ # Example:
+ #
+ # URI::HTTP.build(host: 'www.example.com', path: '/foo/bar').origin #=> "http://www.example.com"
+ # URI::HTTP.build(host: 'www.example.com', port: 8000, path: '/foo/bar').origin #=> "http://www.example.com:8000"
+ # URI::HTTP.build(host: 'www.example.com', port: 80, path: '/foo/bar').origin #=> "http://www.example.com"
+ # URI::HTTPS.build(host: 'www.example.com', path: '/foo/bar').origin #=> "https://www.example.com"
+ #
+ def origin
+ "#{scheme}://#{authority}"
+ end
end
register_scheme 'HTTP', HTTP
diff --git a/lib/uri/version.rb b/lib/uri/version.rb
index 41da51d844c..82188e25ada 100644
--- a/lib/uri/version.rb
+++ b/lib/uri/version.rb
@@ -1,6 +1,6 @@
module URI
# :stopdoc:
- VERSION_CODE = '001001'.freeze
+ VERSION_CODE = '001100'.freeze
VERSION = VERSION_CODE.scan(/../).collect{|n| n.to_i}.join('.').freeze
# :startdoc:
end
diff --git a/lib/yaml/yaml.gemspec b/lib/yaml/yaml.gemspec
index cf19b0e0da1..e8f20b8c2e3 100644
--- a/lib/yaml/yaml.gemspec
+++ b/lib/yaml/yaml.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |spec|
spec.name = "yaml"
- spec.version = "0.1.1"
+ spec.version = "0.2.0"
spec.authors = ["Aaron Patterson", "SHIBATA Hiroshi"]
spec.email = ["aaron@tenderlovemaking.com", "hsbt@ruby-lang.org"]