Merge master branch from rubygems/rubygems upstream.

* Enable Style/MethodDefParentheses in Rubocop
    https://github.com/rubygems/rubygems/pull/2478
  * Enable Style/MultilineIfThen in Rubocop
    https://github.com/rubygems/rubygems/pull/2479
  * Fix required_ruby_version with prereleases and improve error message
    https://github.com/rubygems/rubygems/pull/2344
  * Fix bundler rubygems binstub not properly looking for bundler
    https://github.com/rubygems/rubygems/pull/2426

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@65904 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
hsbt 2018-11-21 10:20:47 +00:00
Родитель 2f023c5dba
Коммит 5335ce0e06
247 изменённых файлов: 1290 добавлений и 1363 удалений

Просмотреть файл

@ -202,7 +202,7 @@ module Gem
# activation succeeded or wasn't needed because it was already # activation succeeded or wasn't needed because it was already
# activated. Returns false if it can't find the path in a gem. # activated. Returns false if it can't find the path in a gem.
def self.try_activate path def self.try_activate(path)
# finds the _latest_ version... regardless of loaded specs and their deps # finds the _latest_ version... regardless of loaded specs and their deps
# if another gem had a requirement that would mean we shouldn't # if another gem had a requirement that would mean we shouldn't
# activate the latest version, then either it would already be activated # activate the latest version, then either it would already be activated
@ -262,19 +262,14 @@ module Gem
find_spec_for_exe(name, exec_name, requirements).bin_file exec_name find_spec_for_exe(name, exec_name, requirements).bin_file exec_name
end end
def self.find_spec_for_exe name, exec_name, requirements def self.find_spec_for_exe(name, exec_name, requirements)
dep = Gem::Dependency.new name, requirements dep = Gem::Dependency.new name, requirements
loaded = Gem.loaded_specs[name] loaded = Gem.loaded_specs[name]
return loaded if loaded && dep.matches_spec?(loaded) return loaded if loaded && dep.matches_spec?(loaded)
find_specs = proc { dep.matching_specs(true) } specs = dep.matching_specs(true)
if dep.to_s == "bundler (>= 0.a)"
specs = Gem::BundlerVersionFinder.without_filtering(&find_specs)
else
specs = find_specs.call
end
specs = specs.find_all { |spec| specs = specs.find_all { |spec|
spec.executables.include? exec_name spec.executables.include? exec_name
@ -303,7 +298,7 @@ module Gem
# #
# This method should *only* be used in bin stub files. # This method should *only* be used in bin stub files.
def self.activate_bin_path name, exec_name, requirement # :nodoc: def self.activate_bin_path(name, exec_name, requirement) # :nodoc:
spec = find_spec_for_exe name, exec_name, [requirement] spec = find_spec_for_exe name, exec_name, [requirement]
Gem::LOADED_SPECS_MUTEX.synchronize do Gem::LOADED_SPECS_MUTEX.synchronize do
spec.activate spec.activate
@ -446,7 +441,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
# #
# World-writable directories will never be created. # World-writable directories will never be created.
def self.ensure_gem_subdirectories dir = Gem.dir, mode = nil def self.ensure_gem_subdirectories(dir = Gem.dir, mode = nil)
ensure_subdirectories(dir, mode, REPOSITORY_SUBDIRECTORIES) ensure_subdirectories(dir, mode, REPOSITORY_SUBDIRECTORIES)
end end
@ -459,11 +454,11 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
# #
# World-writable directories will never be created. # World-writable directories will never be created.
def self.ensure_default_gem_subdirectories dir = Gem.dir, mode = nil def self.ensure_default_gem_subdirectories(dir = Gem.dir, mode = nil)
ensure_subdirectories(dir, mode, REPOSITORY_DEFAULT_GEM_SUBDIRECTORIES) ensure_subdirectories(dir, mode, REPOSITORY_DEFAULT_GEM_SUBDIRECTORIES)
end end
def self.ensure_subdirectories dir, mode, subdirs # :nodoc: def self.ensure_subdirectories(dir, mode, subdirs) # :nodoc:
old_umask = File.umask old_umask = File.umask
File.umask old_umask | 002 File.umask old_umask | 002
@ -487,7 +482,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
# distinction as extensions cannot be shared between the two. # distinction as extensions cannot be shared between the two.
def self.extension_api_version # :nodoc: def self.extension_api_version # :nodoc:
if 'no' == RbConfig::CONFIG['ENABLE_SHARED'] then if 'no' == RbConfig::CONFIG['ENABLE_SHARED']
"#{ruby_api_version}-static" "#{ruby_api_version}-static"
else else
ruby_api_version ruby_api_version
@ -524,7 +519,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
return files return files
end end
def self.find_files_from_load_path glob # :nodoc: def self.find_files_from_load_path(glob) # :nodoc:
glob_with_suffixes = "#{glob}#{Gem.suffix_pattern}" glob_with_suffixes = "#{glob}#{Gem.suffix_pattern}"
$LOAD_PATH.map { |load_path| $LOAD_PATH.map { |load_path|
Gem::Util.glob_files_in_dir(glob_with_suffixes, load_path) Gem::Util.glob_files_in_dir(glob_with_suffixes, load_path)
@ -579,7 +574,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
def self.find_home def self.find_home
Dir.home Dir.home
rescue rescue
if Gem.win_platform? then if Gem.win_platform?
File.expand_path File.join(ENV['HOMEDRIVE'] || ENV['SystemDrive'], '/') File.expand_path File.join(ENV['HOMEDRIVE'] || ENV['SystemDrive'], '/')
else else
File.expand_path "/" File.expand_path "/"
@ -634,7 +629,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
# Fetching: minitest-3.0.1.gem (100%) # Fetching: minitest-3.0.1.gem (100%)
# => [#<Gem::Specification:0x1013b4528 @name="minitest", ...>] # => [#<Gem::Specification:0x1013b4528 @name="minitest", ...>]
def self.install name, version = Gem::Requirement.default, *options def self.install(name, version = Gem::Requirement.default, *options)
require "rubygems/dependency_installer" require "rubygems/dependency_installer"
inst = Gem::DependencyInstaller.new(*options) inst = Gem::DependencyInstaller.new(*options)
inst.install name, version inst.install name, version
@ -652,7 +647,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
## Set the default RubyGems API host. ## Set the default RubyGems API host.
def self.host= host def self.host=(host)
# TODO: move to utils # TODO: move to utils
@host = host @host = host
end end
@ -841,7 +836,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
if prefix != File.expand_path(RbConfig::CONFIG['sitelibdir']) and if prefix != File.expand_path(RbConfig::CONFIG['sitelibdir']) and
prefix != File.expand_path(RbConfig::CONFIG['libdir']) and prefix != File.expand_path(RbConfig::CONFIG['libdir']) and
'lib' == File.basename(RUBYGEMS_DIR) then 'lib' == File.basename(RUBYGEMS_DIR)
prefix prefix
end end
end end
@ -899,7 +894,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
# The path to the running Ruby interpreter. # The path to the running Ruby interpreter.
def self.ruby def self.ruby
if @ruby.nil? then if @ruby.nil?
@ruby = File.join(RbConfig::CONFIG['bindir'], @ruby = File.join(RbConfig::CONFIG['bindir'],
"#{RbConfig::CONFIG['ruby_install_name']}#{RbConfig::CONFIG['EXEEXT']}") "#{RbConfig::CONFIG['ruby_install_name']}#{RbConfig::CONFIG['EXEEXT']}")
@ -928,7 +923,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
## ##
# Returns the latest release-version specification for the gem +name+. # Returns the latest release-version specification for the gem +name+.
def self.latest_spec_for name def self.latest_spec_for(name)
dependency = Gem::Dependency.new name dependency = Gem::Dependency.new name
fetcher = Gem::SpecFetcher.fetcher fetcher = Gem::SpecFetcher.fetcher
spec_tuples, = fetcher.spec_for_dependency dependency spec_tuples, = fetcher.spec_for_dependency dependency
@ -949,7 +944,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
## ##
# Returns the version of the latest release-version of gem +name+ # Returns the version of the latest release-version of gem +name+
def self.latest_version_for name def self.latest_version_for(name)
spec = latest_spec_for name spec = latest_spec_for name
spec and spec.version spec and spec.version
end end
@ -961,10 +956,15 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
return @ruby_version if defined? @ruby_version return @ruby_version if defined? @ruby_version
version = RUBY_VERSION.dup version = RUBY_VERSION.dup
if defined?(RUBY_PATCHLEVEL) && RUBY_PATCHLEVEL != -1 then if defined?(RUBY_PATCHLEVEL) && RUBY_PATCHLEVEL != -1
version << ".#{RUBY_PATCHLEVEL}" version << ".#{RUBY_PATCHLEVEL}"
elsif defined?(RUBY_REVISION) then elsif defined?(RUBY_DESCRIPTION)
version << ".dev.#{RUBY_REVISION}" if RUBY_ENGINE == "ruby"
desc = RUBY_DESCRIPTION[/\Aruby #{Regexp.quote(RUBY_VERSION)}([^ ]+) /, 1]
else
desc = RUBY_DESCRIPTION[/\A#{RUBY_ENGINE} #{Regexp.quote(RUBY_ENGINE_VERSION)} \(#{RUBY_VERSION}([^ ]+)\) /, 1]
end
version << ".#{desc}" if desc
end end
@ruby_version = Gem::Version.new version @ruby_version = Gem::Version.new version
@ -994,7 +994,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
# DOC: This comment is not documentation about the method itself, it's # DOC: This comment is not documentation about the method itself, it's
# more of a code comment about the implementation. # more of a code comment about the implementation.
def self.sources= new_sources def self.sources=(new_sources)
if !new_sources if !new_sources
@sources = nil @sources = nil
else else
@ -1071,7 +1071,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
# Is this a windows platform? # Is this a windows platform?
def self.win_platform? def self.win_platform?
if @@win_platform.nil? then if @@win_platform.nil?
ruby_platform = RbConfig::CONFIG['host_os'] ruby_platform = RbConfig::CONFIG['host_os']
@@win_platform = !!WIN_PATTERNS.find { |r| ruby_platform =~ r } @@win_platform = !!WIN_PATTERNS.find { |r| ruby_platform =~ r }
end end
@ -1082,7 +1082,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
## ##
# Load +plugins+ as Ruby files # Load +plugins+ as Ruby files
def self.load_plugin_files plugins # :nodoc: def self.load_plugin_files(plugins) # :nodoc:
plugins.each do |plugin| plugins.each do |plugin|
# Skip older versions of the GemCutter plugin: Its commands are in # Skip older versions of the GemCutter plugin: Its commands are in
@ -1151,7 +1151,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
# execution of arbitrary code when used from directories outside your # execution of arbitrary code when used from directories outside your
# control. # control.
def self.use_gemdeps path = nil def self.use_gemdeps(path = nil)
raise_exception = path raise_exception = path
path ||= ENV['RUBYGEMS_GEMDEPS'] path ||= ENV['RUBYGEMS_GEMDEPS']
@ -1159,7 +1159,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
path = path.dup path = path.dup
if path == "-" then if path == "-"
Gem::Util.traverse_parents Dir.pwd do |directory| Gem::Util.traverse_parents Dir.pwd do |directory|
dep_file = GEM_DEP_FILES.find { |f| File.file?(f) } dep_file = GEM_DEP_FILES.find { |f| File.file?(f) }
@ -1172,7 +1172,7 @@ An Array (#{env.inspect}) was passed in from #{caller[3]}
path.untaint path.untaint
unless File.file? path then unless File.file? path
return unless raise_exception return unless raise_exception
raise ArgumentError, "Unable to find gem dependencies file at #{path}" raise ArgumentError, "Unable to find gem dependencies file at #{path}"
@ -1376,7 +1376,7 @@ begin
rescue LoadError rescue LoadError
end end
if defined?(RUBY_ENGINE) then if defined?(RUBY_ENGINE)
begin begin
## ##
# Defaults the Ruby implementation wants to provide for RubyGems # Defaults the Ruby implementation wants to provide for RubyGems

Просмотреть файл

@ -103,7 +103,7 @@ class Gem::AvailableSet
# Other options are :shallow for only direct development dependencies of the # Other options are :shallow for only direct development dependencies of the
# gems in this set or :all for all development dependencies. # gems in this set or :all for all development dependencies.
def to_request_set development = :none def to_request_set(development = :none)
request_set = Gem::RequestSet.new request_set = Gem::RequestSet.new
request_set.development = :all == development request_set.development = :all == development

Просмотреть файл

@ -65,10 +65,10 @@ class Gem::BasicSpecification
## ##
# Return true if this spec can require +file+. # Return true if this spec can require +file+.
def contains_requirable_file? file def contains_requirable_file?(file)
if @ignored then if @ignored
return false return false
elsif missing_extensions? then elsif missing_extensions?
@ignored = true @ignored = true
warn "Ignoring #{full_name} because its extensions are not built. " + warn "Ignoring #{full_name} because its extensions are not built. " +
@ -124,7 +124,7 @@ class Gem::BasicSpecification
# default Ruby platform. # default Ruby platform.
def full_name def full_name
if platform == Gem::Platform::RUBY or platform.nil? then if platform == Gem::Platform::RUBY or platform.nil?
"#{name}-#{version}".dup.untaint "#{name}-#{version}".dup.untaint
else else
"#{name}-#{version}-#{platform}".dup.untaint "#{name}-#{version}-#{platform}".dup.untaint
@ -160,8 +160,8 @@ class Gem::BasicSpecification
# Full path of the target library file. # Full path of the target library file.
# If the file is not in this gem, return nil. # If the file is not in this gem, return nil.
def to_fullpath path def to_fullpath(path)
if activated? then if activated?
@paths_map ||= {} @paths_map ||= {}
@paths_map[path] ||= @paths_map[path] ||=
begin begin
@ -249,7 +249,7 @@ class Gem::BasicSpecification
def source_paths def source_paths
paths = raw_require_paths.dup paths = raw_require_paths.dup
if have_extensions? then if have_extensions?
ext_dirs = extensions.map do |extension| ext_dirs = extensions.map do |extension|
extension.split(File::SEPARATOR, 2).first extension.split(File::SEPARATOR, 2).first
end.uniq end.uniq
@ -263,7 +263,7 @@ class Gem::BasicSpecification
## ##
# Return all files in this gem that match for +glob+. # Return all files in this gem that match for +glob+.
def matches_for_glob glob # TODO: rename? def matches_for_glob(glob) # TODO: rename?
# TODO: do we need these?? Kill it # TODO: do we need these?? Kill it
glob = File.join(self.lib_dirs_glob, glob) glob = File.join(self.lib_dirs_glob, glob)
@ -276,7 +276,7 @@ class Gem::BasicSpecification
def lib_dirs_glob def lib_dirs_glob
dirs = if self.raw_require_paths dirs = if self.raw_require_paths
if self.raw_require_paths.size > 1 then if self.raw_require_paths.size > 1
"{#{self.raw_require_paths.join(',')}}" "{#{self.raw_require_paths.join(',')}}"
else else
self.raw_require_paths.first self.raw_require_paths.first
@ -316,7 +316,7 @@ class Gem::BasicSpecification
def have_extensions?; !extensions.empty?; end def have_extensions?; !extensions.empty?; end
def have_file? file, suffixes def have_file?(file, suffixes)
return true if raw_require_paths.any? do |path| return true if raw_require_paths.any? do |path|
base = File.join(gems_dir, full_name, path.untaint, file).untaint base = File.join(gems_dir, full_name, path.untaint, file).untaint
suffixes.any? { |suf| File.file? base + suf } suffixes.any? { |suf| File.file? base + suf }

Просмотреть файл

@ -3,15 +3,6 @@
require "rubygems/util" require "rubygems/util"
module Gem::BundlerVersionFinder module Gem::BundlerVersionFinder
@without_filtering = false
def self.without_filtering
without_filtering, @without_filtering = true, @without_filtering
yield
ensure
@without_filtering = without_filtering
end
def self.bundler_version def self.bundler_version
version, _ = bundler_version_with_reason version, _ = bundler_version_with_reason
@ -21,8 +12,6 @@ module Gem::BundlerVersionFinder
end end
def self.bundler_version_with_reason def self.bundler_version_with_reason
return if @without_filtering
if v = ENV["BUNDLER_VERSION"] if v = ENV["BUNDLER_VERSION"]
return [v, "`$BUNDLER_VERSION`"] return [v, "`$BUNDLER_VERSION`"]
end end
@ -40,7 +29,7 @@ module Gem::BundlerVersionFinder
return unless vr = bundler_version_with_reason return unless vr = bundler_version_with_reason
<<-EOS <<-EOS
Could not find 'bundler' (#{vr.first}) required by #{vr.last}. Could not find 'bundler' (#{vr.first}) required by #{vr.last}.
To update to the lastest version installed on your system, run `bundle update --bundler`. To update to the latest version installed on your system, run `bundle update --bundler`.
To install the missing version, run `gem install bundler:#{vr.first}` To install the missing version, run `gem install bundler:#{vr.first}`
EOS EOS
end end

Просмотреть файл

@ -160,7 +160,7 @@ class Gem::Command
msg << ", here is why:\n" msg << ", here is why:\n"
errors.each { |x| msg << " #{x.wordy}\n" } errors.each { |x| msg << " #{x.wordy}\n" }
else else
if required_by and gem != required_by then if required_by and gem != required_by
msg << " (required by #{required_by}) in any repository" msg << " (required by #{required_by}) in any repository"
else else
msg << " in any repository" msg << " in any repository"
@ -169,7 +169,7 @@ class Gem::Command
alert_error msg alert_error msg
unless domain == :local then # HACK unless domain == :local # HACK
suggestions = Gem::SpecFetcher.fetcher.suggest_gems_from_name gem_name suggestions = Gem::SpecFetcher.fetcher.suggest_gems_from_name gem_name
unless suggestions.empty? unless suggestions.empty?
@ -184,7 +184,7 @@ class Gem::Command
def get_all_gem_names def get_all_gem_names
args = options[:args] args = options[:args]
if args.nil? or args.empty? then if args.nil? or args.empty?
raise Gem::CommandLineError, raise Gem::CommandLineError,
"Please specify at least one gem name (e.g. gem build GEMNAME)" "Please specify at least one gem name (e.g. gem build GEMNAME)"
end end
@ -214,12 +214,12 @@ class Gem::Command
def get_one_gem_name def get_one_gem_name
args = options[:args] args = options[:args]
if args.nil? or args.empty? then if args.nil? or args.empty?
raise Gem::CommandLineError, raise Gem::CommandLineError,
"Please specify a gem name on the command line (e.g. gem build GEMNAME)" "Please specify a gem name on the command line (e.g. gem build GEMNAME)"
end end
if args.size > 1 then if args.size > 1
raise Gem::CommandLineError, raise Gem::CommandLineError,
"Too many gem names (#{args.join(', ')}); please specify only one" "Too many gem names (#{args.join(', ')}); please specify only one"
end end
@ -313,9 +313,9 @@ class Gem::Command
self.ui = ui = Gem::SilentUI.new self.ui = ui = Gem::SilentUI.new
end end
if options[:help] then if options[:help]
show_help show_help
elsif @when_invoked then elsif @when_invoked
@when_invoked.call options @when_invoked.call options
else else
execute execute
@ -451,7 +451,7 @@ class Gem::Command
# Adds a section with +title+ and +content+ to the parser help view. Used # Adds a section with +title+ and +content+ to the parser help view. Used
# for adding command arguments and default arguments. # for adding command arguments and default arguments.
def add_parser_run_info title, content def add_parser_run_info(title, content)
return if content.empty? return if content.empty?
@parser.separator nil @parser.separator nil
@ -531,7 +531,7 @@ class Gem::Command
add_common_option('-V', '--[no-]verbose', add_common_option('-V', '--[no-]verbose',
'Set the verbose level of output') do |value, options| 'Set the verbose level of output') do |value, options|
# Set us to "really verbose" so the progress meter works # Set us to "really verbose" so the progress meter works
if Gem.configuration.verbose and value then if Gem.configuration.verbose and value
Gem.configuration.verbose = 1 Gem.configuration.verbose = 1
else else
Gem.configuration.verbose = value Gem.configuration.verbose = value

Просмотреть файл

@ -155,7 +155,7 @@ class Gem::CommandManager
end end
def process_args(args, build_args=nil) def process_args(args, build_args=nil)
if args.empty? then if args.empty?
say Gem::Command::HELP say Gem::Command::HELP
terminate_interaction 1 terminate_interaction 1
end end
@ -182,10 +182,10 @@ class Gem::CommandManager
possibilities = find_command_possibilities cmd_name possibilities = find_command_possibilities cmd_name
if possibilities.size > 1 then if possibilities.size > 1
raise Gem::CommandLineError, raise Gem::CommandLineError,
"Ambiguous command #{cmd_name} matches [#{possibilities.join(', ')}]" "Ambiguous command #{cmd_name} matches [#{possibilities.join(', ')}]"
elsif possibilities.empty? then elsif possibilities.empty?
raise Gem::CommandLineError, "Unknown command #{cmd_name}" raise Gem::CommandLineError, "Unknown command #{cmd_name}"
end end
@ -230,4 +230,3 @@ class Gem::CommandManager
end end
end end

Просмотреть файл

@ -50,11 +50,11 @@ with gem spec:
gemspec += '.gemspec' if File.exist? gemspec + '.gemspec' gemspec += '.gemspec' if File.exist? gemspec + '.gemspec'
end end
if File.exist? gemspec then if File.exist? gemspec
Dir.chdir(File.dirname(gemspec)) do Dir.chdir(File.dirname(gemspec)) do
spec = Gem::Specification.load File.basename(gemspec) spec = Gem::Specification.load File.basename(gemspec)
if spec then if spec
Gem::Package.build( Gem::Package.build(
spec, spec,
options[:force], options[:force],
@ -72,4 +72,3 @@ with gem spec:
end end
end end

Просмотреть файл

@ -98,7 +98,7 @@ class Gem::Commands::CertCommand < Gem::Command
end end
end end
def add_certificate certificate # :nodoc: def add_certificate(certificate) # :nodoc:
Gem::Security.trust_dir.trust_cert certificate Gem::Security.trust_dir.trust_cert certificate
say "Added '#{certificate.subject}'" say "Added '#{certificate.subject}'"
@ -132,7 +132,7 @@ class Gem::Commands::CertCommand < Gem::Command
sign_certificates unless options[:sign].empty? sign_certificates unless options[:sign].empty?
end end
def build email def build(email)
if !valid_email?(email) if !valid_email?(email)
raise Gem::CommandLineError, "Invalid email address #{email}" raise Gem::CommandLineError, "Invalid email address #{email}"
end end
@ -148,7 +148,7 @@ class Gem::Commands::CertCommand < Gem::Command
end end
end end
def build_cert email, key # :nodoc: def build_cert(email, key) # :nodoc:
expiration_length_days = options[:expiration_length_days] || expiration_length_days = options[:expiration_length_days] ||
Gem.configuration.cert_expiration_length_days Gem.configuration.cert_expiration_length_days
@ -179,7 +179,7 @@ class Gem::Commands::CertCommand < Gem::Command
return key, key_path return key, key_path
end end
def certificates_matching filter def certificates_matching(filter)
return enum_for __method__, filter unless block_given? return enum_for __method__, filter unless block_given?
Gem::Security.trusted_certificates.select do |certificate, _| Gem::Security.trusted_certificates.select do |certificate, _|
@ -231,7 +231,7 @@ For further reading on signing gems see `ri Gem::Security`.
EOF EOF
end end
def list_certificates_matching filter # :nodoc: def list_certificates_matching(filter) # :nodoc:
certificates_matching filter do |certificate, _| certificates_matching filter do |certificate, _|
# this could probably be formatted more gracefully # this could probably be formatted more gracefully
say certificate.subject.to_s say certificate.subject.to_s
@ -276,14 +276,14 @@ For further reading on signing gems see `ri Gem::Security`.
load_default_key unless options[:key] load_default_key unless options[:key]
end end
def remove_certificates_matching filter # :nodoc: def remove_certificates_matching(filter) # :nodoc:
certificates_matching filter do |certificate, path| certificates_matching filter do |certificate, path|
FileUtils.rm path FileUtils.rm path
say "Removed '#{certificate.subject}'" say "Removed '#{certificate.subject}'"
end end
end end
def sign cert_file def sign(cert_file)
cert = File.read cert_file cert = File.read cert_file
cert = OpenSSL::X509::Certificate.new cert cert = OpenSSL::X509::Certificate.new cert
@ -314,11 +314,10 @@ For further reading on signing gems see `ri Gem::Security`.
private private
def valid_email? email def valid_email?(email)
# It's simple, but is all we need # It's simple, but is all we need
email =~ /\A.+@.+\z/ email =~ /\A.+@.+\z/
end end
end if defined?(OpenSSL::SSL) end if defined?(OpenSSL::SSL)

Просмотреть файл

@ -44,7 +44,7 @@ class Gem::Commands::CheckCommand < Gem::Command
gems = get_all_gem_names rescue [] gems = get_all_gem_names rescue []
Gem::Validator.new.alien(gems).sort.each do |key, val| Gem::Validator.new.alien(gems).sort.each do |key, val|
unless val.empty? then unless val.empty?
say "#{key} has #{val.size} problems" say "#{key} has #{val.size} problems"
val.each do |error_entry| val.each do |error_entry|
say " #{error_entry.path}:" say " #{error_entry.path}:"

Просмотреть файл

@ -62,7 +62,7 @@ If no gems are named all gems in GEM_HOME are cleaned.
def execute def execute
say "Cleaning up installed gems..." say "Cleaning up installed gems..."
if options[:args].empty? then if options[:args].empty?
done = false done = false
last_set = nil last_set = nil
@ -111,7 +111,7 @@ If no gems are named all gems in GEM_HOME are cleaned.
end end
def get_candidate_gems def get_candidate_gems
@candidate_gems = unless options[:args].empty? then @candidate_gems = unless options[:args].empty?
options[:args].map do |gem_name| options[:args].map do |gem_name|
Gem::Specification.find_all_by_name gem_name Gem::Specification.find_all_by_name gem_name
end.flatten end.flatten
@ -121,7 +121,6 @@ If no gems are named all gems in GEM_HOME are cleaned.
end end
def get_gems_to_cleanup def get_gems_to_cleanup
gems_to_cleanup = @candidate_gems.select { |spec| gems_to_cleanup = @candidate_gems.select { |spec|
@primary_gems[spec.name].version != spec.version @primary_gems[spec.name].version != spec.version
} }
@ -146,16 +145,16 @@ If no gems are named all gems in GEM_HOME are cleaned.
Gem::Specification.each do |spec| Gem::Specification.each do |spec|
if @primary_gems[spec.name].nil? or if @primary_gems[spec.name].nil? or
@primary_gems[spec.name].version < spec.version then @primary_gems[spec.name].version < spec.version
@primary_gems[spec.name] = spec @primary_gems[spec.name] = spec
end end
end end
end end
def uninstall_dep spec def uninstall_dep(spec)
return unless @full.ok_to_remove?(spec.full_name, options[:check_dev]) return unless @full.ok_to_remove?(spec.full_name, options[:check_dev])
if options[:dryrun] then if options[:dryrun]
say "Dry Run Mode: Would uninstall #{spec.full_name}" say "Dry Run Mode: Would uninstall #{spec.full_name}"
return return
end end

Просмотреть файл

@ -73,7 +73,7 @@ prefix or only the files that are requireable.
names.each do |name| names.each do |name|
found = found =
if options[:show_install_dir] then if options[:show_install_dir]
gem_install_dir name gem_install_dir name
else else
gem_contents name gem_contents name
@ -83,15 +83,15 @@ prefix or only the files that are requireable.
end end
end end
def files_in spec def files_in(spec)
if spec.default_gem? then if spec.default_gem?
files_in_default_gem spec files_in_default_gem spec
else else
files_in_gem spec files_in_gem spec
end end
end end
def files_in_gem spec def files_in_gem(spec)
gem_path = spec.full_gem_path gem_path = spec.full_gem_path
extra = "/{#{spec.require_paths.join ','}}" if options[:lib_only] extra = "/{#{spec.require_paths.join ','}}" if options[:lib_only]
glob = "#{gem_path}#{extra}/**/*" glob = "#{gem_path}#{extra}/**/*"
@ -102,7 +102,7 @@ prefix or only the files that are requireable.
end end
end end
def files_in_default_gem spec def files_in_default_gem(spec)
spec.files.map do |file| spec.files.map do |file|
case file case file
when /\A#{spec.bindir}\// when /\A#{spec.bindir}\//
@ -115,7 +115,7 @@ prefix or only the files that are requireable.
end end
end end
def gem_contents name def gem_contents(name)
spec = spec_for name spec = spec_for name
return false unless spec return false unless spec
@ -127,7 +127,7 @@ prefix or only the files that are requireable.
true true
end end
def gem_install_dir name def gem_install_dir(name)
spec = spec_for name spec = spec_for name
return false unless spec return false unless spec
@ -138,27 +138,27 @@ prefix or only the files that are requireable.
end end
def gem_names # :nodoc: def gem_names # :nodoc:
if options[:all] then if options[:all]
Gem::Specification.map(&:name) Gem::Specification.map(&:name)
else else
get_all_gem_names get_all_gem_names
end end
end end
def path_description spec_dirs # :nodoc: def path_description(spec_dirs) # :nodoc:
if spec_dirs.empty? then if spec_dirs.empty?
"default gem paths" "default gem paths"
else else
"specified path" "specified path"
end end
end end
def show_files files def show_files(files)
files.sort.each do |prefix, basename| files.sort.each do |prefix, basename|
absolute_path = File.join(prefix, basename) absolute_path = File.join(prefix, basename)
next if File.directory? absolute_path next if File.directory? absolute_path
if options[:prefix] then if options[:prefix]
say absolute_path say absolute_path
else else
say basename say basename
@ -166,14 +166,14 @@ prefix or only the files that are requireable.
end end
end end
def spec_for name def spec_for(name)
spec = Gem::Specification.find_all_by_name(name, @version).last spec = Gem::Specification.find_all_by_name(name, @version).last
return spec if spec return spec if spec
say "Unable to find gem '#{name}' in #{@path_kind}" say "Unable to find gem '#{name}' in #{@path_kind}"
if Gem.configuration.verbose then if Gem.configuration.verbose
say "\nDirectories searched:" say "\nDirectories searched:"
@spec_dirs.sort.each { |dir| say dir } @spec_dirs.sort.each { |dir| say dir }
end end
@ -188,4 +188,3 @@ prefix or only the files that are requireable.
end end
end end

Просмотреть файл

@ -54,7 +54,7 @@ use with other commands.
"#{program_name} REGEXP" "#{program_name} REGEXP"
end end
def fetch_remote_specs dependency # :nodoc: def fetch_remote_specs(dependency) # :nodoc:
fetcher = Gem::SpecFetcher.fetcher fetcher = Gem::SpecFetcher.fetcher
ss, = fetcher.spec_for_dependency dependency ss, = fetcher.spec_for_dependency dependency
@ -62,7 +62,7 @@ use with other commands.
ss.map { |spec, _| spec } ss.map { |spec, _| spec }
end end
def fetch_specs name_pattern, dependency # :nodoc: def fetch_specs(name_pattern, dependency) # :nodoc:
specs = [] specs = []
if local? if local?
@ -79,7 +79,7 @@ use with other commands.
specs.uniq.sort specs.uniq.sort
end end
def gem_dependency pattern, version, prerelease # :nodoc: def gem_dependency(pattern, version, prerelease) # :nodoc:
dependency = Gem::Deprecate.skip_during { dependency = Gem::Deprecate.skip_during {
Gem::Dependency.new pattern, version Gem::Dependency.new pattern, version
} }
@ -89,9 +89,9 @@ use with other commands.
dependency dependency
end end
def display_pipe specs # :nodoc: def display_pipe(specs) # :nodoc:
specs.each do |spec| specs.each do |spec|
unless spec.dependencies.empty? then unless spec.dependencies.empty?
spec.dependencies.sort_by { |dep| dep.name }.each do |dep| spec.dependencies.sort_by { |dep| dep.name }.each do |dep|
say "#{dep.name} --version '#{dep.requirement}'" say "#{dep.name} --version '#{dep.requirement}'"
end end
@ -99,12 +99,12 @@ use with other commands.
end end
end end
def display_readable specs, reverse # :nodoc: def display_readable(specs, reverse) # :nodoc:
response = String.new response = String.new
specs.each do |spec| specs.each do |spec|
response << print_dependencies(spec) response << print_dependencies(spec)
unless reverse[spec.full_name].empty? then unless reverse[spec.full_name].empty?
response << " Used by\n" response << " Used by\n"
reverse[spec.full_name].each do |sp, dep| reverse[spec.full_name].each do |sp, dep|
response << " #{sp} (#{dep})\n" response << " #{sp} (#{dep})\n"
@ -128,7 +128,7 @@ use with other commands.
reverse = reverse_dependencies specs reverse = reverse_dependencies specs
if options[:pipe_format] then if options[:pipe_format]
display_pipe specs display_pipe specs
else else
display_readable specs, reverse display_readable specs, reverse
@ -136,13 +136,13 @@ use with other commands.
end end
def ensure_local_only_reverse_dependencies # :nodoc: def ensure_local_only_reverse_dependencies # :nodoc:
if options[:reverse_dependencies] and remote? and not local? then if options[:reverse_dependencies] and remote? and not local?
alert_error 'Only reverse dependencies for local gems are supported.' alert_error 'Only reverse dependencies for local gems are supported.'
terminate_interaction 1 terminate_interaction 1
end end
end end
def ensure_specs specs # :nodoc: def ensure_specs(specs) # :nodoc:
return unless specs.empty? return unless specs.empty?
patterns = options[:args].join ',' patterns = options[:args].join ','
@ -155,7 +155,7 @@ use with other commands.
def print_dependencies(spec, level = 0) # :nodoc: def print_dependencies(spec, level = 0) # :nodoc:
response = String.new response = String.new
response << ' ' * level + "Gem #{spec.full_name}\n" response << ' ' * level + "Gem #{spec.full_name}\n"
unless spec.dependencies.empty? then unless spec.dependencies.empty?
spec.dependencies.sort_by { |dep| dep.name }.each do |dep| spec.dependencies.sort_by { |dep| dep.name }.each do |dep|
response << ' ' * level + " #{dep}\n" response << ' ' * level + " #{dep}\n"
end end
@ -163,7 +163,7 @@ use with other commands.
response response
end end
def remote_specs dependency # :nodoc: def remote_specs(dependency) # :nodoc:
fetcher = Gem::SpecFetcher.fetcher fetcher = Gem::SpecFetcher.fetcher
ss, _ = fetcher.spec_for_dependency dependency ss, _ = fetcher.spec_for_dependency dependency
@ -171,7 +171,7 @@ use with other commands.
ss.map { |s,o| s } ss.map { |s,o| s }
end end
def reverse_dependencies specs # :nodoc: def reverse_dependencies(specs) # :nodoc:
reverse = Hash.new { |h, k| h[k] = [] } reverse = Hash.new { |h, k| h[k] = [] }
return reverse unless options[:reverse_dependencies] return reverse unless options[:reverse_dependencies]
@ -186,7 +186,7 @@ use with other commands.
## ##
# Returns an Array of [specification, dep] that are satisfied by +spec+. # Returns an Array of [specification, dep] that are satisfied by +spec+.
def find_reverse_dependencies spec # :nodoc: def find_reverse_dependencies(spec) # :nodoc:
result = [] result = []
Gem::Specification.each do |sp| Gem::Specification.each do |sp|
@ -194,7 +194,7 @@ use with other commands.
dep = Gem::Dependency.new(*dep) unless Gem::Dependency === dep dep = Gem::Dependency.new(*dep) unless Gem::Dependency === dep
if spec.name == dep.name and if spec.name == dep.name and
dep.requirement.satisfied_by?(spec.version) then dep.requirement.satisfied_by?(spec.version)
result << [sp.full_name, dep] result << [sp.full_name, dep]
end end
end end
@ -205,10 +205,10 @@ use with other commands.
private private
def name_pattern args def name_pattern(args)
args << '' if args.empty? args << '' if args.empty?
if args.length == 1 and args.first =~ /\A\/(.*)\/(i)?\z/m then if args.length == 1 and args.first =~ /\A\/(.*)\/(i)?\z/m
flags = $2 ? Regexp::IGNORECASE : nil flags = $2 ? Regexp::IGNORECASE : nil
Regexp.new $1, flags Regexp.new $1, flags
else else

Просмотреть файл

@ -97,7 +97,7 @@ lib/rubygems/defaults/operating_system.rb
true true
end end
def add_path out, path def add_path(out, path)
path.each do |component| path.each do |component|
out << " - #{component}\n" out << " - #{component}\n"
end end

Просмотреть файл

@ -56,14 +56,14 @@ then repackaging it.
specs_and_sources, errors = specs_and_sources, errors =
Gem::SpecFetcher.fetcher.spec_for_dependency dep Gem::SpecFetcher.fetcher.spec_for_dependency dep
if platform then if platform
filtered = specs_and_sources.select { |s,| s.platform == platform } filtered = specs_and_sources.select { |s,| s.platform == platform }
specs_and_sources = filtered unless filtered.empty? specs_and_sources = filtered unless filtered.empty?
end end
spec, source = specs_and_sources.max_by { |s,| s.version } spec, source = specs_and_sources.max_by { |s,| s.version }
if spec.nil? then if spec.nil?
show_lookup_failure gem_name, version, errors, options[:domain] show_lookup_failure gem_name, version, errors, options[:domain]
next next
end end
@ -75,4 +75,3 @@ then repackaging it.
end end
end end

Просмотреть файл

@ -67,13 +67,13 @@ Marshal::MINOR_VERSION constants. It is used to ensure compatibility.
options[:build_modern] = true options[:build_modern] = true
if not File.exist?(options[:directory]) or if not File.exist?(options[:directory]) or
not File.directory?(options[:directory]) then not File.directory?(options[:directory])
alert_error "unknown directory name #{options[:directory]}." alert_error "unknown directory name #{options[:directory]}."
terminate_interaction 1 terminate_interaction 1
else else
indexer = Gem::Indexer.new options.delete(:directory), options indexer = Gem::Indexer.new options.delete(:directory), options
if options[:update] then if options[:update]
indexer.update_index indexer.update_index
else else
indexer.generate_index indexer.generate_index
@ -82,4 +82,3 @@ Marshal::MINOR_VERSION constants. It is used to ensure compatibility.
end end
end end

Просмотреть файл

@ -297,8 +297,8 @@ platform.
begins? command, arg begins? command, arg
end end
if help then if help
if Symbol === help then if Symbol === help
send help send help
else else
say help say help
@ -306,10 +306,10 @@ platform.
return return
end end
if options[:help] then if options[:help]
show_help show_help
elsif arg then elsif arg
show_command_help arg show_command_help arg
else else
@ -334,7 +334,7 @@ platform.
command = @command_manager[cmd_name] command = @command_manager[cmd_name]
summary = summary =
if command then if command
command.summary command.summary
else else
"[No command found for #{cmd_name}]" "[No command found for #{cmd_name}]"
@ -356,15 +356,15 @@ platform.
say out.join("\n") say out.join("\n")
end end
def show_command_help command_name # :nodoc: def show_command_help(command_name) # :nodoc:
command_name = command_name.downcase command_name = command_name.downcase
possibilities = @command_manager.find_command_possibilities command_name possibilities = @command_manager.find_command_possibilities command_name
if possibilities.size == 1 then if possibilities.size == 1
command = @command_manager[possibilities.first] command = @command_manager[possibilities.first]
command.invoke("--help") command.invoke("--help")
elsif possibilities.size > 1 then elsif possibilities.size > 1
alert_warning "Ambiguous command #{command_name} (#{possibilities.join(', ')})" alert_warning "Ambiguous command #{command_name} (#{possibilities.join(', ')})"
else else
alert_warning "Unknown command #{command_name}. Try: gem help commands" alert_warning "Unknown command #{command_name}. Try: gem help commands"
@ -372,4 +372,3 @@ platform.
end end
end end

Просмотреть файл

@ -132,7 +132,7 @@ You can use `i` command instead of `install`.
end end
def check_install_dir # :nodoc: def check_install_dir # :nodoc:
if options[:install_dir] and options[:user_install] then if options[:install_dir] and options[:user_install]
alert_error "Use --install-dir or --user-install but not both" alert_error "Use --install-dir or --user-install but not both"
terminate_interaction 1 terminate_interaction 1
end end
@ -140,7 +140,7 @@ You can use `i` command instead of `install`.
def check_version # :nodoc: def check_version # :nodoc:
if options[:version] != Gem::Requirement.default and if options[:version] != Gem::Requirement.default and
get_all_gem_names.size > 1 then get_all_gem_names.size > 1
alert_error "Can't use --version with multiple gems. You can specify multiple gems with" \ alert_error "Can't use --version with multiple gems. You can specify multiple gems with" \
" version requirments using `gem install 'my_gem:1.0.0' 'my_other_gem:~>2.0.0'`" " version requirments using `gem install 'my_gem:1.0.0' 'my_other_gem:~>2.0.0'`"
terminate_interaction 1 terminate_interaction 1
@ -148,8 +148,7 @@ You can use `i` command instead of `install`.
end end
def execute def execute
if options.include? :gemdeps
if options.include? :gemdeps then
install_from_gemdeps install_from_gemdeps
return # not reached return # not reached
end end
@ -189,13 +188,13 @@ You can use `i` command instead of `install`.
terminate_interaction terminate_interaction
end end
def install_gem name, version # :nodoc: def install_gem(name, version) # :nodoc:
return if options[:conservative] and return if options[:conservative] and
not Gem::Dependency.new(name, version).matching_specs.empty? not Gem::Dependency.new(name, version).matching_specs.empty?
req = Gem::Requirement.create(version) req = Gem::Requirement.create(version)
if options[:ignore_dependencies] then if options[:ignore_dependencies]
install_gem_without_dependencies name, req install_gem_without_dependencies name, req
else else
inst = Gem::DependencyInstaller.new options inst = Gem::DependencyInstaller.new options
@ -217,11 +216,11 @@ You can use `i` command instead of `install`.
end end
end end
def install_gem_without_dependencies name, req # :nodoc: def install_gem_without_dependencies(name, req) # :nodoc:
gem = nil gem = nil
if local? then if local?
if name =~ /\.gem$/ and File.file? name then if name =~ /\.gem$/ and File.file? name
source = Gem::Source::SpecificFile.new name source = Gem::Source::SpecificFile.new name
spec = source.spec spec = source.spec
else else
@ -231,7 +230,7 @@ You can use `i` command instead of `install`.
gem = source.download spec if spec gem = source.download spec if spec
end end
if remote? and not gem then if remote? and not gem
dependency = Gem::Dependency.new name, req dependency = Gem::Dependency.new name, req
dependency.prerelease = options[:prerelease] dependency.prerelease = options[:prerelease]
@ -293,7 +292,7 @@ You can use `i` command instead of `install`.
require 'rubygems/rdoc' require 'rubygems/rdoc'
end end
def show_install_errors errors # :nodoc: def show_install_errors(errors) # :nodoc:
return unless errors return unless errors
errors.each do |x| errors.each do |x|

Просмотреть файл

@ -38,4 +38,3 @@ To search for remote gems use the search command.
end end
end end

Просмотреть файл

@ -59,7 +59,7 @@ lock it down to the exact version.
end end
def complain(message) def complain(message)
if options[:strict] then if options[:strict]
raise Gem::Exception, message raise Gem::Exception, message
else else
say "# #{message}" say "# #{message}"
@ -78,7 +78,7 @@ lock it down to the exact version.
spec = Gem::Specification.load spec_path(full_name) spec = Gem::Specification.load spec_path(full_name)
if spec.nil? then if spec.nil?
complain "Could not find gem #{full_name}, try using the full name" complain "Could not find gem #{full_name}, try using the full name"
next next
end end
@ -90,7 +90,7 @@ lock it down to the exact version.
next if locked[dep.name] next if locked[dep.name]
candidates = dep.matching_specs candidates = dep.matching_specs
if candidates.empty? then if candidates.empty?
complain "Unable to satisfy '#{dep}' from currently installed gems" complain "Unable to satisfy '#{dep}' from currently installed gems"
else else
pending << candidates.last.full_name pending << candidates.last.full_name
@ -108,4 +108,3 @@ lock it down to the exact version.
end end
end end

Просмотреть файл

@ -11,9 +11,9 @@ class Gem::Commands::OpenCommand < Gem::Command
def initialize def initialize
super 'open', 'Open gem sources in editor' super 'open', 'Open gem sources in editor'
add_option('-e', '--editor EDITOR', String, add_option('-e', '--editor COMMAND', String,
"Opens gem sources in EDITOR") do |editor, options| "Prepends COMMAND to gem path. Could be used to specify editor.") do |command, options|
options[:editor] = editor || get_env_editor options[:editor] = command || get_env_editor
end end
add_option('-v', '--version VERSION', String, add_option('-v', '--version VERSION', String,
"Opens specific gem version") do |version| "Opens specific gem version") do |version|
@ -32,14 +32,14 @@ class Gem::Commands::OpenCommand < Gem::Command
def description # :nodoc: def description # :nodoc:
<<-EOF <<-EOF
The open command opens gem in editor and changes current path The open command opens gem in editor and changes current path
to gem's source directory. Editor can be specified with -e option, to gem's source directory.
otherwise rubygems will look for editor in $EDITOR, $VISUAL and Editor command can be specified with -e option, otherwise rubygems
$GEM_EDITOR variables. will look for editor in $EDITOR, $VISUAL and $GEM_EDITOR variables.
EOF EOF
end end
def usage # :nodoc: def usage # :nodoc:
"#{program_name} GEMNAME [-e EDITOR]" "#{program_name} GEMNAME [-e COMMAND]"
end end
def get_env_editor def get_env_editor
@ -58,7 +58,7 @@ class Gem::Commands::OpenCommand < Gem::Command
terminate_interaction 1 unless found terminate_interaction 1 unless found
end end
def open_gem name def open_gem(name)
spec = spec_for name spec = spec_for name
return false unless spec return false unless spec
@ -71,13 +71,13 @@ class Gem::Commands::OpenCommand < Gem::Command
open_editor(spec.full_gem_path) open_editor(spec.full_gem_path)
end end
def open_editor path def open_editor(path)
Dir.chdir(path) do Dir.chdir(path) do
system(*@editor.split(/\s+/) + [path]) system(*@editor.split(/\s+/) + [path])
end end
end end
def spec_for name def spec_for(name)
spec = Gem::Specification.find_all_by_name(name, @version).first spec = Gem::Specification.find_all_by_name(name, @version).first
return spec if spec return spec if spec

Просмотреть файл

@ -58,7 +58,7 @@ permission to.
show_owners name show_owners name
end end
def show_owners name def show_owners(name)
response = rubygems_api_request :get, "api/v1/gems/#{name}/owners.yaml" do |request| response = rubygems_api_request :get, "api/v1/gems/#{name}/owners.yaml" do |request|
request.add_field "Authorization", api_key request.add_field "Authorization", api_key
end end
@ -73,15 +73,15 @@ permission to.
end end
end end
def add_owners name, owners def add_owners(name, owners)
manage_owners :post, name, owners manage_owners :post, name, owners
end end
def remove_owners name, owners def remove_owners(name, owners)
manage_owners :delete, name, owners manage_owners :delete, name, owners
end end
def manage_owners method, name, owners def manage_owners(method, name, owners)
owners.each do |owner| owners.each do |owner|
begin begin
response = rubygems_api_request method, "api/v1/gems/#{name}/owners" do |request| response = rubygems_api_request method, "api/v1/gems/#{name}/owners" do |request|

Просмотреть файл

@ -88,13 +88,13 @@ extensions will be restored.
end end
def execute def execute
specs = if options[:all] then specs = if options[:all]
Gem::Specification.map Gem::Specification.map
# `--extensions` must be explicitly given to pristine only gems # `--extensions` must be explicitly given to pristine only gems
# with extensions. # with extensions.
elsif options[:extensions_set] and elsif options[:extensions_set] and
options[:extensions] and options[:args].empty? then options[:extensions] and options[:args].empty?
Gem::Specification.select do |spec| Gem::Specification.select do |spec|
spec.extensions and not spec.extensions.empty? spec.extensions and not spec.extensions.empty?
end end
@ -104,7 +104,7 @@ extensions will be restored.
end.flatten end.flatten
end end
if specs.to_a.empty? then if specs.to_a.empty?
raise Gem::Exception, raise Gem::Exception,
"Failed to find gems #{options[:args]} #{options[:version]}" "Failed to find gems #{options[:args]} #{options[:version]}"
end end
@ -134,14 +134,14 @@ extensions will be restored.
next next
end end
unless spec.extensions.empty? or options[:extensions] or options[:only_executables] then unless spec.extensions.empty? or options[:extensions] or options[:only_executables]
say "Skipped #{spec.full_name}, it needs to compile an extension" say "Skipped #{spec.full_name}, it needs to compile an extension"
next next
end end
gem = spec.cache_file gem = spec.cache_file
unless File.exist? gem or options[:only_executables] then unless File.exist? gem or options[:only_executables]
require 'rubygems/remote_fetcher' require 'rubygems/remote_fetcher'
say "Cached gem for #{spec.full_name} not found, attempting to fetch..." say "Cached gem for #{spec.full_name} not found, attempting to fetch..."
@ -159,7 +159,7 @@ extensions will be restored.
end end
env_shebang = env_shebang =
if options.include? :env_shebang then if options.include? :env_shebang
options[:env_shebang] options[:env_shebang]
else else
install_defaults = Gem::ConfigFile::PLATFORM_DEFAULTS['install'] install_defaults = Gem::ConfigFile::PLATFORM_DEFAULTS['install']
@ -177,7 +177,7 @@ extensions will be restored.
:bin_dir => bin_dir :bin_dir => bin_dir
} }
if options[:only_executables] then if options[:only_executables]
installer = Gem::Installer.for_spec(spec, installer_options) installer = Gem::Installer.for_spec(spec, installer_options)
installer.generate_bin installer.generate_bin
else else

Просмотреть файл

@ -79,7 +79,7 @@ command. For further discussion see the help for the yank command.
if latest_rubygems_version < Gem.rubygems_version and if latest_rubygems_version < Gem.rubygems_version and
Gem.rubygems_version.prerelease? and Gem.rubygems_version.prerelease? and
Gem::Version.new('2.0.0.rc.2') != Gem.rubygems_version then Gem::Version.new('2.0.0.rc.2') != Gem.rubygems_version
alert_error <<-ERROR alert_error <<-ERROR
You are using a beta release of RubyGems (#{Gem::VERSION}) which is not You are using a beta release of RubyGems (#{Gem::VERSION}) which is not
allowed to push gems. Please downgrade or upgrade to a release version. allowed to push gems. Please downgrade or upgrade to a release version.
@ -96,7 +96,7 @@ You can upgrade or downgrade to the latest release version with:
gem_data = Gem::Package.new(name) gem_data = Gem::Package.new(name)
unless @host then unless @host
@host = gem_data.spec.metadata['default_gem_server'] @host = gem_data.spec.metadata['default_gem_server']
end end
@ -134,4 +134,3 @@ You can upgrade or downgrade to the latest release version with:
] ]
end end
end end

Просмотреть файл

@ -91,8 +91,8 @@ is too hard to use.
prerelease = options[:prerelease] prerelease = options[:prerelease]
unless options[:installed].nil? then unless options[:installed].nil?
if no_name then if no_name
alert_error "You must specify a gem name" alert_error "You must specify a gem name"
exit_code |= 4 exit_code |= 4
elsif name.count > 1 elsif name.count > 1
@ -102,7 +102,7 @@ is too hard to use.
installed = installed? name.first, options[:version] installed = installed? name.first, options[:version]
installed = !installed unless options[:installed] installed = !installed unless options[:installed]
if installed then if installed
say "true" say "true"
else else
say "false" say "false"
@ -119,8 +119,8 @@ is too hard to use.
private private
def display_header type def display_header(type)
if (ui.outs.tty? and Gem.configuration.verbose) or both? then if (ui.outs.tty? and Gem.configuration.verbose) or both?
say say
say "*** #{type} GEMS ***" say "*** #{type} GEMS ***"
say say
@ -128,14 +128,14 @@ is too hard to use.
end end
#Guts of original execute #Guts of original execute
def show_gems name, prerelease def show_gems(name, prerelease)
req = Gem::Requirement.default req = Gem::Requirement.default
# TODO: deprecate for real # TODO: deprecate for real
dep = Gem::Deprecate.skip_during { Gem::Dependency.new name, req } dep = Gem::Deprecate.skip_during { Gem::Dependency.new name, req }
dep.prerelease = prerelease dep.prerelease = prerelease
if local? then if local?
if prerelease and not both? then if prerelease and not both?
alert_warning "prereleases are always shown locally" alert_warning "prereleases are always shown locally"
end end
@ -152,7 +152,7 @@ is too hard to use.
output_query_results spec_tuples output_query_results spec_tuples
end end
if remote? then if remote?
display_header 'REMOTE' display_header 'REMOTE'
fetcher = Gem::SpecFetcher.fetcher fetcher = Gem::SpecFetcher.fetcher
@ -205,7 +205,7 @@ is too hard to use.
say output.join(options[:details] ? "\n\n" : "\n") say output.join(options[:details] ? "\n\n" : "\n")
end end
def output_versions output, versions def output_versions(output, versions)
versions.each do |gem_name, matching_tuples| versions.each do |gem_name, matching_tuples|
matching_tuples = matching_tuples.sort_by { |n,_| n.version }.reverse matching_tuples = matching_tuples.sort_by { |n,_| n.version }.reverse
@ -218,7 +218,7 @@ is too hard to use.
seen = {} seen = {}
matching_tuples.delete_if do |n,_| matching_tuples.delete_if do |n,_|
if seen[n.version] then if seen[n.version]
true true
else else
seen[n.version] = true seen[n.version] = true
@ -230,7 +230,7 @@ is too hard to use.
end end
end end
def entry_details entry, detail_tuple, specs, platforms def entry_details(entry, detail_tuple, specs, platforms)
return unless options[:details] return unless options[:details]
name_tuple, spec = detail_tuple name_tuple, spec = detail_tuple
@ -247,11 +247,11 @@ is too hard to use.
spec_summary entry, spec spec_summary entry, spec
end end
def entry_versions entry, name_tuples, platforms, specs def entry_versions(entry, name_tuples, platforms, specs)
return unless options[:versions] return unless options[:versions]
list = list =
if platforms.empty? or options[:details] then if platforms.empty? or options[:details]
name_tuples.map { |n| n.version }.uniq name_tuples.map { |n| n.version }.uniq
else else
platforms.sort.reverse.map do |version, pls| platforms.sort.reverse.map do |version, pls|
@ -264,7 +264,7 @@ is too hard to use.
out = "default: #{out}" if default out = "default: #{out}" if default
end end
if pls != [Gem::Platform::RUBY] then if pls != [Gem::Platform::RUBY]
platform_list = [pls.delete(Gem::Platform::RUBY), *pls.sort].compact platform_list = [pls.delete(Gem::Platform::RUBY), *pls.sort].compact
out = platform_list.unshift(out).join(' ') out = platform_list.unshift(out).join(' ')
end end
@ -276,7 +276,7 @@ is too hard to use.
entry << " (#{list.join ', '})" entry << " (#{list.join ', '})"
end end
def make_entry entry_tuples, platforms def make_entry(entry_tuples, platforms)
detail_tuple = entry_tuples.first detail_tuple = entry_tuples.first
name_tuples, specs = entry_tuples.flatten.partition do |item| name_tuples, specs = entry_tuples.flatten.partition do |item|
@ -291,19 +291,19 @@ is too hard to use.
entry.join entry.join
end end
def spec_authors entry, spec def spec_authors(entry, spec)
authors = "Author#{spec.authors.length > 1 ? 's' : ''}: ".dup authors = "Author#{spec.authors.length > 1 ? 's' : ''}: ".dup
authors << spec.authors.join(', ') authors << spec.authors.join(', ')
entry << format_text(authors, 68, 4) entry << format_text(authors, 68, 4)
end end
def spec_homepage entry, spec def spec_homepage(entry, spec)
return if spec.homepage.nil? or spec.homepage.empty? return if spec.homepage.nil? or spec.homepage.empty?
entry << "\n" << format_text("Homepage: #{spec.homepage}", 68, 4) entry << "\n" << format_text("Homepage: #{spec.homepage}", 68, 4)
end end
def spec_license entry, spec def spec_license(entry, spec)
return if spec.license.nil? or spec.license.empty? return if spec.license.nil? or spec.license.empty?
licenses = "License#{spec.licenses.length > 1 ? 's' : ''}: ".dup licenses = "License#{spec.licenses.length > 1 ? 's' : ''}: ".dup
@ -311,10 +311,10 @@ is too hard to use.
entry << "\n" << format_text(licenses, 68, 4) entry << "\n" << format_text(licenses, 68, 4)
end end
def spec_loaded_from entry, spec, specs def spec_loaded_from(entry, spec, specs)
return unless spec.loaded_from return unless spec.loaded_from
if specs.length == 1 then if specs.length == 1
default = spec.default_gem? ? ' (default)' : nil default = spec.default_gem? ? ' (default)' : nil
entry << "\n" << " Installed at#{default}: #{spec.base_dir}" entry << "\n" << " Installed at#{default}: #{spec.base_dir}"
else else
@ -328,14 +328,14 @@ is too hard to use.
end end
end end
def spec_platforms entry, platforms def spec_platforms(entry, platforms)
non_ruby = platforms.any? do |_, pls| non_ruby = platforms.any? do |_, pls|
pls.any? { |pl| pl != Gem::Platform::RUBY } pls.any? { |pl| pl != Gem::Platform::RUBY }
end end
return unless non_ruby return unless non_ruby
if platforms.length == 1 then if platforms.length == 1
title = platforms.values.length == 1 ? 'Platform' : 'Platforms' title = platforms.values.length == 1 ? 'Platform' : 'Platforms'
entry << " #{title}: #{platforms.values.sort.join ', '}\n" entry << " #{title}: #{platforms.values.sort.join ', '}\n"
else else
@ -351,7 +351,7 @@ is too hard to use.
end end
end end
def spec_summary entry, spec def spec_summary(entry, spec)
summary = truncate_text(spec.summary, "the summary for #{spec.full_name}") summary = truncate_text(spec.summary, "the summary for #{spec.full_name}")
entry << "\n\n" << format_text(summary, 68, 4) entry << "\n\n" << format_text(summary, 68, 4)
end end

Просмотреть файл

@ -60,7 +60,7 @@ Use --overwrite to force rebuilding of documentation.
end end
def execute def execute
specs = if options[:all] then specs = if options[:all]
Gem::Specification.to_a Gem::Specification.to_a
else else
get_all_gem_names.map do |name| get_all_gem_names.map do |name|
@ -68,7 +68,7 @@ Use --overwrite to force rebuilding of documentation.
end.flatten.uniq end.flatten.uniq
end end
if specs.empty? then if specs.empty?
alert_error 'No matching gems found' alert_error 'No matching gems found'
terminate_interaction 1 terminate_interaction 1
end end
@ -78,7 +78,7 @@ Use --overwrite to force rebuilding of documentation.
doc.force = options[:overwrite] doc.force = options[:overwrite]
if options[:overwrite] then if options[:overwrite]
FileUtils.rm_rf File.join(spec.doc_dir, 'ri') FileUtils.rm_rf File.join(spec.doc_dir, 'ri')
FileUtils.rm_rf File.join(spec.doc_dir, 'rdoc') FileUtils.rm_rf File.join(spec.doc_dir, 'rdoc')
end end
@ -94,4 +94,3 @@ Use --overwrite to force rebuilding of documentation.
end end
end end

Просмотреть файл

@ -38,4 +38,3 @@ To list local gems use the list command.
end end
end end

Просмотреть файл

@ -9,7 +9,7 @@ class Gem::Commands::ServerCommand < Gem::Command
:port => 8808, :gemdir => [], :daemon => false :port => 8808, :gemdir => [], :daemon => false
OptionParser.accept :Port do |port| OptionParser.accept :Port do |port|
if port =~ /\A\d+\z/ then if port =~ /\A\d+\z/
port = Integer port port = Integer port
raise OptionParser::InvalidArgument, "#{port}: not a port number" if raise OptionParser::InvalidArgument, "#{port}: not a port number" if
port > 65535 port > 65535
@ -84,4 +84,3 @@ You can set up a shortcut to gem server documentation using the URL:
end end
end end

Просмотреть файл

@ -6,8 +6,8 @@ require 'rubygems/command'
# RubyGems checkout or tarball. # RubyGems checkout or tarball.
class Gem::Commands::SetupCommand < Gem::Command class Gem::Commands::SetupCommand < Gem::Command
HISTORY_HEADER = /^===\s*[\d.a-zA-Z]+\s*\/\s*\d{4}-\d{2}-\d{2}\s*$/ HISTORY_HEADER = /^===\s*[\d.a-zA-Z]+\s*\/\s*\d{4}-\d{2}-\d{2}\s*$/.freeze
VERSION_MATCHER = /^===\s*([\d.a-zA-Z]+)\s*\/\s*\d{4}-\d{2}-\d{2}\s*$/ VERSION_MATCHER = /^===\s*([\d.a-zA-Z]+)\s*\/\s*\d{4}-\d{2}-\d{2}\s*$/.freeze
ENV_PATHS = %w[/usr/bin/env /bin/env].freeze ENV_PATHS = %w[/usr/bin/env /bin/env].freeze
@ -62,7 +62,7 @@ class Gem::Commands::SetupCommand < Gem::Command
add_option '--[no-]rdoc', add_option '--[no-]rdoc',
'Generate RDoc documentation for RubyGems' do |value, options| 'Generate RDoc documentation for RubyGems' do |value, options|
if value then if value
options[:document] << 'rdoc' options[:document] << 'rdoc'
else else
options[:document].delete 'rdoc' options[:document].delete 'rdoc'
@ -73,7 +73,7 @@ class Gem::Commands::SetupCommand < Gem::Command
add_option '--[no-]ri', add_option '--[no-]ri',
'Generate RI documentation for RubyGems' do |value, options| 'Generate RI documentation for RubyGems' do |value, options|
if value then if value
options[:document] << 'ri' options[:document] << 'ri'
else else
options[:document].delete 'ri' options[:document].delete 'ri'
@ -99,7 +99,7 @@ class Gem::Commands::SetupCommand < Gem::Command
def check_ruby_version def check_ruby_version
required_version = Gem::Requirement.new '>= 1.8.7' required_version = Gem::Requirement.new '>= 1.8.7'
unless required_version.satisfied_by? Gem.ruby_version then unless required_version.satisfied_by? Gem.ruby_version
alert_error "Expected Ruby version #{required_version}, is #{Gem.ruby_version}" alert_error "Expected Ruby version #{required_version}, is #{Gem.ruby_version}"
terminate_interaction 1 terminate_interaction 1
end end
@ -139,7 +139,7 @@ By default, this RubyGems will install gem as:
install_destdir = options[:destdir] install_destdir = options[:destdir]
unless install_destdir.empty? then unless install_destdir.empty?
ENV['GEM_HOME'] ||= File.join(install_destdir, ENV['GEM_HOME'] ||= File.join(install_destdir,
Gem.default_dir.gsub(/^[a-zA-Z]:/, '')) Gem.default_dir.gsub(/^[a-zA-Z]:/, ''))
end end
@ -147,7 +147,7 @@ By default, this RubyGems will install gem as:
check_ruby_version check_ruby_version
require 'fileutils' require 'fileutils'
if Gem.configuration.really_verbose then if Gem.configuration.really_verbose
extend FileUtils::Verbose extend FileUtils::Verbose
else else
extend FileUtils extend FileUtils
@ -180,7 +180,7 @@ By default, this RubyGems will install gem as:
documentation_success = install_rdoc documentation_success = install_rdoc
say say
if @verbose then if @verbose
say "-" * 78 say "-" * 78
say say
end end
@ -201,14 +201,14 @@ By default, this RubyGems will install gem as:
say @bin_file_names.map { |name| "\t#{name}\n" } say @bin_file_names.map { |name| "\t#{name}\n" }
say say
unless @bin_file_names.grep(/#{File::SEPARATOR}gem$/) then unless @bin_file_names.grep(/#{File::SEPARATOR}gem$/)
say "If `gem` was installed by a previous RubyGems installation, you may need" say "If `gem` was installed by a previous RubyGems installation, you may need"
say "to remove it by hand." say "to remove it by hand."
say say
end end
if documentation_success if documentation_success
if options[:document].include? 'rdoc' then if options[:document].include? 'rdoc'
say "Rdoc documentation was installed. You may now invoke:" say "Rdoc documentation was installed. You may now invoke:"
say " gem server" say " gem server"
say "and then peruse beautifully formatted documentation for your gems" say "and then peruse beautifully formatted documentation for your gems"
@ -219,7 +219,7 @@ By default, this RubyGems will install gem as:
say say
end end
if options[:document].include? 'ri' then if options[:document].include? 'ri'
say "Ruby Interactive (ri) documentation was installed. ri is kind of like man " say "Ruby Interactive (ri) documentation was installed. ri is kind of like man "
say "pages for Ruby libraries. You may access it like this:" say "pages for Ruby libraries. You may access it like this:"
say " ri Classname" say " ri Classname"
@ -250,7 +250,7 @@ By default, this RubyGems will install gem as:
bin_files -= %w[update_rubygems bundler bundle_ruby] bin_files -= %w[update_rubygems bundler bundle_ruby]
bin_files.each do |bin_file| bin_files.each do |bin_file|
bin_file_formatted = if options[:format_executable] then bin_file_formatted = if options[:format_executable]
Gem.default_exec_format % bin_file Gem.default_exec_format % bin_file
else else
bin_file bin_file
@ -308,7 +308,7 @@ By default, this RubyGems will install gem as:
end end
end end
def install_file file, dest_dir def install_file(file, dest_dir)
dest_file = File.join dest_dir, file dest_file = File.join dest_dir, file
dest_dir = File.dirname dest_file dest_dir = File.dirname dest_file
unless File.directory? dest_dir unless File.directory? dest_dir
@ -354,7 +354,7 @@ By default, this RubyGems will install gem as:
if File.writable? gem_doc_dir and if File.writable? gem_doc_dir and
(not File.exist? rubygems_doc_dir or (not File.exist? rubygems_doc_dir or
File.writable? rubygems_doc_dir) then File.writable? rubygems_doc_dir)
say "Removing old RubyGems RDoc and ri" if @verbose say "Removing old RubyGems RDoc and ri" if @verbose
Dir[File.join(Gem.dir, 'doc', 'rubygems-[0-9]*')].each do |dir| Dir[File.join(Gem.dir, 'doc', 'rubygems-[0-9]*')].each do |dir|
rm_rf dir rm_rf dir
@ -374,7 +374,7 @@ By default, this RubyGems will install gem as:
rdoc.generate rdoc.generate
return true return true
elsif @verbose then elsif @verbose
say "Skipping RDoc generation, #{gem_doc_dir} not writable" say "Skipping RDoc generation, #{gem_doc_dir} not writable"
say "Set the GEM_HOME environment variable if you want RDoc generated" say "Set the GEM_HOME environment variable if you want RDoc generated"
end end
@ -456,7 +456,7 @@ By default, this RubyGems will install gem as:
prefix = options[:prefix] prefix = options[:prefix]
site_or_vendor = options[:site_or_vendor] site_or_vendor = options[:site_or_vendor]
if prefix.empty? then if prefix.empty?
lib_dir = RbConfig::CONFIG[site_or_vendor] lib_dir = RbConfig::CONFIG[site_or_vendor]
bin_dir = RbConfig::CONFIG['bindir'] bin_dir = RbConfig::CONFIG['bindir']
else else
@ -467,7 +467,7 @@ By default, this RubyGems will install gem as:
# just in case Apple and RubyGems don't get this patched up proper. # just in case Apple and RubyGems don't get this patched up proper.
(prefix == RbConfig::CONFIG['libdir'] or (prefix == RbConfig::CONFIG['libdir'] or
# this one is important # this one is important
prefix == File.join(RbConfig::CONFIG['libdir'], 'ruby')) then prefix == File.join(RbConfig::CONFIG['libdir'], 'ruby'))
lib_dir = RbConfig::CONFIG[site_or_vendor] lib_dir = RbConfig::CONFIG[site_or_vendor]
bin_dir = RbConfig::CONFIG['bindir'] bin_dir = RbConfig::CONFIG['bindir']
else else
@ -476,7 +476,7 @@ By default, this RubyGems will install gem as:
end end
end end
unless install_destdir.empty? then unless install_destdir.empty?
lib_dir = File.join install_destdir, lib_dir.gsub(/^[a-zA-Z]:/, '') lib_dir = File.join install_destdir, lib_dir.gsub(/^[a-zA-Z]:/, '')
bin_dir = File.join install_destdir, bin_dir.gsub(/^[a-zA-Z]:/, '') bin_dir = File.join install_destdir, bin_dir.gsub(/^[a-zA-Z]:/, '')
end end
@ -484,13 +484,13 @@ By default, this RubyGems will install gem as:
[lib_dir, bin_dir] [lib_dir, bin_dir]
end end
def pem_files_in dir def pem_files_in(dir)
Dir.chdir dir do Dir.chdir dir do
Dir[File.join('**', '*pem')] Dir[File.join('**', '*pem')]
end end
end end
def rb_files_in dir def rb_files_in(dir)
Dir.chdir dir do Dir.chdir dir do
Dir[File.join('**', '*rb')] Dir[File.join('**', '*rb')]
end end
@ -505,7 +505,7 @@ By default, this RubyGems will install gem as:
end end
# for cleanup old bundler files # for cleanup old bundler files
def template_files_in dir def template_files_in(dir)
Dir.chdir dir do Dir.chdir dir do
(Dir[File.join('templates', '**', '{*,.*}')]). (Dir[File.join('templates', '**', '{*,.*}')]).
select{|f| !File.directory?(f)} select{|f| !File.directory?(f)}
@ -544,7 +544,7 @@ abort "#{deprecation_message}"
end end
end end
def remove_old_lib_files lib_dir def remove_old_lib_files(lib_dir)
lib_dirs = { File.join(lib_dir, 'rubygems') => 'lib/rubygems' } lib_dirs = { File.join(lib_dir, 'rubygems') => 'lib/rubygems' }
lib_dirs[File.join(lib_dir, 'bundler')] = 'bundler/lib/bundler' if Gem::USE_BUNDLER_FOR_GEMDEPS lib_dirs[File.join(lib_dir, 'bundler')] = 'bundler/lib/bundler' if Gem::USE_BUNDLER_FOR_GEMDEPS
lib_dirs.each do |old_lib_dir, new_lib_dir| lib_dirs.each do |old_lib_dir, new_lib_dir|
@ -575,7 +575,7 @@ abort "#{deprecation_message}"
release_notes = File.join Dir.pwd, 'History.txt' release_notes = File.join Dir.pwd, 'History.txt'
release_notes = release_notes =
if File.exist? release_notes then if File.exist? release_notes
history = File.read release_notes history = File.read release_notes
history.force_encoding Encoding::UTF_8 history.force_encoding Encoding::UTF_8

Просмотреть файл

@ -12,7 +12,6 @@ class Gem::Commands::SigninCommand < Gem::Command
add_option('--host HOST', 'Push to another gemcutter-compatible host') do |value, options| add_option('--host HOST', 'Push to another gemcutter-compatible host') do |value, options|
options[:host] = value options[:host] = value
end end
end end
def description # :nodoc: def description # :nodoc:

Просмотреть файл

@ -19,9 +19,9 @@ class Gem::Commands::SignoutCommand < Gem::Command
def execute def execute
credentials_path = Gem.configuration.credentials_path credentials_path = Gem.configuration.credentials_path
if !File.exist?(credentials_path) then if !File.exist?(credentials_path)
alert_error 'You are not currently signed in.' alert_error 'You are not currently signed in.'
elsif !File.writable?(credentials_path) then elsif !File.writable?(credentials_path)
alert_error "File '#{Gem.configuration.credentials_path}' is read-only."\ alert_error "File '#{Gem.configuration.credentials_path}' is read-only."\
' Please make sure it is writable.' ' Please make sure it is writable.'
else else

Просмотреть файл

@ -38,13 +38,13 @@ class Gem::Commands::SourcesCommand < Gem::Command
add_proxy_option add_proxy_option
end end
def add_source source_uri # :nodoc: def add_source(source_uri) # :nodoc:
check_rubygems_https source_uri check_rubygems_https source_uri
source = Gem::Source.new source_uri source = Gem::Source.new source_uri
begin begin
if Gem.sources.include? source then if Gem.sources.include? source
say "source #{source_uri} already present in the cache" say "source #{source_uri} already present in the cache"
else else
source.load_specs :released source.load_specs :released
@ -62,11 +62,11 @@ class Gem::Commands::SourcesCommand < Gem::Command
end end
end end
def check_rubygems_https source_uri # :nodoc: def check_rubygems_https(source_uri) # :nodoc:
uri = URI source_uri uri = URI source_uri
if uri.scheme and uri.scheme.downcase == 'http' and if uri.scheme and uri.scheme.downcase == 'http' and
uri.host.downcase == 'rubygems.org' then uri.host.downcase == 'rubygems.org'
question = <<-QUESTION.chomp question = <<-QUESTION.chomp
https://rubygems.org is recommended for security over #{uri} https://rubygems.org is recommended for security over #{uri}
@ -81,10 +81,10 @@ Do you want to add this insecure source?
path = Gem.spec_cache_dir path = Gem.spec_cache_dir
FileUtils.rm_rf path FileUtils.rm_rf path
unless File.exist? path then unless File.exist? path
say "*** Removed specs cache ***" say "*** Removed specs cache ***"
else else
unless File.writable? path then unless File.writable? path
say "*** Unable to remove source cache (write protected) ***" say "*** Unable to remove source cache (write protected) ***"
else else
say "*** Unable to remove source cache ***" say "*** Unable to remove source cache ***"
@ -175,8 +175,8 @@ To remove a source use the --remove argument:
list if list? list if list?
end end
def remove_source source_uri # :nodoc: def remove_source(source_uri) # :nodoc:
unless Gem.sources.include? source_uri then unless Gem.sources.include? source_uri
say "source #{source_uri} not present in cache" say "source #{source_uri} not present in cache"
else else
Gem.sources.delete source_uri Gem.sources.delete source_uri
@ -195,12 +195,12 @@ To remove a source use the --remove argument:
say "source cache successfully updated" say "source cache successfully updated"
end end
def remove_cache_file desc, path # :nodoc: def remove_cache_file(desc, path) # :nodoc:
FileUtils.rm_rf path FileUtils.rm_rf path
if not File.exist?(path) then if not File.exist?(path)
say "*** Removed #{desc} source cache ***" say "*** Removed #{desc} source cache ***"
elsif not File.writable?(path) then elsif not File.writable?(path)
say "*** Unable to remove #{desc} source cache (write protected) ***" say "*** Unable to remove #{desc} source cache (write protected) ***"
else else
say "*** Unable to remove #{desc} source cache ***" say "*** Unable to remove #{desc} source cache ***"
@ -208,4 +208,3 @@ To remove a source use the --remove argument:
end end
end end

Просмотреть файл

@ -75,7 +75,7 @@ Specific fields in the specification can be extracted in YAML format:
specs = [] specs = []
gem = options[:args].shift gem = options[:args].shift
unless gem then unless gem
raise Gem::CommandLineError, raise Gem::CommandLineError,
"Please specify a gem name or file on the command line" "Please specify a gem name or file on the command line"
end end
@ -105,29 +105,29 @@ Specific fields in the specification can be extracted in YAML format:
raise Gem::CommandLineError, "--ruby and FIELD are mutually exclusive" if raise Gem::CommandLineError, "--ruby and FIELD are mutually exclusive" if
field and options[:format] == :ruby field and options[:format] == :ruby
if local? then if local?
if File.exist? gem then if File.exist? gem
specs << Gem::Package.new(gem).spec rescue nil specs << Gem::Package.new(gem).spec rescue nil
end end
if specs.empty? then if specs.empty?
specs.push(*dep.matching_specs) specs.push(*dep.matching_specs)
end end
end end
if remote? then if remote?
dep.prerelease = options[:prerelease] dep.prerelease = options[:prerelease]
found, _ = Gem::SpecFetcher.fetcher.spec_for_dependency dep found, _ = Gem::SpecFetcher.fetcher.spec_for_dependency dep
specs.push(*found.map { |spec,| spec }) specs.push(*found.map { |spec,| spec })
end end
if specs.empty? then if specs.empty?
alert_error "No gem matching '#{dep}' found" alert_error "No gem matching '#{dep}' found"
terminate_interaction 1 terminate_interaction 1
end end
unless options[:all] then unless options[:all]
specs = [specs.max_by { |s| s.version }] specs = [specs.max_by { |s| s.version }]
end end

Просмотреть файл

@ -81,7 +81,7 @@ class Gem::Commands::UninstallCommand < Gem::Command
add_option('--vendor', add_option('--vendor',
'Uninstall gem from the vendor directory.', 'Uninstall gem from the vendor directory.',
'Only for use by gem repackagers.') do |value, options| 'Only for use by gem repackagers.') do |value, options|
unless Gem.vendor_dir then unless Gem.vendor_dir
raise OptionParser::InvalidOption.new 'your platform is not supported' raise OptionParser::InvalidOption.new 'your platform is not supported'
end end
@ -115,9 +115,9 @@ that is a dependency of an existing gem. You can use the
end end
def execute def execute
if options[:all] and not options[:args].empty? then if options[:all] and not options[:args].empty?
uninstall_specific uninstall_specific
elsif options[:all] then elsif options[:all]
uninstall_all uninstall_all
else else
uninstall_specific uninstall_specific

Просмотреть файл

@ -79,15 +79,15 @@ command help for an example.
dependency = Gem::Dependency.new name, options[:version] dependency = Gem::Dependency.new name, options[:version]
path = get_path dependency path = get_path dependency
unless path then unless path
alert_error "Gem '#{name}' not installed nor fetchable." alert_error "Gem '#{name}' not installed nor fetchable."
next next
end end
if @options[:spec] then if @options[:spec]
spec, metadata = get_metadata path, security_policy spec, metadata = get_metadata path, security_policy
if metadata.nil? then if metadata.nil?
alert_error "--spec is unsupported on '#{name}' (old format gem)" alert_error "--spec is unsupported on '#{name}' (old format gem)"
next next
end end
@ -152,7 +152,7 @@ command help for an example.
# TODO: It just uses Gem.dir for now. What's an easy way to get the list of # TODO: It just uses Gem.dir for now. What's an easy way to get the list of
# source directories? # source directories?
def get_path dependency def get_path(dependency)
return dependency.name if dependency.name =~ /\.gem$/i return dependency.name if dependency.name =~ /\.gem$/i
specs = dependency.matching_specs specs = dependency.matching_specs
@ -180,7 +180,7 @@ command help for an example.
#-- #--
# TODO move to Gem::Package as #raw_spec or something # TODO move to Gem::Package as #raw_spec or something
def get_metadata path, security_policy = nil def get_metadata(path, security_policy = nil)
format = Gem::Package.new path, security_policy format = Gem::Package.new path, security_policy
spec = format.spec spec = format.spec
@ -202,4 +202,3 @@ command help for an example.
end end
end end

Просмотреть файл

@ -68,8 +68,8 @@ command to remove old versions.
"#{program_name} GEMNAME [GEMNAME ...]" "#{program_name} GEMNAME [GEMNAME ...]"
end end
def check_latest_rubygems version # :nodoc: def check_latest_rubygems(version) # :nodoc:
if Gem.rubygems_version == version then if Gem.rubygems_version == version
say "Latest version already installed. Done." say "Latest version already installed. Done."
terminate_interaction terminate_interaction
end end
@ -78,14 +78,14 @@ command to remove old versions.
end end
def check_update_arguments # :nodoc: def check_update_arguments # :nodoc:
unless options[:args].empty? then unless options[:args].empty?
alert_error "Gem names are not allowed with the --system option" alert_error "Gem names are not allowed with the --system option"
terminate_interaction 1 terminate_interaction 1
end end
end end
def execute def execute
if options[:system] then if options[:system]
update_rubygems update_rubygems
return return
end end
@ -111,7 +111,7 @@ command to remove old versions.
updated_names = updated.map { |spec| spec.name } updated_names = updated.map { |spec| spec.name }
not_updated_names = options[:args].uniq - updated_names not_updated_names = options[:args].uniq - updated_names
if updated.empty? then if updated.empty?
say "Nothing to update" say "Nothing to update"
else else
say "Gems updated: #{updated_names.join(' ')}" say "Gems updated: #{updated_names.join(' ')}"
@ -119,7 +119,7 @@ command to remove old versions.
end end
end end
def fetch_remote_gems spec # :nodoc: def fetch_remote_gems(spec) # :nodoc:
dependency = Gem::Dependency.new spec.name, "> #{spec.version}" dependency = Gem::Dependency.new spec.name, "> #{spec.version}"
dependency.prerelease = options[:prerelease] dependency.prerelease = options[:prerelease]
@ -138,7 +138,7 @@ command to remove old versions.
hig = {} # highest installed gems hig = {} # highest installed gems
Gem::Specification.each do |spec| Gem::Specification.each do |spec|
if hig[spec.name].nil? or hig[spec.name].version < spec.version then if hig[spec.name].nil? or hig[spec.name].version < spec.version
hig[spec.name] = spec hig[spec.name] = spec
end end
end end
@ -146,7 +146,7 @@ command to remove old versions.
hig hig
end end
def highest_remote_version spec # :nodoc: def highest_remote_version(spec) # :nodoc:
spec_tuples = fetch_remote_gems spec spec_tuples = fetch_remote_gems spec
matching_gems = spec_tuples.select do |g,_| matching_gems = spec_tuples.select do |g,_|
@ -160,7 +160,7 @@ command to remove old versions.
highest_remote_gem.first.version highest_remote_gem.first.version
end end
def install_rubygems version # :nodoc: def install_rubygems(version) # :nodoc:
args = update_rubygems_arguments args = update_rubygems_arguments
update_dir = File.join Gem.dir, 'gems', "rubygems-update-#{version}" update_dir = File.join Gem.dir, 'gems', "rubygems-update-#{version}"
@ -177,7 +177,7 @@ command to remove old versions.
version = options[:system] version = options[:system]
update_latest = version == true update_latest = version == true
if update_latest then if update_latest
version = Gem::Version.new Gem::VERSION version = Gem::Version.new Gem::VERSION
requirement = Gem::Requirement.new ">= #{Gem::VERSION}" requirement = Gem::Requirement.new ">= #{Gem::VERSION}"
else else
@ -196,7 +196,7 @@ command to remove old versions.
gems_to_update = which_to_update hig, options[:args], :system gems_to_update = which_to_update hig, options[:args], :system
_, up_ver = gems_to_update.first _, up_ver = gems_to_update.first
target = if update_latest then target = if update_latest
up_ver up_ver
else else
version version
@ -205,7 +205,7 @@ command to remove old versions.
return target, requirement return target, requirement
end end
def update_gem name, version = Gem::Requirement.default def update_gem(name, version = Gem::Requirement.default)
return if @updated.any? { |spec| spec.name == name } return if @updated.any? { |spec| spec.name == name }
update_options = options.dup update_options = options.dup
@ -225,7 +225,7 @@ command to remove old versions.
end end
end end
def update_gems gems_to_update def update_gems(gems_to_update)
gems_to_update.uniq.sort.each do |(name, version)| gems_to_update.uniq.sort.each do |(name, version)|
update_gem name, version update_gem name, version
end end
@ -264,7 +264,7 @@ command to remove old versions.
args args
end end
def which_to_update highest_installed_gems, gem_names, system = false def which_to_update(highest_installed_gems, gem_names, system = false)
result = [] result = []
highest_installed_gems.each do |l_name, l_spec| highest_installed_gems.each do |l_name, l_spec|
@ -273,7 +273,7 @@ command to remove old versions.
highest_remote_ver = highest_remote_version l_spec highest_remote_ver = highest_remote_version l_spec
if system or (l_spec.version < highest_remote_ver) then if system or (l_spec.version < highest_remote_ver)
result << [l_spec.name, [l_spec.version, highest_remote_ver].max] result << [l_spec.name, [l_spec.version, highest_remote_ver].max]
end end
end end

Просмотреть файл

@ -44,8 +44,8 @@ requiring to see why it does not behave as you expect.
spec = Gem::Specification.find_by_path arg spec = Gem::Specification.find_by_path arg
if spec then if spec
if options[:search_gems_first] then if options[:search_gems_first]
dirs = spec.full_require_paths + $LOAD_PATH dirs = spec.full_require_paths + $LOAD_PATH
else else
dirs = $LOAD_PATH + spec.full_require_paths dirs = $LOAD_PATH + spec.full_require_paths
@ -55,7 +55,7 @@ requiring to see why it does not behave as you expect.
# TODO: this is totally redundant and stupid # TODO: this is totally redundant and stupid
paths = find_paths arg, dirs paths = find_paths arg, dirs
if paths.empty? then if paths.empty?
alert_error "Can't find Ruby library file or shared library #{arg}" alert_error "Can't find Ruby library file or shared library #{arg}"
found &&= false found &&= false
@ -73,7 +73,7 @@ requiring to see why it does not behave as you expect.
dirs.each do |dir| dirs.each do |dir|
Gem.suffixes.each do |ext| Gem.suffixes.each do |ext|
full_path = File.join dir, "#{package_name}#{ext}" full_path = File.join dir, "#{package_name}#{ext}"
if File.exist? full_path and not File.directory? full_path then if File.exist? full_path and not File.directory? full_path
result << full_path result << full_path
return result unless options[:show_all] return result unless options[:show_all]
end end
@ -88,4 +88,3 @@ requiring to see why it does not behave as you expect.
end end
end end

Просмотреть файл

@ -51,7 +51,7 @@ data you will need to change them immediately and yank your gem.
version = get_version_from_requirements(options[:version]) version = get_version_from_requirements(options[:version])
platform = get_platform_from_requirements(options) platform = get_platform_from_requirements(options)
if version then if version
yank_gem(version, platform) yank_gem(version, platform)
else else
say "A version argument is required: #{usage}" say "A version argument is required: #{usage}"
@ -93,4 +93,3 @@ data you will need to change them immediately and yank your gem.
end end
end end

Просмотреть файл

@ -174,12 +174,12 @@ class Gem::ConfigFile
arg_list = [] arg_list = []
args.each do |arg| args.each do |arg|
if need_config_file_name then if need_config_file_name
@config_file_name = arg @config_file_name = arg
need_config_file_name = false need_config_file_name = false
elsif arg =~ /^--config-file=(.*)/ then elsif arg =~ /^--config-file=(.*)/
@config_file_name = $1 @config_file_name = $1
elsif arg =~ /^--config-file$/ then elsif arg =~ /^--config-file$/
need_config_file_name = true need_config_file_name = true
else else
arg_list << arg arg_list << arg
@ -281,13 +281,13 @@ if you believe they were disclosed to a third party.
def load_api_keys def load_api_keys
check_credentials_permissions check_credentials_permissions
@api_keys = if File.exist? credentials_path then @api_keys = if File.exist? credentials_path
load_file(credentials_path) load_file(credentials_path)
else else
@hash @hash
end end
if @api_keys.key? :rubygems_api_key then if @api_keys.key? :rubygems_api_key
@rubygems_api_key = @api_keys[:rubygems_api_key] @rubygems_api_key = @api_keys[:rubygems_api_key]
@api_keys[:rubygems] = @api_keys.delete :rubygems_api_key unless @api_keys[:rubygems] = @api_keys.delete :rubygems_api_key unless
@api_keys.key? :rubygems @api_keys.key? :rubygems
@ -306,7 +306,7 @@ if you believe they were disclosed to a third party.
## ##
# Sets the RubyGems.org API key to +api_key+ # Sets the RubyGems.org API key to +api_key+
def rubygems_api_key= api_key def rubygems_api_key=(api_key)
set_api_key :rubygems_api_key, api_key set_api_key :rubygems_api_key, api_key
@rubygems_api_key = api_key @rubygems_api_key = api_key
@ -315,7 +315,7 @@ if you believe they were disclosed to a third party.
## ##
# Set a specific host's API key to +api_key+ # Set a specific host's API key to +api_key+
def set_api_key host, api_key def set_api_key(host, api_key)
check_credentials_permissions check_credentials_permissions
config = load_file(credentials_path).merge(host => api_key) config = load_file(credentials_path).merge(host => api_key)

Просмотреть файл

@ -31,7 +31,7 @@ module Kernel
# The normal <tt>require</tt> functionality of returning false if # The normal <tt>require</tt> functionality of returning false if
# that file has already been loaded is preserved. # that file has already been loaded is preserved.
def require path def require(path)
RUBYGEMS_ACTIVATION_MONITOR.enter RUBYGEMS_ACTIVATION_MONITOR.enter
path = path.to_path if path.respond_to? :to_path path = path.to_path if path.respond_to? :to_path
@ -49,7 +49,7 @@ module Kernel
# If there are no unresolved deps, then we can use just try # If there are no unresolved deps, then we can use just try
# normal require handle loading a gem from the rescue below. # normal require handle loading a gem from the rescue below.
if Gem::Specification.unresolved_deps.empty? then if Gem::Specification.unresolved_deps.empty?
RUBYGEMS_ACTIVATION_MONITOR.exit RUBYGEMS_ACTIVATION_MONITOR.exit
return gem_original_require(path) return gem_original_require(path)
end end
@ -79,7 +79,7 @@ module Kernel
# requested, then find_in_unresolved_tree will find d.rb in d because # requested, then find_in_unresolved_tree will find d.rb in d because
# it's a dependency of c. # it's a dependency of c.
# #
if found_specs.empty? then if found_specs.empty?
found_specs = Gem::Specification.find_in_unresolved_tree path found_specs = Gem::Specification.find_in_unresolved_tree path
found_specs.each do |found_spec| found_specs.each do |found_spec|
@ -94,7 +94,7 @@ module Kernel
# versions of the same gem # versions of the same gem
names = found_specs.map(&:name).uniq names = found_specs.map(&:name).uniq
if names.size > 1 then if names.size > 1
RUBYGEMS_ACTIVATION_MONITOR.exit RUBYGEMS_ACTIVATION_MONITOR.exit
raise Gem::LoadError, "#{path} found in multiple gems: #{names.join ', '}" raise Gem::LoadError, "#{path} found in multiple gems: #{names.join ', '}"
end end
@ -103,7 +103,7 @@ module Kernel
# at the highest version. # at the highest version.
valid = found_specs.find { |s| !s.has_conflicts? } valid = found_specs.find { |s| !s.has_conflicts? }
unless valid then unless valid
le = Gem::LoadError.new "unable to find a version of '#{names.first}' to activate" le = Gem::LoadError.new "unable to find a version of '#{names.first}' to activate"
le.name = names.first le.name = names.first
RUBYGEMS_ACTIVATION_MONITOR.exit RUBYGEMS_ACTIVATION_MONITOR.exit
@ -120,7 +120,7 @@ module Kernel
begin begin
if load_error.message.start_with?("Could not find") or if load_error.message.start_with?("Could not find") or
(load_error.message.end_with?(path) and Gem.try_activate(path)) then (load_error.message.end_with?(path) and Gem.try_activate(path))
require_again = true require_again = true
end end
ensure ensure

Просмотреть файл

@ -28,13 +28,13 @@ module Gem
# specified in the environment # specified in the environment
def self.default_dir def self.default_dir
path = if defined? RUBY_FRAMEWORK_VERSION then path = if defined? RUBY_FRAMEWORK_VERSION
[ [
File.dirname(RbConfig::CONFIG['sitedir']), File.dirname(RbConfig::CONFIG['sitedir']),
'Gems', 'Gems',
RbConfig::CONFIG['ruby_version'] RbConfig::CONFIG['ruby_version']
] ]
elsif RbConfig::CONFIG['rubylibprefix'] then elsif RbConfig::CONFIG['rubylibprefix']
[ [
RbConfig::CONFIG['rubylibprefix'], RbConfig::CONFIG['rubylibprefix'],
'gems', 'gems',
@ -59,7 +59,7 @@ module Gem
# By default, the binary extensions are located side by side with their # By default, the binary extensions are located side by side with their
# Ruby counterparts, therefore nil is returned # Ruby counterparts, therefore nil is returned
def self.default_ext_dir_for base_dir def self.default_ext_dir_for(base_dir)
nil nil
end end
@ -103,7 +103,7 @@ module Gem
def self.default_exec_format def self.default_exec_format
exec_format = RbConfig::CONFIG['ruby_install_name'].sub('ruby', '%s') rescue '%s' exec_format = RbConfig::CONFIG['ruby_install_name'].sub('ruby', '%s') rescue '%s'
unless exec_format =~ /%s/ then unless exec_format =~ /%s/
raise Gem::Exception, raise Gem::Exception,
"[BUG] invalid exec_format #{exec_format.inspect}, no %s" "[BUG] invalid exec_format #{exec_format.inspect}, no %s"
end end
@ -115,7 +115,7 @@ module Gem
# The default directory for binaries # The default directory for binaries
def self.default_bindir def self.default_bindir
if defined? RUBY_FRAMEWORK_VERSION then # mac framework support if defined? RUBY_FRAMEWORK_VERSION # mac framework support
'/usr/bin' '/usr/bin'
else # generic install else # generic install
RbConfig::CONFIG['bindir'] RbConfig::CONFIG['bindir']
@ -126,7 +126,7 @@ module Gem
# A wrapper around RUBY_ENGINE const that may not be defined # A wrapper around RUBY_ENGINE const that may not be defined
def self.ruby_engine def self.ruby_engine
if defined? RUBY_ENGINE then if defined? RUBY_ENGINE
RUBY_ENGINE RUBY_ENGINE
else else
'ruby' 'ruby'
@ -165,7 +165,7 @@ module Gem
# Directory where vendor gems are installed. # Directory where vendor gems are installed.
def self.vendor_dir # :nodoc: def self.vendor_dir # :nodoc:
if vendor_dir = ENV['GEM_VENDOR'] then if vendor_dir = ENV['GEM_VENDOR']
return vendor_dir.dup return vendor_dir.dup
end end

Просмотреть файл

@ -36,7 +36,7 @@ class Gem::Dependency
# argument can optionally be the dependency type, which defaults to # argument can optionally be the dependency type, which defaults to
# <tt>:runtime</tt>. # <tt>:runtime</tt>.
def initialize name, *requirements def initialize(name, *requirements)
case name case name
when String then # ok when String then # ok
when Regexp then when Regexp then
@ -76,7 +76,7 @@ class Gem::Dependency
end end
def inspect # :nodoc: def inspect # :nodoc:
if prerelease? then if prerelease?
"<%s type=%p name=%p requirements=%p prerelease=ok>" % "<%s type=%p name=%p requirements=%p prerelease=ok>" %
[self.class, self.type, self.name, requirement.to_s] [self.class, self.type, self.name, requirement.to_s]
else else
@ -100,7 +100,7 @@ class Gem::Dependency
@requirement.none? @requirement.none?
end end
def pretty_print q # :nodoc: def pretty_print(q) # :nodoc:
q.group 1, 'Gem::Dependency.new(', ')' do q.group 1, 'Gem::Dependency.new(', ')' do
q.pp name q.pp name
q.text ',' q.text ','
@ -152,7 +152,7 @@ class Gem::Dependency
end end
def to_s # :nodoc: def to_s # :nodoc:
if type != :runtime then if type != :runtime
"#{name} (#{requirement}, #{type})" "#{name} (#{requirement}, #{type})"
else else
"#{name} (#{requirement})" "#{name} (#{requirement})"
@ -170,7 +170,7 @@ class Gem::Dependency
@type == :runtime || !@type @type == :runtime || !@type
end end
def == other # :nodoc: def ==(other) # :nodoc:
Gem::Dependency === other && Gem::Dependency === other &&
self.name == other.name && self.name == other.name &&
self.type == other.type && self.type == other.type &&
@ -180,7 +180,7 @@ class Gem::Dependency
## ##
# Dependencies are ordered by name. # Dependencies are ordered by name.
def <=> other def <=>(other)
self.name <=> other.name self.name <=> other.name
end end
@ -190,7 +190,7 @@ class Gem::Dependency
# other has only an equal version requirement that satisfies this # other has only an equal version requirement that satisfies this
# dependency. # dependency.
def =~ other def =~(other)
unless Gem::Dependency === other unless Gem::Dependency === other
return unless other.respond_to?(:name) && other.respond_to?(:version) return unless other.respond_to?(:name) && other.respond_to?(:version)
other = Gem::Dependency.new other.name, other.version other = Gem::Dependency.new other.name, other.version
@ -222,7 +222,7 @@ class Gem::Dependency
# NOTE: Unlike #matches_spec? this method does not return true when the # NOTE: Unlike #matches_spec? this method does not return true when the
# version is a prerelease version unless this is a prerelease dependency. # version is a prerelease version unless this is a prerelease dependency.
def match? obj, version=nil, allow_prerelease=false def match?(obj, version=nil, allow_prerelease=false)
if !version if !version
name = obj.name name = obj.name
version = obj.version version = obj.version
@ -249,7 +249,7 @@ class Gem::Dependency
# returns true when +spec+ is a prerelease version even if this dependency # returns true when +spec+ is a prerelease version even if this dependency
# is not a prerelease dependency. # is not a prerelease dependency.
def matches_spec? spec def matches_spec?(spec)
return false unless name === spec.name return false unless name === spec.name
return true if requirement.none? return true if requirement.none?
@ -259,8 +259,8 @@ class Gem::Dependency
## ##
# Merges the requirements of +other+ into this dependency # Merges the requirements of +other+ into this dependency
def merge other def merge(other)
unless name == other.name then unless name == other.name
raise ArgumentError, raise ArgumentError,
"#{self} and #{other} have different names" "#{self} and #{other} have different names"
end end
@ -275,7 +275,7 @@ class Gem::Dependency
self.class.new name, self_req.as_list.concat(other_req.as_list) self.class.new name, self_req.as_list.concat(other_req.as_list)
end end
def matching_specs platform_only = false def matching_specs(platform_only = false)
env_req = Gem.env_requirement(name) env_req = Gem.env_requirement(name)
matches = Gem::Specification.stubs_for(name).find_all { |spec| matches = Gem::Specification.stubs_for(name).find_all { |spec|
requirement.satisfied_by?(spec.version) && env_req.satisfied_by?(spec.version) requirement.satisfied_by?(spec.version) && env_req.satisfied_by?(spec.version)
@ -304,7 +304,7 @@ class Gem::Dependency
# TODO: check Gem.activated_spec[self.name] in case matches falls outside # TODO: check Gem.activated_spec[self.name] in case matches falls outside
if matches.empty? then if matches.empty?
specs = Gem::Specification.stubs_for name specs = Gem::Specification.stubs_for name
if specs.empty? if specs.empty?

Просмотреть файл

@ -66,7 +66,7 @@ class Gem::DependencyInstaller
# :wrappers:: See Gem::Installer::new # :wrappers:: See Gem::Installer::new
# :build_args:: See Gem::Installer::new # :build_args:: See Gem::Installer::new
def initialize options = {} def initialize(options = {})
@only_install_dir = !!options[:install_dir] @only_install_dir = !!options[:install_dir]
@install_dir = options[:install_dir] || Gem.dir @install_dir = options[:install_dir] || Gem.dir
@build_root = options[:build_root] @build_root = options[:build_root]
@ -110,7 +110,7 @@ class Gem::DependencyInstaller
#-- #--
# TODO remove at RubyGems 4, no longer used # TODO remove at RubyGems 4, no longer used
def add_found_dependencies to_do, dependency_list # :nodoc: def add_found_dependencies(to_do, dependency_list) # :nodoc:
seen = {} seen = {}
dependencies = Hash.new { |h, name| h[name] = Gem::Dependency.new name } dependencies = Hash.new { |h, name| h[name] = Gem::Dependency.new name }
@ -164,8 +164,8 @@ class Gem::DependencyInstaller
# Creates an AvailableSet to install from based on +dep_or_name+ and # Creates an AvailableSet to install from based on +dep_or_name+ and
# +version+ # +version+
def available_set_for dep_or_name, version # :nodoc: def available_set_for(dep_or_name, version) # :nodoc:
if String === dep_or_name then if String === dep_or_name
find_spec_by_name_and_version dep_or_name, version, @prerelease find_spec_by_name_and_version dep_or_name, version, @prerelease
else else
dep = dep_or_name.dup dep = dep_or_name.dup
@ -198,7 +198,7 @@ class Gem::DependencyInstaller
# sources. Gems are sorted with newer gems preferred over older gems, and # sources. Gems are sorted with newer gems preferred over older gems, and
# local gems preferred over remote gems. # local gems preferred over remote gems.
def find_gems_with_sources dep, best_only=false # :nodoc: def find_gems_with_sources(dep, best_only=false) # :nodoc:
set = Gem::AvailableSet.new set = Gem::AvailableSet.new
if consider_local? if consider_local?
@ -272,16 +272,16 @@ class Gem::DependencyInstaller
# +version+. Returns an Array of specs and sources required for # +version+. Returns an Array of specs and sources required for
# installation of the gem. # installation of the gem.
def find_spec_by_name_and_version gem_name, def find_spec_by_name_and_version(gem_name,
version = Gem::Requirement.default, version = Gem::Requirement.default,
prerelease = false prerelease = false)
set = Gem::AvailableSet.new set = Gem::AvailableSet.new
if consider_local? if consider_local?
if gem_name =~ /\.gem$/ and File.file? gem_name then if gem_name =~ /\.gem$/ and File.file? gem_name
src = Gem::Source::SpecificFile.new(gem_name) src = Gem::Source::SpecificFile.new(gem_name)
set.add src.spec, src set.add src.spec, src
elsif gem_name =~ /\.gem$/ then elsif gem_name =~ /\.gem$/
Dir[gem_name].each do |name| Dir[gem_name].each do |name|
begin begin
src = Gem::Source::SpecificFile.new name src = Gem::Source::SpecificFile.new name
@ -341,7 +341,7 @@ class Gem::DependencyInstaller
Gem::Specification.include?(spec) Gem::Specification.include?(spec)
} }
unless dependency_list.ok? or @ignore_dependencies or @force then unless dependency_list.ok? or @ignore_dependencies or @force
reason = dependency_list.why_not_ok?.map { |k,v| reason = dependency_list.why_not_ok?.map { |k,v|
"#{k} requires #{v.join(", ")}" "#{k} requires #{v.join(", ")}"
}.join("; ") }.join("; ")
@ -352,7 +352,7 @@ class Gem::DependencyInstaller
end end
deprecate :gather_dependencies, :none, 2018, 12 deprecate :gather_dependencies, :none, 2018, 12
def in_background what # :nodoc: def in_background(what) # :nodoc:
fork_happened = false fork_happened = false
if @build_docs_in_background and Process.respond_to?(:fork) if @build_docs_in_background and Process.respond_to?(:fork)
begin begin
@ -381,7 +381,7 @@ class Gem::DependencyInstaller
# c-1.a, b-1 and a-1.a will be installed. b-1.a will need to be installed # c-1.a, b-1 and a-1.a will be installed. b-1.a will need to be installed
# separately. # separately.
def install dep_or_name, version = Gem::Requirement.default def install(dep_or_name, version = Gem::Requirement.default)
request_set = resolve_dependencies dep_or_name, version request_set = resolve_dependencies dep_or_name, version
@installed_gems = [] @installed_gems = []
@ -425,16 +425,16 @@ class Gem::DependencyInstaller
end end
def install_development_deps # :nodoc: def install_development_deps # :nodoc:
if @development and @dev_shallow then if @development and @dev_shallow
:shallow :shallow
elsif @development then elsif @development
:all :all
else else
:none :none
end end
end end
def resolve_dependencies dep_or_name, version # :nodoc: def resolve_dependencies(dep_or_name, version) # :nodoc:
request_set = Gem::RequestSet.new request_set = Gem::RequestSet.new
request_set.development = @development request_set.development = @development
request_set.development_shallow = @dev_shallow request_set.development_shallow = @dev_shallow
@ -446,11 +446,11 @@ class Gem::DependencyInstaller
installer_set.ignore_installed = @only_install_dir installer_set.ignore_installed = @only_install_dir
if consider_local? if consider_local?
if dep_or_name =~ /\.gem$/ and File.file? dep_or_name then if dep_or_name =~ /\.gem$/ and File.file? dep_or_name
src = Gem::Source::SpecificFile.new dep_or_name src = Gem::Source::SpecificFile.new dep_or_name
installer_set.add_local dep_or_name, src.spec, src installer_set.add_local dep_or_name, src.spec, src
version = src.spec.version if version == Gem::Requirement.default version = src.spec.version if version == Gem::Requirement.default
elsif dep_or_name =~ /\.gem$/ then elsif dep_or_name =~ /\.gem$/
Dir[dep_or_name].each do |name| Dir[dep_or_name].each do |name|
begin begin
src = Gem::Source::SpecificFile.new name src = Gem::Source::SpecificFile.new name
@ -463,9 +463,9 @@ class Gem::DependencyInstaller
end end
dependency = dependency =
if spec = installer_set.local?(dep_or_name) then if spec = installer_set.local?(dep_or_name)
Gem::Dependency.new spec.name, version Gem::Dependency.new spec.name, version
elsif String === dep_or_name then elsif String === dep_or_name
Gem::Dependency.new dep_or_name, version Gem::Dependency.new dep_or_name, version
else else
dep_or_name dep_or_name
@ -479,7 +479,7 @@ class Gem::DependencyInstaller
request_set.always_install = installer_set.always_install request_set.always_install = installer_set.always_install
if @ignore_dependencies then if @ignore_dependencies
installer_set.ignore_dependencies = true installer_set.ignore_dependencies = true
request_set.ignore_dependencies = true request_set.ignore_dependencies = true
request_set.soft_missing = true request_set.soft_missing = true

Просмотреть файл

@ -40,7 +40,7 @@ class Gem::DependencyList
# Creates a new DependencyList. If +development+ is true, development # Creates a new DependencyList. If +development+ is true, development
# dependencies will be included. # dependencies will be included.
def initialize development = false def initialize(development = false)
@specs = [] @specs = []
@development = development @development = development
@ -79,8 +79,8 @@ class Gem::DependencyList
seen = {} seen = {}
sorted.each do |spec| sorted.each do |spec|
if index = seen[spec.name] then if index = seen[spec.name]
if result[index].version < spec.version then if result[index].version < spec.version
result[index] = spec result[index] = spec
end end
else else
@ -114,7 +114,7 @@ class Gem::DependencyList
why_not_ok?(:quick).empty? why_not_ok?(:quick).empty?
end end
def why_not_ok? quick = false def why_not_ok?(quick = false)
unsatisfied = Hash.new { |h,k| h[k] = [] } unsatisfied = Hash.new { |h,k| h[k] = [] }
each do |spec| each do |spec|
spec.runtime_dependencies.each do |dep| spec.runtime_dependencies.each do |dep|
@ -123,7 +123,7 @@ class Gem::DependencyList
dep.requirement.satisfied_by? installed_spec.version dep.requirement.satisfied_by? installed_spec.version
} }
unless inst or @specs.find { |s| s.satisfies_requirement? dep } then unless inst or @specs.find { |s| s.satisfies_requirement? dep }
unsatisfied[spec.name] << dep unsatisfied[spec.name] << dep
return unsatisfied if quick return unsatisfied if quick
end end
@ -172,7 +172,7 @@ class Gem::DependencyList
# satisfy items in +dependencies+ (a hash of gem names to arrays of # satisfy items in +dependencies+ (a hash of gem names to arrays of
# dependencies). # dependencies).
def remove_specs_unsatisfied_by dependencies def remove_specs_unsatisfied_by(dependencies)
specs.reject! { |spec| specs.reject! { |spec|
dep = dependencies[spec.name] dep = dependencies[spec.name]
dep and not dep.requirement.satisfied_by? spec.version dep and not dep.requirement.satisfied_by? spec.version
@ -200,7 +200,7 @@ class Gem::DependencyList
next if spec == other next if spec == other
other.dependencies.each do |dep| other.dependencies.each do |dep|
if spec.satisfies_requirement? dep then if spec.satisfies_requirement? dep
result[spec] << other result[spec] << other
end end
end end
@ -222,7 +222,7 @@ class Gem::DependencyList
dependencies.each do |dep| dependencies.each do |dep|
specs.each do |spec| specs.each do |spec|
if spec.satisfies_requirement? dep then if spec.satisfies_requirement? dep
yield spec yield spec
break break
end end
@ -241,4 +241,3 @@ class Gem::DependencyList
end end
end end

Просмотреть файл

@ -27,7 +27,7 @@ module Gem::Deprecate
@skip ||= false @skip ||= false
end end
def self.skip= v # :nodoc: def self.skip=(v) # :nodoc:
@skip = v @skip = v
end end
@ -47,7 +47,7 @@ module Gem::Deprecate
# telling the user of +repl+ (unless +repl+ is :none) and the # telling the user of +repl+ (unless +repl+ is :none) and the
# year/month that it is planned to go away. # year/month that it is planned to go away.
def deprecate name, repl, year, month def deprecate(name, repl, year, month)
class_eval { class_eval {
old = "_deprecated_#{name}" old = "_deprecated_#{name}"
alias_method old, name alias_method old, name
@ -68,4 +68,3 @@ module Gem::Deprecate
module_function :deprecate, :skip_during module_function :deprecate, :skip_during
end end

Просмотреть файл

@ -41,7 +41,7 @@ class Gem::Doctor
# #
# If +dry_run+ is true no files or directories will be removed. # If +dry_run+ is true no files or directories will be removed.
def initialize gem_repository, dry_run = false def initialize(gem_repository, dry_run = false)
@gem_repository = gem_repository @gem_repository = gem_repository
@dry_run = dry_run @dry_run = dry_run
@ -73,7 +73,7 @@ class Gem::Doctor
Gem.use_paths @gem_repository.to_s Gem.use_paths @gem_repository.to_s
unless gem_repository? then unless gem_repository?
say 'This directory does not appear to be a RubyGems repository, ' + say 'This directory does not appear to be a RubyGems repository, ' +
'skipping' 'skipping'
say say
@ -99,7 +99,7 @@ class Gem::Doctor
## ##
# Removes files in +sub_directory+ with +extension+ # Removes files in +sub_directory+ with +extension+
def doctor_child sub_directory, extension # :nodoc: def doctor_child(sub_directory, extension) # :nodoc:
directory = File.join(@gem_repository, sub_directory) directory = File.join(@gem_repository, sub_directory)
Dir.entries(directory).sort.each do |ent| Dir.entries(directory).sort.each do |ent|
@ -115,7 +115,7 @@ class Gem::Doctor
type = File.directory?(child) ? 'directory' : 'file' type = File.directory?(child) ? 'directory' : 'file'
action = if @dry_run then action = if @dry_run
'Extra' 'Extra'
else else
FileUtils.rm_r(child) FileUtils.rm_r(child)
@ -129,4 +129,3 @@ class Gem::Doctor
end end
end end

Просмотреть файл

@ -25,7 +25,7 @@ module Gem
# system. Instead of rescuing from this class, make sure to rescue from the # system. Instead of rescuing from this class, make sure to rescue from the
# superclass Gem::LoadError to catch all types of load errors. # superclass Gem::LoadError to catch all types of load errors.
class MissingSpecError < Gem::LoadError class MissingSpecError < Gem::LoadError
def initialize name, requirement def initialize(name, requirement)
@name = name @name = name
@requirement = requirement @requirement = requirement
end end
@ -50,7 +50,7 @@ module Gem
class MissingSpecVersionError < MissingSpecError class MissingSpecVersionError < MissingSpecError
attr_reader :specs attr_reader :specs
def initialize name, requirement, specs def initialize(name, requirement, specs)
super(name, requirement) super(name, requirement)
@specs = specs @specs = specs
end end
@ -81,7 +81,7 @@ module Gem
attr_reader :target attr_reader :target
def initialize target, conflicts def initialize(target, conflicts)
@target = target @target = target
@conflicts = conflicts @conflicts = conflicts
@name = target.name @name = target.name

Просмотреть файл

@ -36,7 +36,7 @@ class Gem::DependencyResolutionError < Gem::DependencyError
attr_reader :conflict attr_reader :conflict
def initialize conflict def initialize(conflict)
@conflict = conflict @conflict = conflict
a, b = conflicting_dependencies a, b = conflicting_dependencies
@ -77,7 +77,7 @@ class Gem::FilePermissionError < Gem::Exception
attr_reader :directory attr_reader :directory
def initialize directory def initialize(directory)
@directory = directory @directory = directory
super "You don't have write permissions for the #{directory} directory." super "You don't have write permissions for the #{directory} directory."
@ -137,7 +137,7 @@ class Gem::ImpossibleDependenciesError < Gem::Exception
attr_reader :conflicts attr_reader :conflicts
attr_reader :request attr_reader :request
def initialize request, conflicts def initialize(request, conflicts)
@request = request @request = request
@conflicts = conflicts @conflicts = conflicts
@ -249,7 +249,7 @@ class Gem::UnsatisfiableDependencyError < Gem::DependencyError
# Creates a new UnsatisfiableDependencyError for the unsatisfiable # Creates a new UnsatisfiableDependencyError for the unsatisfiable
# Gem::Resolver::DependencyRequest +dep+ # Gem::Resolver::DependencyRequest +dep+
def initialize dep, platform_mismatch=nil def initialize(dep, platform_mismatch=nil)
if platform_mismatch and !platform_mismatch.empty? if platform_mismatch and !platform_mismatch.empty?
plats = platform_mismatch.map { |x| x.platform.to_s }.sort.uniq plats = platform_mismatch.map { |x| x.platform.to_s }.sort.uniq
super "Unable to resolve dependency: No match for '#{dep}' on this platform. Found: #{plats.join(', ')}" super "Unable to resolve dependency: No match for '#{dep}' on this platform. Found: #{plats.join(', ')}"

Просмотреть файл

@ -16,4 +16,3 @@ require 'rubygems/ext/configure_builder'
require 'rubygems/ext/ext_conf_builder' require 'rubygems/ext/ext_conf_builder'
require 'rubygems/ext/rake_builder' require 'rubygems/ext/rake_builder'
require 'rubygems/ext/cmake_builder' require 'rubygems/ext/cmake_builder'

Просмотреть файл

@ -4,4 +4,3 @@
class Gem::Ext::BuildError < Gem::InstallError class Gem::Ext::BuildError < Gem::InstallError
end end

Просмотреть файл

@ -27,14 +27,14 @@ class Gem::Ext::Builder
end end
def self.make(dest_path, results) def self.make(dest_path, results)
unless File.exist? 'Makefile' then unless File.exist? 'Makefile'
raise Gem::InstallError, 'Makefile not found' raise Gem::InstallError, 'Makefile not found'
end end
# try to find make program from Ruby configure arguments first # try to find make program from Ruby configure arguments first
RbConfig::CONFIG['configure_args'] =~ /with-make-prog\=(\w+)/ RbConfig::CONFIG['configure_args'] =~ /with-make-prog\=(\w+)/
make_program = ENV['MAKE'] || ENV['make'] || $1 make_program = ENV['MAKE'] || ENV['make'] || $1
unless make_program then unless make_program
make_program = (/mswin/ =~ RUBY_PLATFORM) ? 'nmake' : 'make' make_program = (/mswin/ =~ RUBY_PLATFORM) ? 'nmake' : 'make'
end end
@ -86,13 +86,13 @@ class Gem::Ext::Builder
ENV['RUBYGEMS_GEMDEPS'] = rubygems_gemdeps ENV['RUBYGEMS_GEMDEPS'] = rubygems_gemdeps
end end
unless $?.success? then unless $?.success?
results << "Building has failed. See above output for more information on the failure." if verbose results << "Building has failed. See above output for more information on the failure." if verbose
exit_reason = exit_reason =
if $?.exited? then if $?.exited?
", exit code #{$?.exitstatus}" ", exit code #{$?.exitstatus}"
elsif $?.signaled? then elsif $?.signaled?
", uncaught signal #{$?.termsig}" ", uncaught signal #{$?.termsig}"
end end
@ -105,7 +105,7 @@ class Gem::Ext::Builder
# have build arguments, saved, set +build_args+ which is an ARGV-style # have build arguments, saved, set +build_args+ which is an ARGV-style
# array. # array.
def initialize spec, build_args = spec.build_args def initialize(spec, build_args = spec.build_args)
@spec = spec @spec = spec
@build_args = build_args @build_args = build_args
@gem_dir = spec.full_gem_path @gem_dir = spec.full_gem_path
@ -116,7 +116,7 @@ class Gem::Ext::Builder
## ##
# Chooses the extension builder class for +extension+ # Chooses the extension builder class for +extension+
def builder_for extension # :nodoc: def builder_for(extension) # :nodoc:
case extension case extension
when /extconf/ then when /extconf/ then
Gem::Ext::ExtConfBuilder Gem::Ext::ExtConfBuilder
@ -138,7 +138,7 @@ class Gem::Ext::Builder
## ##
# Logs the build +output+ in +build_dir+, then raises Gem::Ext::BuildError. # Logs the build +output+ in +build_dir+, then raises Gem::Ext::BuildError.
def build_error build_dir, output, backtrace = nil # :nodoc: def build_error(build_dir, output, backtrace = nil) # :nodoc:
gem_make_out = write_gem_make_out output gem_make_out = write_gem_make_out output
message = <<-EOF message = <<-EOF
@ -153,7 +153,7 @@ EOF
raise Gem::Ext::BuildError, message, backtrace raise Gem::Ext::BuildError, message, backtrace
end end
def build_extension extension, dest_path # :nodoc: def build_extension(extension, dest_path) # :nodoc:
results = [] results = []
# FIXME: Determine if this line is necessary and, if so, why. # FIXME: Determine if this line is necessary and, if so, why.
@ -235,7 +235,7 @@ EOF
## ##
# Writes +output+ to gem_make.out in the extension install directory. # Writes +output+ to gem_make.out in the extension install directory.
def write_gem_make_out output # :nodoc: def write_gem_make_out(output) # :nodoc:
destination = File.join @spec.extension_dir, 'gem_make.out' destination = File.join @spec.extension_dir, 'gem_make.out'
FileUtils.mkdir_p @spec.extension_dir FileUtils.mkdir_p @spec.extension_dir

Просмотреть файл

@ -3,7 +3,7 @@ require 'rubygems/command'
class Gem::Ext::CmakeBuilder < Gem::Ext::Builder class Gem::Ext::CmakeBuilder < Gem::Ext::Builder
def self.build(extension, dest_path, results, args=[], lib_dir=nil) def self.build(extension, dest_path, results, args=[], lib_dir=nil)
unless File.exist?('Makefile') then unless File.exist?('Makefile')
cmd = "cmake . -DCMAKE_INSTALL_PREFIX=#{dest_path}" cmd = "cmake . -DCMAKE_INSTALL_PREFIX=#{dest_path}"
cmd << " #{Gem::Command.build_args.join ' '}" unless Gem::Command.build_args.empty? cmd << " #{Gem::Command.build_args.join ' '}" unless Gem::Command.build_args.empty?

Просмотреть файл

@ -8,7 +8,7 @@
class Gem::Ext::ConfigureBuilder < Gem::Ext::Builder class Gem::Ext::ConfigureBuilder < Gem::Ext::Builder
def self.build(extension, dest_path, results, args=[], lib_dir=nil) def self.build(extension, dest_path, results, args=[], lib_dir=nil)
unless File.exist?('Makefile') then unless File.exist?('Makefile')
cmd = "sh ./configure --prefix=#{dest_path}" cmd = "sh ./configure --prefix=#{dest_path}"
cmd << " #{args.join ' '}" unless args.empty? cmd << " #{args.join ' '}" unless args.empty?

Просмотреть файл

@ -47,7 +47,7 @@ class Gem::Ext::ExtConfBuilder < Gem::Ext::Builder
run cmd, results run cmd, results
ensure ensure
if File.exist? 'mkmf.log' if File.exist? 'mkmf.log'
unless $?.success? then unless $?.success?
results << "To see why this extension failed to compile, please check" \ results << "To see why this extension failed to compile, please check" \
" the mkmf.log which can be found here:\n" " the mkmf.log which can be found here:\n"
results << " " + File.join(dest_path, 'mkmf.log') + "\n" results << " " + File.join(dest_path, 'mkmf.log') + "\n"
@ -63,7 +63,7 @@ class Gem::Ext::ExtConfBuilder < Gem::Ext::Builder
if tmp_dest if tmp_dest
# TODO remove in RubyGems 3 # TODO remove in RubyGems 3
if Gem.install_extension_in_lib and lib_dir then if Gem.install_extension_in_lib and lib_dir
FileUtils.mkdir_p lib_dir FileUtils.mkdir_p lib_dir
entries = Dir.entries(tmp_dest) - %w[. ..] entries = Dir.entries(tmp_dest) - %w[. ..]
entries = entries.map { |entry| File.join tmp_dest, entry } entries = entries.map { |entry| File.join tmp_dest, entry }

Просмотреть файл

@ -10,7 +10,7 @@ require "shellwords"
class Gem::Ext::RakeBuilder < Gem::Ext::Builder class Gem::Ext::RakeBuilder < Gem::Ext::Builder
def self.build(extension, dest_path, results, args=[], lib_dir=nil) def self.build(extension, dest_path, results, args=[], lib_dir=nil)
if File.basename(extension) =~ /mkrf_conf/i then if File.basename(extension) =~ /mkrf_conf/i
run([Gem.ruby, File.basename(extension), *args], results) run([Gem.ruby, File.basename(extension), *args], results)
end end

Просмотреть файл

@ -38,7 +38,7 @@ class Gem::GemRunner
## ##
# Run the gem command with the following arguments. # Run the gem command with the following arguments.
def run args def run(args)
build_args = extract_build_args args build_args = extract_build_args args
do_configuration args do_configuration args
@ -63,7 +63,7 @@ class Gem::GemRunner
# Separates the build arguments (those following <code>--</code>) from the # Separates the build arguments (those following <code>--</code>) from the
# other arguments in the list. # other arguments in the list.
def extract_build_args args # :nodoc: def extract_build_args(args) # :nodoc:
return [] unless offset = args.index('--') return [] unless offset = args.index('--')
build_args = args.slice!(offset...args.length) build_args = args.slice!(offset...args.length)

Просмотреть файл

@ -28,7 +28,7 @@ module Gem::GemcutterUtilities
# The API key from the command options or from the user's configuration. # The API key from the command options or from the user's configuration.
def api_key def api_key
if options[:key] then if options[:key]
verify_api_key options[:key] verify_api_key options[:key]
elsif Gem.configuration.api_keys.key?(host) elsif Gem.configuration.api_keys.key?(host)
Gem.configuration.api_keys[host] Gem.configuration.api_keys[host]
@ -90,11 +90,11 @@ module Gem::GemcutterUtilities
# Signs in with the RubyGems API at +sign_in_host+ and sets the rubygems API # Signs in with the RubyGems API at +sign_in_host+ and sets the rubygems API
# key. # key.
def sign_in sign_in_host = nil def sign_in(sign_in_host = nil)
sign_in_host ||= self.host sign_in_host ||= self.host
return if api_key return if api_key
pretty_host = if Gem::DEFAULT_HOST == sign_in_host then pretty_host = if Gem::DEFAULT_HOST == sign_in_host
'RubyGems.org' 'RubyGems.org'
else else
sign_in_host sign_in_host
@ -124,7 +124,7 @@ module Gem::GemcutterUtilities
# an error. # an error.
def verify_api_key(key) def verify_api_key(key)
if Gem.configuration.api_keys.key? key then if Gem.configuration.api_keys.key? key
Gem.configuration.api_keys[key] Gem.configuration.api_keys[key]
else else
alert_error "No such API key. Please add it to your configuration (done automatically on initial `gem push`)." alert_error "No such API key. Please add it to your configuration (done automatically on initial `gem push`)."
@ -139,10 +139,10 @@ module Gem::GemcutterUtilities
# If the response was not successful, shows an error to the user including # If the response was not successful, shows an error to the user including
# the +error_prefix+ and the response body. # the +error_prefix+ and the response body.
def with_response response, error_prefix = nil def with_response(response, error_prefix = nil)
case response case response
when Net::HTTPSuccess then when Net::HTTPSuccess then
if block_given? then if block_given?
yield response yield response
else else
say response.body say response.body
@ -156,7 +156,7 @@ module Gem::GemcutterUtilities
end end
end end
def set_api_key host, key def set_api_key(host, key)
if host == Gem::DEFAULT_HOST if host == Gem::DEFAULT_HOST
Gem.configuration.rubygems_api_key = key Gem.configuration.rubygems_api_key = key
else else
@ -165,4 +165,3 @@ module Gem::GemcutterUtilities
end end
end end

Просмотреть файл

@ -4,17 +4,10 @@ require 'rubygems/package'
require 'time' require 'time'
require 'tmpdir' require 'tmpdir'
rescue_exceptions = [LoadError]
begin
require 'bundler/errors'
rescue LoadError # this rubygems + old ruby
else # this rubygems + ruby trunk with bundler
rescue_exceptions << Bundler::GemfileNotFound
end
begin begin
gem 'builder' gem 'builder'
require 'builder/xchar' require 'builder/xchar'
rescue *rescue_exceptions rescue LoadError
end end
## ##
@ -62,7 +55,7 @@ class Gem::Indexer
require 'tmpdir' require 'tmpdir'
require 'zlib' require 'zlib'
unless defined?(Builder::XChar) then unless defined?(Builder::XChar)
raise "Gem::Indexer requires that the XML Builder library be installed:" + raise "Gem::Indexer requires that the XML Builder library be installed:" +
"\n\tgem install builder" "\n\tgem install builder"
end end
@ -116,7 +109,7 @@ class Gem::Indexer
## ##
# Builds Marshal quick index gemspecs. # Builds Marshal quick index gemspecs.
def build_marshal_gemspecs specs def build_marshal_gemspecs(specs)
count = specs.count count = specs.count
progress = ui.progress_reporter count, progress = ui.progress_reporter count,
"Generating Marshal quick index gemspecs for #{count} gems", "Generating Marshal quick index gemspecs for #{count} gems",
@ -161,7 +154,7 @@ class Gem::Indexer
platform = spec.original_platform platform = spec.original_platform
# win32-api-1.0.4-x86-mswin32-60 # win32-api-1.0.4-x86-mswin32-60
unless String === platform then unless String === platform
alert_warning "Skipping invalid platform in gem: #{spec.full_name}" alert_warning "Skipping invalid platform in gem: #{spec.full_name}"
next next
end end
@ -179,7 +172,7 @@ class Gem::Indexer
## ##
# Builds indices for RubyGems 1.2 and newer. Handles full, latest, prerelease # Builds indices for RubyGems 1.2 and newer. Handles full, latest, prerelease
def build_modern_indices specs def build_modern_indices(specs)
prerelease, released = specs.partition { |s| prerelease, released = specs.partition { |s|
s.version.prerelease? s.version.prerelease?
} }
@ -199,9 +192,9 @@ class Gem::Indexer
"#{@prerelease_specs_index}.gz"] "#{@prerelease_specs_index}.gz"]
end end
def map_gems_to_specs gems def map_gems_to_specs(gems)
gems.map { |gemfile| gems.map { |gemfile|
if File.size(gemfile) == 0 then if File.size(gemfile) == 0
alert_warning "Skipping zero-length gem: #{gemfile}" alert_warning "Skipping zero-length gem: #{gemfile}"
next next
end end
@ -235,7 +228,7 @@ class Gem::Indexer
say "Compressing indices" say "Compressing indices"
Gem.time 'Compressed indices' do Gem.time 'Compressed indices' do
if @build_modern then if @build_modern
gzip @specs_index gzip @specs_index
gzip @latest_specs_index gzip @latest_specs_index
gzip @prerelease_specs_index gzip @prerelease_specs_index
@ -313,7 +306,7 @@ class Gem::Indexer
files = @files files = @files
files.delete @quick_marshal_dir if files.include? @quick_dir files.delete @quick_marshal_dir if files.include? @quick_dir
if files.include? @quick_marshal_dir and not files.include? @quick_dir then if files.include? @quick_marshal_dir and not files.include? @quick_dir
files.delete @quick_marshal_dir files.delete @quick_marshal_dir
dst_name = File.join(@dest_directory, @quick_marshal_dir_base) dst_name = File.join(@dest_directory, @quick_marshal_dir_base)
@ -354,7 +347,7 @@ class Gem::Indexer
data = Gem.read_binary path data = Gem.read_binary path
compressed_data = Gem.read_binary "#{path}.#{extension}" compressed_data = Gem.read_binary "#{path}.#{extension}"
unless data == Gem::Util.inflate(compressed_data) then unless data == Gem::Util.inflate(compressed_data)
raise "Compressed file #{compressed_path} does not match uncompressed file #{path}" raise "Compressed file #{compressed_path} does not match uncompressed file #{path}"
end end
end end
@ -374,7 +367,7 @@ class Gem::Indexer
gem_mtime >= specs_mtime gem_mtime >= specs_mtime
end end
if updated_gems.empty? then if updated_gems.empty?
say 'No new gems' say 'No new gems'
terminate_interaction 0 terminate_interaction 0
end end

Просмотреть файл

@ -10,4 +10,3 @@ Gem.post_install do |installer|
ui = Gem::DefaultUserInteraction.ui ui = Gem::DefaultUserInteraction.ui
ui.say "Successfully installed #{installer.spec.full_name} as a default gem" ui.say "Successfully installed #{installer.spec.full_name} as a default gem"
end end

Просмотреть файл

@ -10,4 +10,3 @@ Gem.post_install do |installer|
ui = Gem::DefaultUserInteraction.ui ui = Gem::DefaultUserInteraction.ui
ui.say "Successfully installed #{installer.spec.full_name}" ui.say "Successfully installed #{installer.spec.full_name}"
end end

Просмотреть файл

@ -50,7 +50,7 @@ module Gem::InstallUpdateOptions
add_option(:"Install/Update", '--vendor', add_option(:"Install/Update", '--vendor',
'Install gem into the vendor directory.', 'Install gem into the vendor directory.',
'Only for use by gem repackagers.') do |value, options| 'Only for use by gem repackagers.') do |value, options|
unless Gem.vendor_dir then unless Gem.vendor_dir
raise OptionParser::InvalidOption.new 'your platform is not supported' raise OptionParser::InvalidOption.new 'your platform is not supported'
end end
@ -140,7 +140,7 @@ module Gem::InstallUpdateOptions
File.exist? file File.exist? file
end unless v end unless v
unless v then unless v
message = v ? v : "(tried #{Gem::GEM_DEP_FILES.join ', '})" message = v ? v : "(tried #{Gem::GEM_DEP_FILES.join ', '})"
raise OptionParser::InvalidArgument, raise OptionParser::InvalidArgument,
@ -178,7 +178,6 @@ module Gem::InstallUpdateOptions
'Suggest alternates when gems are not found') do |v,o| 'Suggest alternates when gems are not found') do |v,o|
options[:suggest_alternate] = v options[:suggest_alternate] = v
end end
end end
## ##
@ -189,4 +188,3 @@ module Gem::InstallUpdateOptions
end end
end end

Просмотреть файл

@ -101,7 +101,7 @@ class Gem::Installer
## ##
# Construct an installer object for the gem file located at +path+ # Construct an installer object for the gem file located at +path+
def self.at path, options = {} def self.at(path, options = {})
security_policy = options[:security_policy] security_policy = options[:security_policy]
package = Gem::Package.new path, security_policy package = Gem::Package.new path, security_policy
new package, options new package, options
@ -118,7 +118,7 @@ class Gem::Installer
@spec = spec @spec = spec
end end
def extract_files destination_dir, pattern = '*' def extract_files(destination_dir, pattern = '*')
FileUtils.mkdir_p destination_dir FileUtils.mkdir_p destination_dir
spec.files.each do |file| spec.files.each do |file|
@ -129,7 +129,7 @@ class Gem::Installer
end end
end end
def copy_to path def copy_to(path)
end end
end end
@ -137,7 +137,7 @@ class Gem::Installer
# Construct an installer object for an ephemeral gem (one where we don't # Construct an installer object for an ephemeral gem (one where we don't
# actually have a .gem file, just a spec) # actually have a .gem file, just a spec)
def self.for_spec spec, options = {} def self.for_spec(spec, options = {})
# FIXME: we should have a real Package class for this # FIXME: we should have a real Package class for this
new FakePackage.new(spec), options new FakePackage.new(spec), options
end end
@ -189,7 +189,7 @@ class Gem::Installer
@bin_dir = options[:bin_dir] if options[:bin_dir] @bin_dir = options[:bin_dir] if options[:bin_dir]
if options[:user_install] and not options[:unpack] then if options[:user_install] and not options[:unpack]
@gem_home = Gem.user_dir @gem_home = Gem.user_dir
@bin_dir = Gem.bindir gem_home unless options[:bin_dir] @bin_dir = Gem.bindir gem_home unless options[:bin_dir]
check_that_user_bin_dir_is_in_path check_that_user_bin_dir_is_in_path
@ -209,7 +209,7 @@ class Gem::Installer
# #
# Otherwise +filename+ is overwritten. # Otherwise +filename+ is overwritten.
def check_executable_overwrite filename # :nodoc: def check_executable_overwrite(filename) # :nodoc:
return if @force return if @force
generated_bin = File.join @bin_dir, formatted_program_filename(filename) generated_bin = File.join @bin_dir, formatted_program_filename(filename)
@ -245,7 +245,7 @@ class Gem::Installer
question = "#{spec.name}'s executable \"#{filename}\" conflicts with ".dup question = "#{spec.name}'s executable \"#{filename}\" conflicts with ".dup
if ruby_executable then if ruby_executable
question << (existing || 'an unknown executable') question << (existing || 'an unknown executable')
return if ask_yes_no "#{question}\nOverwrite the executable?", false return if ask_yes_no "#{question}\nOverwrite the executable?", false
@ -298,7 +298,7 @@ class Gem::Installer
run_pre_install_hooks run_pre_install_hooks
# Set loaded_from to ensure extension_dir is correct # Set loaded_from to ensure extension_dir is correct
if @options[:install_as_default] then if @options[:install_as_default]
spec.loaded_from = default_spec_file spec.loaded_from = default_spec_file
else else
spec.loaded_from = spec_file spec.loaded_from = spec_file
@ -311,7 +311,7 @@ class Gem::Installer
dir_mode = options[:dir_mode] dir_mode = options[:dir_mode]
FileUtils.mkdir_p gem_dir, :mode => dir_mode && 0700 FileUtils.mkdir_p gem_dir, :mode => dir_mode && 0700
if @options[:install_as_default] then if @options[:install_as_default]
extract_bin extract_bin
write_default_spec write_default_spec
else else
@ -344,7 +344,7 @@ class Gem::Installer
def run_pre_install_hooks # :nodoc: def run_pre_install_hooks # :nodoc:
Gem.pre_install_hooks.each do |hook| Gem.pre_install_hooks.each do |hook|
if hook.call(self) == false then if hook.call(self) == false
location = " at #{$1}" if hook.inspect =~ /@(.*:\d+)/ location = " at #{$1}" if hook.inspect =~ /@(.*:\d+)/
message = "pre-install hook#{location} failed for #{spec.full_name}" message = "pre-install hook#{location} failed for #{spec.full_name}"
@ -355,7 +355,7 @@ class Gem::Installer
def run_post_build_hooks # :nodoc: def run_post_build_hooks # :nodoc:
Gem.post_build_hooks.each do |hook| Gem.post_build_hooks.each do |hook|
if hook.call(self) == false then if hook.call(self) == false
FileUtils.rm_rf gem_dir FileUtils.rm_rf gem_dir
location = " at #{$1}" if hook.inspect =~ /@(.*:\d+)/ location = " at #{$1}" if hook.inspect =~ /@(.*:\d+)/
@ -398,7 +398,7 @@ class Gem::Installer
# dependency :: Gem::Dependency # dependency :: Gem::Dependency
def ensure_dependency(spec, dependency) def ensure_dependency(spec, dependency)
unless installation_satisfies_dependency? dependency then unless installation_satisfies_dependency? dependency
raise Gem::InstallError, "#{spec.name} requires #{dependency}" raise Gem::InstallError, "#{spec.name} requires #{dependency}"
end end
true true
@ -466,7 +466,7 @@ class Gem::Installer
# Creates windows .bat files for easy running of commands # Creates windows .bat files for easy running of commands
def generate_windows_script(filename, bindir) def generate_windows_script(filename, bindir)
if Gem.win_platform? then if Gem.win_platform?
script_name = filename + ".bat" script_name = filename + ".bat"
script_path = File.join bindir, File.basename(script_name) script_path = File.join bindir, File.basename(script_name)
File.open script_path, 'w' do |file| File.open script_path, 'w' do |file|
@ -492,7 +492,7 @@ class Gem::Installer
filename.untaint filename.untaint
bin_path = File.join gem_dir, spec.bindir, filename bin_path = File.join gem_dir, spec.bindir, filename
unless File.exist? bin_path then unless File.exist? bin_path
# TODO change this to a more useful warning # TODO change this to a more useful warning
warn "`#{bin_path}` does not exist, maybe `gem pristine #{spec.name}` will fix it?" warn "`#{bin_path}` does not exist, maybe `gem pristine #{spec.name}` will fix it?"
next next
@ -504,7 +504,7 @@ class Gem::Installer
check_executable_overwrite filename check_executable_overwrite filename
if @wrappers then if @wrappers
generate_bin_script filename, @bin_dir generate_bin_script filename, @bin_dir
else else
generate_bin_symlink filename, @bin_dir generate_bin_symlink filename, @bin_dir
@ -543,8 +543,8 @@ class Gem::Installer
src = File.join gem_dir, spec.bindir, filename src = File.join gem_dir, spec.bindir, filename
dst = File.join bindir, formatted_program_filename(filename) dst = File.join bindir, formatted_program_filename(filename)
if File.exist? dst then if File.exist? dst
if File.symlink? dst then if File.symlink? dst
link = File.readlink(dst).split File::SEPARATOR link = File.readlink(dst).split File::SEPARATOR
cur_version = Gem::Version.create(link[-3].sub(/^.*-/, '')) cur_version = Gem::Version.create(link[-3].sub(/^.*-/, ''))
return if spec.version < cur_version return if spec.version < cur_version
@ -578,7 +578,7 @@ class Gem::Installer
path = File.join gem_dir, spec.bindir, bin_file_name path = File.join gem_dir, spec.bindir, bin_file_name
first_line = File.open(path, "rb") {|file| file.gets} first_line = File.open(path, "rb") {|file| file.gets}
if /\A#!/ =~ first_line then if /\A#!/ =~ first_line
# Preserve extra words on shebang line, like "-w". Thanks RPA. # Preserve extra words on shebang line, like "-w". Thanks RPA.
shebang = first_line.sub(/\A\#!.*?ruby\S*((\s+\S+)+)/, "#!#{Gem.ruby}") shebang = first_line.sub(/\A\#!.*?ruby\S*((\s+\S+)+)/, "#!#{Gem.ruby}")
opts = $1 opts = $1
@ -603,9 +603,9 @@ class Gem::Installer
end end
"#!#{which}" "#!#{which}"
elsif not ruby_name then elsif not ruby_name
"#!#{Gem.ruby}#{opts}" "#!#{Gem.ruby}#{opts}"
elsif opts then elsif opts
"#!/bin/sh\n'exec' #{ruby_name.dump} '-x' \"$0\" \"$@\"\n#{shebang}" "#!/bin/sh\n'exec' #{ruby_name.dump} '-x' \"$0\" \"$@\"\n#{shebang}"
else else
# Create a plain shebang line. # Create a plain shebang line.
@ -631,9 +631,9 @@ class Gem::Installer
end end
def ensure_required_ruby_version_met # :nodoc: def ensure_required_ruby_version_met # :nodoc:
if rrv = spec.required_ruby_version then if rrv = spec.required_ruby_version
unless rrv.satisfied_by? Gem.ruby_version then ruby_version = Gem.ruby_version
ruby_version = Gem.ruby_api_version unless rrv.satisfied_by? ruby_version
raise Gem::RuntimeRequirementNotMetError, raise Gem::RuntimeRequirementNotMetError,
"#{spec.name} requires Ruby version #{rrv}. The current ruby version is #{ruby_version}." "#{spec.name} requires Ruby version #{rrv}. The current ruby version is #{ruby_version}."
end end
@ -641,8 +641,8 @@ class Gem::Installer
end end
def ensure_required_rubygems_version_met # :nodoc: def ensure_required_rubygems_version_met # :nodoc:
if rrgv = spec.required_rubygems_version then if rrgv = spec.required_rubygems_version
unless rrgv.satisfied_by? Gem.rubygems_version then unless rrgv.satisfied_by? Gem.rubygems_version
rg_version = Gem::VERSION rg_version = Gem::VERSION
raise Gem::RuntimeRequirementNotMetError, raise Gem::RuntimeRequirementNotMetError,
"#{spec.name} requires RubyGems version #{rrgv}. The current RubyGems version is #{rg_version}. " + "#{spec.name} requires RubyGems version #{rrgv}. The current RubyGems version is #{rg_version}. " +
@ -702,16 +702,16 @@ class Gem::Installer
File::ALT_SEPARATOR File::ALT_SEPARATOR
path = ENV['PATH'] path = ENV['PATH']
if Gem.win_platform? then if Gem.win_platform?
path = path.downcase path = path.downcase
user_bin_dir = user_bin_dir.downcase user_bin_dir = user_bin_dir.downcase
end end
path = path.split(File::PATH_SEPARATOR) path = path.split(File::PATH_SEPARATOR)
unless path.include? user_bin_dir then unless path.include? user_bin_dir
unless !Gem.win_platform? && (path.include? user_bin_dir.sub(ENV['HOME'], '~')) unless !Gem.win_platform? && (path.include? user_bin_dir.sub(ENV['HOME'], '~'))
unless self.class.path_warning then unless self.class.path_warning
alert_warning "You don't have #{user_bin_dir} in your PATH,\n\t gem executables will not run." alert_warning "You don't have #{user_bin_dir} in your PATH,\n\t gem executables will not run."
self.class.path_warning = true self.class.path_warning = true
end end
@ -752,7 +752,7 @@ version = "#{Gem::Requirement.default}.a"
if ARGV.first if ARGV.first
str = ARGV.first str = ARGV.first
str = str.dup.force_encoding("BINARY") str = str.dup.force_encoding("BINARY")
if str =~ /\\A_(.*)_\\z/ and Gem::Version.correct?($1) then if str =~ /\\A_(.*)_\\z/ and Gem::Version.correct?($1)
version = $1 version = $1
ARGV.shift ARGV.shift
end end
@ -847,7 +847,7 @@ TEXT
# Prefix and suffix the program filename the same as ruby. # Prefix and suffix the program filename the same as ruby.
def formatted_program_filename(filename) def formatted_program_filename(filename)
if @format_executable then if @format_executable
self.class.exec_format % File.basename(filename) self.class.exec_format % File.basename(filename)
else else
filename filename

Просмотреть файл

@ -183,4 +183,3 @@ class Gem::InstallerTestCase < Gem::TestCase
end end
end end

Просмотреть файл

@ -108,7 +108,7 @@ module Gem::LocalRemoteOptions
source << '/' if source !~ /\/\z/ source << '/' if source !~ /\/\z/
if options.delete :sources_cleared then if options.delete :sources_cleared
Gem.sources = [source] Gem.sources = [source]
else else
Gem.sources << source unless Gem.sources.include?(source) Gem.sources << source unless Gem.sources.include?(source)
@ -148,4 +148,3 @@ module Gem::LocalRemoteOptions
end end
end end

Просмотреть файл

@ -12,7 +12,7 @@ class Gem::MockGemUi < Gem::StreamUI
class InputEOFError < RuntimeError class InputEOFError < RuntimeError
def initialize question def initialize(question)
super "Out of input for MockGemUi on #{question.inspect}" super "Out of input for MockGemUi on #{question.inspect}"
end end
@ -21,7 +21,7 @@ class Gem::MockGemUi < Gem::StreamUI
class TermError < RuntimeError class TermError < RuntimeError
attr_reader :exit_code attr_reader :exit_code
def initialize exit_code def initialize(exit_code)
super super
@exit_code = exit_code @exit_code = exit_code
end end
@ -56,7 +56,7 @@ class Gem::MockGemUi < Gem::StreamUI
@terminated = false @terminated = false
end end
def ask question def ask(question)
raise InputEOFError, question if @ins.eof? raise InputEOFError, question if @ins.eof?
super super
@ -86,4 +86,3 @@ class Gem::MockGemUi < Gem::StreamUI
end end
end end

Просмотреть файл

@ -24,7 +24,7 @@ class Gem::NameTuple
# Turn an array of [name, version, platform] into an array of # Turn an array of [name, version, platform] into an array of
# NameTuple objects. # NameTuple objects.
def self.from_list list def self.from_list(list)
list.map { |t| new(*t) } list.map { |t| new(*t) }
end end
@ -32,7 +32,7 @@ class Gem::NameTuple
# Turn an array of NameTuple objects back into an array of # Turn an array of NameTuple objects back into an array of
# [name, version, platform] tuples. # [name, version, platform] tuples.
def self.to_basic list def self.to_basic(list)
list.map { |t| t.to_a } list.map { |t| t.to_a }
end end
@ -90,7 +90,7 @@ class Gem::NameTuple
alias to_s inspect # :nodoc: alias to_s inspect # :nodoc:
def <=> other def <=>(other)
[@name, @version, @platform == Gem::Platform::RUBY ? -1 : 1] <=> [@name, @version, @platform == Gem::Platform::RUBY ? -1 : 1] <=>
[other.name, other.version, [other.name, other.version,
other.platform == Gem::Platform::RUBY ? -1 : 1] other.platform == Gem::Platform::RUBY ? -1 : 1]
@ -102,7 +102,7 @@ class Gem::NameTuple
# Compare with +other+. Supports another NameTuple or an Array # Compare with +other+. Supports another NameTuple or an Array
# in the [name, version, platform] format. # in the [name, version, platform] format.
def == other def ==(other)
case other case other
when self.class when self.class
@name == other.name and @name == other.name and

Просмотреть файл

@ -55,7 +55,7 @@ class Gem::Package
class FormatError < Error class FormatError < Error
attr_reader :path attr_reader :path
def initialize message, source = nil def initialize(message, source = nil)
if source if source
@path = source.path @path = source.path
@ -68,7 +68,7 @@ class Gem::Package
end end
class PathError < Error class PathError < Error
def initialize destination, destination_dir def initialize(destination, destination_dir)
super "installing into parent path %s of %s is not allowed" % super "installing into parent path %s of %s is not allowed" %
[destination, destination_dir] [destination, destination_dir]
end end
@ -119,7 +119,7 @@ class Gem::Package
# Permission for other files # Permission for other files
attr_accessor :data_mode attr_accessor :data_mode
def self.build spec, skip_validation = false, strict_validation = false def self.build(spec, skip_validation = false, strict_validation = false)
gem_file = spec.file_name gem_file = spec.file_name
package = new gem_file package = new gem_file
@ -136,7 +136,7 @@ class Gem::Package
# If +gem+ is an existing file in the old format a Gem::Package::Old will be # If +gem+ is an existing file in the old format a Gem::Package::Old will be
# returned. # returned.
def self.new gem, security_policy = nil def self.new(gem, security_policy = nil)
gem = if gem.is_a?(Gem::Package::Source) gem = if gem.is_a?(Gem::Package::Source)
gem gem
elsif gem.respond_to? :read elsif gem.respond_to? :read
@ -157,7 +157,7 @@ class Gem::Package
## ##
# Creates a new package that will read or write to the file +gem+. # Creates a new package that will read or write to the file +gem+.
def initialize gem, security_policy # :notnew: def initialize(gem, security_policy) # :notnew:
@gem = gem @gem = gem
@build_time = ENV["SOURCE_DATE_EPOCH"] ? Time.at(ENV["SOURCE_DATE_EPOCH"].to_i).utc : Time.now @build_time = ENV["SOURCE_DATE_EPOCH"] ? Time.at(ENV["SOURCE_DATE_EPOCH"].to_i).utc : Time.now
@ -174,14 +174,14 @@ class Gem::Package
## ##
# Copies this package to +path+ (if possible) # Copies this package to +path+ (if possible)
def copy_to path def copy_to(path)
FileUtils.cp @gem.path, path unless File.exist? path FileUtils.cp @gem.path, path unless File.exist? path
end end
## ##
# Adds a checksum for each entry in the gem to checksums.yaml.gz. # Adds a checksum for each entry in the gem to checksums.yaml.gz.
def add_checksums tar def add_checksums(tar)
Gem.load_yaml Gem.load_yaml
checksums_by_algorithm = Hash.new { |h, algorithm| h[algorithm] = {} } checksums_by_algorithm = Hash.new { |h, algorithm| h[algorithm] = {} }
@ -203,7 +203,7 @@ class Gem::Package
# Adds the files listed in the packages's Gem::Specification to data.tar.gz # Adds the files listed in the packages's Gem::Specification to data.tar.gz
# and adds this file to the +tar+. # and adds this file to the +tar+.
def add_contents tar # :nodoc: def add_contents(tar) # :nodoc:
digests = tar.add_file_signed 'data.tar.gz', 0444, @signer do |io| digests = tar.add_file_signed 'data.tar.gz', 0444, @signer do |io|
gzip_to io do |gz_io| gzip_to io do |gz_io|
Gem::Package::TarWriter.new gz_io do |data_tar| Gem::Package::TarWriter.new gz_io do |data_tar|
@ -218,7 +218,7 @@ class Gem::Package
## ##
# Adds files included the package's Gem::Specification to the +tar+ file # Adds files included the package's Gem::Specification to the +tar+ file
def add_files tar # :nodoc: def add_files(tar) # :nodoc:
@spec.files.each do |file| @spec.files.each do |file|
stat = File.lstat file stat = File.lstat file
@ -241,7 +241,7 @@ class Gem::Package
## ##
# Adds the package's Gem::Specification to the +tar+ file # Adds the package's Gem::Specification to the +tar+ file
def add_metadata tar # :nodoc: def add_metadata(tar) # :nodoc:
digests = tar.add_file_signed 'metadata.gz', 0444, @signer do |io| digests = tar.add_file_signed 'metadata.gz', 0444, @signer do |io|
gzip_to io do |gz_io| gzip_to io do |gz_io|
gz_io.write @spec.to_yaml gz_io.write @spec.to_yaml
@ -254,7 +254,7 @@ class Gem::Package
## ##
# Builds this package based on the specification set by #spec= # Builds this package based on the specification set by #spec=
def build skip_validation = false, strict_validation = false def build(skip_validation = false, strict_validation = false)
raise ArgumentError, "skip_validation = true and strict_validation = true are incompatible" if skip_validation && strict_validation raise ArgumentError, "skip_validation = true and strict_validation = true are incompatible" if skip_validation && strict_validation
Gem.load_yaml Gem.load_yaml
@ -318,8 +318,8 @@ EOM
# Creates a digest of the TarEntry +entry+ from the digest algorithm set by # Creates a digest of the TarEntry +entry+ from the digest algorithm set by
# the security policy. # the security policy.
def digest entry # :nodoc: def digest(entry) # :nodoc:
algorithms = if @checksums then algorithms = if @checksums
@checksums.keys @checksums.keys
else else
[Gem::Security::DIGEST_NAME].compact [Gem::Security::DIGEST_NAME].compact
@ -327,7 +327,7 @@ EOM
algorithms.each do |algorithm| algorithms.each do |algorithm|
digester = digester =
if defined?(OpenSSL::Digest) then if defined?(OpenSSL::Digest)
OpenSSL::Digest.new algorithm OpenSSL::Digest.new algorithm
else else
Digest.const_get(algorithm).new Digest.const_get(algorithm).new
@ -349,7 +349,7 @@ EOM
# If +pattern+ is specified, only entries matching that glob will be # If +pattern+ is specified, only entries matching that glob will be
# extracted. # extracted.
def extract_files destination_dir, pattern = "*" def extract_files(destination_dir, pattern = "*")
verify unless @spec verify unless @spec
FileUtils.mkdir_p destination_dir, :mode => dir_mode && 0700 FileUtils.mkdir_p destination_dir, :mode => dir_mode && 0700
@ -378,7 +378,7 @@ EOM
# If +pattern+ is specified, only entries matching that glob will be # If +pattern+ is specified, only entries matching that glob will be
# extracted. # extracted.
def extract_tar_gz io, destination_dir, pattern = "*" # :nodoc: def extract_tar_gz(io, destination_dir, pattern = "*") # :nodoc:
directories = [] if dir_mode directories = [] if dir_mode
open_tar_gz io do |tar| open_tar_gz io do |tar|
tar.each do |entry| tar.each do |entry|
@ -391,7 +391,7 @@ EOM
mkdir_options = {} mkdir_options = {}
mkdir_options[:mode] = dir_mode ? 0700 : (entry.header.mode if entry.directory?) mkdir_options[:mode] = dir_mode ? 0700 : (entry.header.mode if entry.directory?)
mkdir = mkdir =
if entry.directory? then if entry.directory?
destination destination
else else
File.dirname destination File.dirname destination
@ -427,7 +427,7 @@ EOM
# Also sets the gzip modification time to the package build time to ease # Also sets the gzip modification time to the package build time to ease
# testing. # testing.
def gzip_to io # :yields: gz_io def gzip_to(io) # :yields: gz_io
gz_io = Zlib::GzipWriter.new io, Zlib::BEST_COMPRESSION gz_io = Zlib::GzipWriter.new io, Zlib::BEST_COMPRESSION
gz_io.mtime = @build_time gz_io.mtime = @build_time
@ -441,7 +441,7 @@ EOM
# #
# If +filename+ is not inside +destination_dir+ an exception is raised. # If +filename+ is not inside +destination_dir+ an exception is raised.
def install_location filename, destination_dir # :nodoc: def install_location(filename, destination_dir) # :nodoc:
raise Gem::Package::PathError.new(filename, destination_dir) if raise Gem::Package::PathError.new(filename, destination_dir) if
filename.start_with? '/' filename.start_with? '/'
@ -463,7 +463,7 @@ EOM
end end
end end
def mkdir_p_safe mkdir, mkdir_options, destination_dir, file_name def mkdir_p_safe(mkdir, mkdir_options, destination_dir, file_name)
destination_dir = File.realpath(File.expand_path(destination_dir)) destination_dir = File.realpath(File.expand_path(destination_dir))
parts = mkdir.split(File::SEPARATOR) parts = mkdir.split(File::SEPARATOR)
parts.reduce do |path, basename| parts.reduce do |path, basename|
@ -482,7 +482,7 @@ EOM
## ##
# Loads a Gem::Specification from the TarEntry +entry+ # Loads a Gem::Specification from the TarEntry +entry+
def load_spec entry # :nodoc: def load_spec(entry) # :nodoc:
case entry.full_name case entry.full_name
when 'metadata' then when 'metadata' then
@spec = Gem::Specification.from_yaml entry.read @spec = Gem::Specification.from_yaml entry.read
@ -500,7 +500,7 @@ EOM
## ##
# Opens +io+ as a gzipped tar archive # Opens +io+ as a gzipped tar archive
def open_tar_gz io # :nodoc: def open_tar_gz(io) # :nodoc:
Zlib::GzipReader.wrap io do |gzio| Zlib::GzipReader.wrap io do |gzio|
tar = Gem::Package::TarReader.new gzio tar = Gem::Package::TarReader.new gzio
@ -511,7 +511,7 @@ EOM
## ##
# Reads and loads checksums.yaml.gz from the tar file +gem+ # Reads and loads checksums.yaml.gz from the tar file +gem+
def read_checksums gem def read_checksums(gem)
Gem.load_yaml Gem.load_yaml
@checksums = gem.seek 'checksums.yaml.gz' do |entry| @checksums = gem.seek 'checksums.yaml.gz' do |entry|
@ -527,7 +527,7 @@ EOM
def setup_signer(signer_options: {}) def setup_signer(signer_options: {})
passphrase = ENV['GEM_PRIVATE_KEY_PASSPHRASE'] passphrase = ENV['GEM_PRIVATE_KEY_PASSPHRASE']
if @spec.signing_key then if @spec.signing_key
@signer = @signer =
Gem::Security::Signer.new( Gem::Security::Signer.new(
@spec.signing_key, @spec.signing_key,
@ -600,14 +600,14 @@ EOM
# Verifies the +checksums+ against the +digests+. This check is not # Verifies the +checksums+ against the +digests+. This check is not
# cryptographically secure. Missing checksums are ignored. # cryptographically secure. Missing checksums are ignored.
def verify_checksums digests, checksums # :nodoc: def verify_checksums(digests, checksums) # :nodoc:
return unless checksums return unless checksums
checksums.sort.each do |algorithm, gem_digests| checksums.sort.each do |algorithm, gem_digests|
gem_digests.sort.each do |file_name, gem_hexdigest| gem_digests.sort.each do |file_name, gem_hexdigest|
computed_digest = digests[algorithm][file_name] computed_digest = digests[algorithm][file_name]
unless computed_digest.hexdigest == gem_hexdigest then unless computed_digest.hexdigest == gem_hexdigest
raise Gem::Package::FormatError.new \ raise Gem::Package::FormatError.new \
"#{algorithm} checksum mismatch for #{file_name}", @gem "#{algorithm} checksum mismatch for #{file_name}", @gem
end end
@ -618,7 +618,7 @@ EOM
## ##
# Verifies +entry+ in a .gem file. # Verifies +entry+ in a .gem file.
def verify_entry entry def verify_entry(entry)
file_name = entry.full_name file_name = entry.full_name
@files << file_name @files << file_name
@ -645,16 +645,16 @@ EOM
## ##
# Verifies the files of the +gem+ # Verifies the files of the +gem+
def verify_files gem def verify_files(gem)
gem.each do |entry| gem.each do |entry|
verify_entry entry verify_entry entry
end end
unless @spec then unless @spec
raise Gem::Package::FormatError.new 'package metadata is missing', @gem raise Gem::Package::FormatError.new 'package metadata is missing', @gem
end end
unless @files.include? 'data.tar.gz' then unless @files.include? 'data.tar.gz'
raise Gem::Package::FormatError.new \ raise Gem::Package::FormatError.new \
'package content (data.tar.gz) is missing', @gem 'package content (data.tar.gz) is missing', @gem
end end
@ -667,7 +667,7 @@ EOM
## ##
# Verifies that +entry+ is a valid gzipped file. # Verifies that +entry+ is a valid gzipped file.
def verify_gz entry # :nodoc: def verify_gz(entry) # :nodoc:
Zlib::GzipReader.wrap entry do |gzio| Zlib::GzipReader.wrap entry do |gzio|
gzio.read 16384 until gzio.eof? # gzip checksum verification gzio.read 16384 until gzio.eof? # gzip checksum verification
end end

Просмотреть файл

@ -31,7 +31,7 @@ class Gem::Package::DigestIO
# digests['SHA1'].hexdigest #=> "aaf4c61d[...]" # digests['SHA1'].hexdigest #=> "aaf4c61d[...]"
# digests['SHA512'].hexdigest #=> "9b71d224[...]" # digests['SHA512'].hexdigest #=> "9b71d224[...]"
def self.wrap io, digests def self.wrap(io, digests)
digest_io = new io, digests digest_io = new io, digests
yield digest_io yield digest_io
@ -43,7 +43,7 @@ class Gem::Package::DigestIO
# Creates a new DigestIO instance. Using ::wrap is recommended, see the # Creates a new DigestIO instance. Using ::wrap is recommended, see the
# ::wrap documentation for documentation of +io+ and +digests+. # ::wrap documentation for documentation of +io+ and +digests+.
def initialize io, digests def initialize(io, digests)
@io = io @io = io
@digests = digests @digests = digests
end end
@ -51,7 +51,7 @@ class Gem::Package::DigestIO
## ##
# Writes +data+ to the underlying IO and updates the digests # Writes +data+ to the underlying IO and updates the digests
def write data def write(data)
result = @io.write data result = @io.write data
@digests.each do |_, digest| @digests.each do |_, digest|
@ -62,4 +62,3 @@ class Gem::Package::DigestIO
end end
end end

Просмотреть файл

@ -10,7 +10,7 @@ class Gem::Package::FileSource < Gem::Package::Source # :nodoc: all
attr_reader :path attr_reader :path
def initialize path def initialize(path)
@path = path @path = path
end end
@ -22,13 +22,12 @@ class Gem::Package::FileSource < Gem::Package::Source # :nodoc: all
File.exist? path File.exist? path
end end
def with_write_io &block def with_write_io(&block)
File.open path, 'wb', &block File.open path, 'wb', &block
end end
def with_read_io &block def with_read_io(&block)
File.open path, 'rb', &block File.open path, 'rb', &block
end end
end end

Просмотреть файл

@ -11,7 +11,7 @@ class Gem::Package::IOSource < Gem::Package::Source # :nodoc: all
attr_reader :io attr_reader :io
def initialize io def initialize(io)
@io = io @io = io
end end
@ -43,4 +43,3 @@ class Gem::Package::IOSource < Gem::Package::Source # :nodoc: all
end end
end end

Просмотреть файл

@ -19,7 +19,7 @@ class Gem::Package::Old < Gem::Package
# Creates a new old-format package reader for +gem+. Old-format packages # Creates a new old-format package reader for +gem+. Old-format packages
# cannot be written. # cannot be written.
def initialize gem, security_policy def initialize(gem, security_policy)
require 'fileutils' require 'fileutils'
require 'zlib' require 'zlib'
Gem.load_yaml Gem.load_yaml
@ -49,7 +49,7 @@ class Gem::Package::Old < Gem::Package
## ##
# Extracts the files in this package into +destination_dir+ # Extracts the files in this package into +destination_dir+
def extract_files destination_dir def extract_files(destination_dir)
verify verify
errstr = "Error reading files from gem" errstr = "Error reading files from gem"
@ -94,7 +94,7 @@ class Gem::Package::Old < Gem::Package
## ##
# Reads the file list section from the old-format gem +io+ # Reads the file list section from the old-format gem +io+
def file_list io # :nodoc: def file_list(io) # :nodoc:
header = String.new header = String.new
read_until_dashes io do |line| read_until_dashes io do |line|
@ -107,7 +107,7 @@ class Gem::Package::Old < Gem::Package
## ##
# Reads lines until a "---" separator is found # Reads lines until a "---" separator is found
def read_until_dashes io # :nodoc: def read_until_dashes(io) # :nodoc:
while (line = io.gets) && line.chomp.strip != "---" do while (line = io.gets) && line.chomp.strip != "---" do
yield line if block_given? yield line if block_given?
end end
@ -116,7 +116,7 @@ class Gem::Package::Old < Gem::Package
## ##
# Skips the Ruby self-install header in +io+. # Skips the Ruby self-install header in +io+.
def skip_ruby io # :nodoc: def skip_ruby(io) # :nodoc:
loop do loop do
line = io.gets line = io.gets

Просмотреть файл

@ -1,4 +1,3 @@
# frozen_string_literal: true # frozen_string_literal: true
class Gem::Package::Source # :nodoc: class Gem::Package::Source # :nodoc:
end end

Просмотреть файл

@ -134,7 +134,7 @@ class Gem::Package::TarHeader
# Creates a new TarHeader using +vals+ # Creates a new TarHeader using +vals+
def initialize(vals) def initialize(vals)
unless vals[:name] && vals[:size] && vals[:prefix] && vals[:mode] then unless vals[:name] && vals[:size] && vals[:prefix] && vals[:mode]
raise ArgumentError, ":name, :size, :prefix and :mode required" raise ArgumentError, ":name, :size, :prefix and :mode required"
end end

Просмотреть файл

@ -92,7 +92,7 @@ class Gem::Package::TarReader
# NOTE: Do not call #rewind during #each # NOTE: Do not call #rewind during #each
def rewind def rewind
if @init_pos == 0 then if @init_pos == 0
@io.rewind @io.rewind
else else
@io.pos = @init_pos @io.pos = @init_pos
@ -104,7 +104,7 @@ class Gem::Package::TarReader
# yields it. Rewinds the tar file to the beginning when the block # yields it. Rewinds the tar file to the beginning when the block
# terminates. # terminates.
def seek name # :yields: entry def seek(name) # :yields: entry
found = find do |entry| found = find do |entry|
entry.full_name == name entry.full_name == name
end end

Просмотреть файл

@ -64,7 +64,7 @@ class Gem::Package::TarReader::Entry
# Full name of the tar entry # Full name of the tar entry
def full_name def full_name
if @header.prefix != "" then if @header.prefix != ""
File.join @header.prefix, @header.name File.join @header.prefix, @header.name
else else
@header.name @header.name

Просмотреть файл

@ -52,7 +52,7 @@ class Gem::Package::TarTestCase < Gem::TestCase
name = fields.shift name = fields.shift
length = fields.shift.to_i length = fields.shift.to_i
if name == "checksum" then if name == "checksum"
chksum_off = offset chksum_off = offset
offset += length offset += length
next next

Просмотреть файл

@ -139,11 +139,11 @@ class Gem::Package::TarWriter
# #
# The created digest object is returned. # The created digest object is returned.
def add_file_digest name, mode, digest_algorithms # :yields: io def add_file_digest(name, mode, digest_algorithms) # :yields: io
digests = digest_algorithms.map do |digest_algorithm| digests = digest_algorithms.map do |digest_algorithm|
digest = digest_algorithm.new digest = digest_algorithm.new
digest_name = digest_name =
if digest.respond_to? :name then if digest.respond_to? :name
digest.name digest.name
else else
/::([^:]+)$/ =~ digest_algorithm.name /::([^:]+)$/ =~ digest_algorithm.name
@ -172,7 +172,7 @@ class Gem::Package::TarWriter
# #
# Returns the digest. # Returns the digest.
def add_file_signed name, mode, signer def add_file_signed(name, mode, signer)
digest_algorithms = [ digest_algorithms = [
signer.digest_algorithm, signer.digest_algorithm,
Digest::SHA512, Digest::SHA512,
@ -184,7 +184,7 @@ class Gem::Package::TarWriter
signature_digest = digests.values.compact.find do |digest| signature_digest = digests.values.compact.find do |digest|
digest_name = digest_name =
if digest.respond_to? :name then if digest.respond_to? :name
digest.name digest.name
else else
digest.class.name[/::([^:]+)\z/, 1] digest.class.name[/::([^:]+)\z/, 1]
@ -195,7 +195,7 @@ class Gem::Package::TarWriter
raise "no #{signer.digest_name} in #{digests.values.compact}" unless signature_digest raise "no #{signer.digest_name} in #{digests.values.compact}" unless signature_digest
if signer.key then if signer.key
signature = signer.sign signature_digest.digest signature = signer.sign signature_digest.digest
add_file_simple "#{name}.sig", 0444, signature.length do |io| add_file_simple "#{name}.sig", 0444, signature.length do |io|
@ -309,12 +309,12 @@ class Gem::Package::TarWriter
# Splits +name+ into a name and prefix that can fit in the TarHeader # Splits +name+ into a name and prefix that can fit in the TarHeader
def split_name(name) # :nodoc: def split_name(name) # :nodoc:
if name.bytesize > 256 then if name.bytesize > 256
raise Gem::Package::TooLongFileName.new("File \"#{name}\" has a too long path (should be 256 or less)") raise Gem::Package::TooLongFileName.new("File \"#{name}\" has a too long path (should be 256 or less)")
end end
prefix = '' prefix = ''
if name.bytesize > 100 then if name.bytesize > 100
parts = name.split('/', -1) # parts are never empty here parts = name.split('/', -1) # parts are never empty here
name = parts.pop # initially empty for names with a trailing slash ("foo/.../bar/") name = parts.pop # initially empty for names with a trailing slash ("foo/.../bar/")
prefix = parts.join('/') # if empty, then it's impossible to split (parts is empty too) prefix = parts.join('/') # if empty, then it's impossible to split (parts is empty too)
@ -323,11 +323,11 @@ class Gem::Package::TarWriter
prefix = parts.join('/') prefix = parts.join('/')
end end
if name.bytesize > 100 or prefix.empty? then if name.bytesize > 100 or prefix.empty?
raise Gem::Package::TooLongFileName.new("File \"#{prefix}/#{name}\" has a too long name (should be 100 or less)") raise Gem::Package::TooLongFileName.new("File \"#{prefix}/#{name}\" has a too long name (should be 100 or less)")
end end
if prefix.bytesize > 155 then if prefix.bytesize > 155
raise Gem::Package::TooLongFileName.new("File \"#{prefix}/#{name}\" has a too long base path (should be 155 or less)") raise Gem::Package::TooLongFileName.new("File \"#{prefix}/#{name}\" has a too long base path (should be 155 or less)")
end end
end end

Просмотреть файл

@ -126,4 +126,3 @@ class Gem::PackageTask < Rake::PackageTask
end end
end end

Просмотреть файл

@ -25,7 +25,7 @@ class Gem::PathSupport
def initialize(env) def initialize(env)
@home = env["GEM_HOME"] || Gem.default_dir @home = env["GEM_HOME"] || Gem.default_dir
if File::ALT_SEPARATOR then if File::ALT_SEPARATOR
@home = @home.gsub(File::ALT_SEPARATOR, File::SEPARATOR) @home = @home.gsub(File::ALT_SEPARATOR, File::SEPARATOR)
end end
@ -43,7 +43,7 @@ class Gem::PathSupport
## ##
# Split the Gem search path (as reported by Gem.path). # Split the Gem search path (as reported by Gem.path).
def split_gem_path gpaths, home def split_gem_path(gpaths, home)
# FIX: it should be [home, *path], not [*path, home] # FIX: it should be [home, *path], not [*path, home]
gem_path = [] gem_path = []
@ -56,7 +56,7 @@ class Gem::PathSupport
gem_path += default_path gem_path += default_path
end end
if File::ALT_SEPARATOR then if File::ALT_SEPARATOR
gem_path.map! do |this_path| gem_path.map! do |this_path|
this_path.gsub File::ALT_SEPARATOR, File::SEPARATOR this_path.gsub File::ALT_SEPARATOR, File::SEPARATOR
end end

Просмотреть файл

@ -56,7 +56,7 @@ class Gem::Platform
when String then when String then
arch = arch.split '-' arch = arch.split '-'
if arch.length > 2 and arch.last !~ /\d/ then # reassemble x86-linux-gnu if arch.length > 2 and arch.last !~ /\d/ # reassemble x86-linux-gnu
extra = arch.pop extra = arch.pop
arch.last << "-#{extra}" arch.last << "-#{extra}"
end end
@ -68,7 +68,7 @@ class Gem::Platform
else cpu else cpu
end end
if arch.length == 2 and arch.last =~ /^\d+(\.\d+)?$/ then # for command-line if arch.length == 2 and arch.last =~ /^\d+(\.\d+)?$/ # for command-line
@os, @version = arch @os, @version = arch
return return
end end
@ -203,4 +203,3 @@ class Gem::Platform
CURRENT = 'current'.freeze CURRENT = 'current'.freeze
end end

Просмотреть файл

@ -18,7 +18,7 @@ module Gem
end end
# This is ported over from the yaml_tree in 1.9.3 # This is ported over from the yaml_tree in 1.9.3
def format_time time def format_time(time)
if time.utc? if time.utc?
time.strftime("%Y-%m-%d %H:%M:%S.%9N Z") time.strftime("%Y-%m-%d %H:%M:%S.%9N Z")
else else

Просмотреть файл

@ -97,7 +97,7 @@ class Gem::RemoteFetcher
# Should probably be integrated with #download below, but that will be a # Should probably be integrated with #download below, but that will be a
# larger, more encompassing effort. -erikh # larger, more encompassing effort. -erikh
def download_to_cache dependency def download_to_cache(dependency)
found, _ = Gem::SpecFetcher.fetcher.spec_for_dependency dependency found, _ = Gem::SpecFetcher.fetcher.spec_for_dependency dependency
return if found.empty? return if found.empty?
@ -114,9 +114,9 @@ class Gem::RemoteFetcher
def download(spec, source_uri, install_dir = Gem.dir) def download(spec, source_uri, install_dir = Gem.dir)
cache_dir = cache_dir =
if Dir.pwd == install_dir then # see fetch_command if Dir.pwd == install_dir # see fetch_command
install_dir install_dir
elsif File.writable? install_dir then elsif File.writable? install_dir
File.join install_dir, "cache" File.join install_dir, "cache"
else else
File.join Gem.user_dir, "cache" File.join Gem.user_dir, "cache"
@ -149,7 +149,7 @@ class Gem::RemoteFetcher
# REFACTOR: be sure to clean up fake fetcher when you do this... cleaner # REFACTOR: be sure to clean up fake fetcher when you do this... cleaner
case scheme case scheme
when 'http', 'https', 's3' then when 'http', 'https', 's3' then
unless File.exist? local_gem_path then unless File.exist? local_gem_path
begin begin
verbose "Downloading gem #{gem_file_name}" verbose "Downloading gem #{gem_file_name}"
@ -183,7 +183,7 @@ class Gem::RemoteFetcher
verbose "Using local gem #{local_gem_path}" verbose "Using local gem #{local_gem_path}"
when nil then # TODO test for local overriding cache when nil then # TODO test for local overriding cache
source_path = if Gem.win_platform? && source_uri.scheme && source_path = if Gem.win_platform? && source_uri.scheme &&
!source_uri.path.include?(':') then !source_uri.path.include?(':')
"#{source_uri.scheme}:#{source_uri.path}" "#{source_uri.scheme}:#{source_uri.path}"
else else
source_uri.path source_uri.path
@ -209,14 +209,14 @@ class Gem::RemoteFetcher
## ##
# File Fetcher. Dispatched by +fetch_path+. Use it instead. # File Fetcher. Dispatched by +fetch_path+. Use it instead.
def fetch_file uri, *_ def fetch_file(uri, *_)
Gem.read_binary correct_for_windows_path uri.path Gem.read_binary correct_for_windows_path uri.path
end end
## ##
# HTTP Fetcher. Dispatched by +fetch_path+. Use it instead. # HTTP Fetcher. Dispatched by +fetch_path+. Use it instead.
def fetch_http uri, last_modified = nil, head = false, depth = 0 def fetch_http(uri, last_modified = nil, head = false, depth = 0)
fetch_type = head ? Net::HTTP::Head : Net::HTTP::Get fetch_type = head ? Net::HTTP::Head : Net::HTTP::Get
response = request uri, fetch_type, last_modified do |req| response = request uri, fetch_type, last_modified do |req|
headers.each { |k,v| req.add_field(k,v) } headers.each { |k,v| req.add_field(k,v) }
@ -291,7 +291,7 @@ class Gem::RemoteFetcher
# Downloads +uri+ to +path+ if necessary. If no path is given, it just # Downloads +uri+ to +path+ if necessary. If no path is given, it just
# passes the data. # passes the data.
def cache_update_path uri, path = nil, update = true def cache_update_path(uri, path = nil, update = true)
mtime = path && File.stat(path).mtime rescue nil mtime = path && File.stat(path).mtime rescue nil
data = fetch_path(uri, mtime) data = fetch_path(uri, mtime)
@ -375,11 +375,11 @@ class Gem::RemoteFetcher
private private
def proxy_for proxy, uri def proxy_for(proxy, uri)
Gem::Request.proxy_uri(proxy || Gem::Request.get_proxy_from_env(uri.scheme)) Gem::Request.proxy_uri(proxy || Gem::Request.get_proxy_from_env(uri.scheme))
end end
def pools_for proxy def pools_for(proxy)
@pool_lock.synchronize do @pool_lock.synchronize do
@pools[proxy] ||= Gem::Request::ConnectionPools.new proxy, @cert_files @pools[proxy] ||= Gem::Request::ConnectionPools.new proxy, @cert_files
end end

Просмотреть файл

@ -10,7 +10,7 @@ class Gem::Request
### ###
# Legacy. This is used in tests. # Legacy. This is used in tests.
def self.create_with_proxy uri, request_class, last_modified, proxy # :nodoc: def self.create_with_proxy(uri, request_class, last_modified, proxy) # :nodoc:
cert_files = get_cert_files cert_files = get_cert_files
proxy ||= get_proxy_from_env(uri.scheme) proxy ||= get_proxy_from_env(uri.scheme)
pool = ConnectionPools.new proxy_uri(proxy), cert_files pool = ConnectionPools.new proxy_uri(proxy), cert_files
@ -18,7 +18,7 @@ class Gem::Request
new(uri, request_class, last_modified, pool.pool_for(uri)) new(uri, request_class, last_modified, pool.pool_for(uri))
end end
def self.proxy_uri proxy # :nodoc: def self.proxy_uri(proxy) # :nodoc:
case proxy case proxy
when :no_proxy then nil when :no_proxy then nil
when URI::HTTP then proxy when URI::HTTP then proxy
@ -51,7 +51,7 @@ class Gem::Request
Gem.configuration.ssl_verify_mode || OpenSSL::SSL::VERIFY_PEER Gem.configuration.ssl_verify_mode || OpenSSL::SSL::VERIFY_PEER
store = OpenSSL::X509::Store.new store = OpenSSL::X509::Store.new
if Gem.configuration.ssl_client_cert then if Gem.configuration.ssl_client_cert
pem = File.read Gem.configuration.ssl_client_cert pem = File.read Gem.configuration.ssl_client_cert
connection.cert = OpenSSL::X509::Certificate.new pem connection.cert = OpenSSL::X509::Certificate.new pem
connection.key = OpenSSL::PKey::RSA.new pem connection.key = OpenSSL::PKey::RSA.new pem
@ -85,7 +85,7 @@ class Gem::Request
'Unable to require openssl, install OpenSSL and rebuild Ruby (preferred) or use non-HTTPS sources') 'Unable to require openssl, install OpenSSL and rebuild Ruby (preferred) or use non-HTTPS sources')
end end
def self.verify_certificate store_context def self.verify_certificate(store_context)
depth = store_context.error_depth depth = store_context.error_depth
error = store_context.error_string error = store_context.error_string
number = store_context.error number = store_context.error
@ -98,7 +98,7 @@ class Gem::Request
ui.alert_error extra_message if extra_message ui.alert_error extra_message if extra_message
end end
def self.verify_certificate_message error_number, cert def self.verify_certificate_message(error_number, cert)
return unless cert return unless cert
case error_number case error_number
when OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED then when OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED then
@ -139,7 +139,7 @@ class Gem::Request
def fetch def fetch
request = @request_class.new @uri.request_uri request = @request_class.new @uri.request_uri
unless @uri.nil? || @uri.user.nil? || @uri.user.empty? then unless @uri.nil? || @uri.user.nil? || @uri.user.empty?
request.basic_auth Gem::UriFormatter.new(@uri.user).unescape, request.basic_auth Gem::UriFormatter.new(@uri.user).unescape,
Gem::UriFormatter.new(@uri.password).unescape Gem::UriFormatter.new(@uri.password).unescape
end end
@ -148,7 +148,7 @@ class Gem::Request
request.add_field 'Connection', 'keep-alive' request.add_field 'Connection', 'keep-alive'
request.add_field 'Keep-Alive', '30' request.add_field 'Keep-Alive', '30'
if @last_modified then if @last_modified
request.add_field 'If-Modified-Since', @last_modified.httpdate request.add_field 'If-Modified-Since', @last_modified.httpdate
end end
@ -161,7 +161,7 @@ class Gem::Request
# Returns a proxy URI for the given +scheme+ if one is set in the # Returns a proxy URI for the given +scheme+ if one is set in the
# environment variables. # environment variables.
def self.get_proxy_from_env scheme = 'http' def self.get_proxy_from_env(scheme = 'http')
_scheme = scheme.downcase _scheme = scheme.downcase
_SCHEME = scheme.upcase _SCHEME = scheme.upcase
env_proxy = ENV["#{_scheme}_proxy"] || ENV["#{_SCHEME}_PROXY"] env_proxy = ENV["#{_scheme}_proxy"] || ENV["#{_SCHEME}_PROXY"]
@ -173,7 +173,7 @@ class Gem::Request
uri = URI(Gem::UriFormatter.new(env_proxy).normalize) uri = URI(Gem::UriFormatter.new(env_proxy).normalize)
if uri and uri.user.nil? and uri.password.nil? then if uri and uri.user.nil? and uri.password.nil?
user = ENV["#{_scheme}_proxy_user"] || ENV["#{_SCHEME}_PROXY_USER"] user = ENV["#{_scheme}_proxy_user"] || ENV["#{_SCHEME}_PROXY_USER"]
password = ENV["#{_scheme}_proxy_pass"] || ENV["#{_SCHEME}_PROXY_PASS"] password = ENV["#{_scheme}_proxy_pass"] || ENV["#{_SCHEME}_PROXY_PASS"]
@ -184,7 +184,7 @@ class Gem::Request
uri uri
end end
def perform_request request # :nodoc: def perform_request(request) # :nodoc:
connection = connection_for @uri connection = connection_for @uri
retried = false retried = false
@ -276,9 +276,9 @@ class Gem::Request
ruby_version += 'dev' if RUBY_PATCHLEVEL == -1 ruby_version += 'dev' if RUBY_PATCHLEVEL == -1
ua << " Ruby/#{ruby_version} (#{RUBY_RELEASE_DATE}" ua << " Ruby/#{ruby_version} (#{RUBY_RELEASE_DATE}"
if RUBY_PATCHLEVEL >= 0 then if RUBY_PATCHLEVEL >= 0
ua << " patchlevel #{RUBY_PATCHLEVEL}" ua << " patchlevel #{RUBY_PATCHLEVEL}"
elsif defined?(RUBY_REVISION) then elsif defined?(RUBY_REVISION)
ua << " revision #{RUBY_REVISION}" ua << " revision #{RUBY_REVISION}"
end end
ua << ")" ua << ")"

Просмотреть файл

@ -8,19 +8,19 @@ class Gem::Request::ConnectionPools # :nodoc:
attr_accessor :client attr_accessor :client
end end
def initialize proxy_uri, cert_files def initialize(proxy_uri, cert_files)
@proxy_uri = proxy_uri @proxy_uri = proxy_uri
@cert_files = cert_files @cert_files = cert_files
@pools = {} @pools = {}
@pool_mutex = Mutex.new @pool_mutex = Mutex.new
end end
def pool_for uri def pool_for(uri)
http_args = net_http_args(uri, @proxy_uri) http_args = net_http_args(uri, @proxy_uri)
key = http_args + [https?(uri)] key = http_args + [https?(uri)]
@pool_mutex.synchronize do @pool_mutex.synchronize do
@pools[key] ||= @pools[key] ||=
if https? uri then if https? uri
Gem::Request::HTTPSPool.new(http_args, @cert_files, @proxy_uri) Gem::Request::HTTPSPool.new(http_args, @cert_files, @proxy_uri)
else else
Gem::Request::HTTPPool.new(http_args, @cert_files, @proxy_uri) Gem::Request::HTTPPool.new(http_args, @cert_files, @proxy_uri)
@ -45,11 +45,11 @@ class Gem::Request::ConnectionPools # :nodoc:
env_no_proxy.split(/\s*,\s*/) env_no_proxy.split(/\s*,\s*/)
end end
def https? uri def https?(uri)
uri.scheme.downcase == 'https' uri.scheme.downcase == 'https'
end end
def no_proxy? host, env_no_proxy def no_proxy?(host, env_no_proxy)
host = host.downcase host = host.downcase
env_no_proxy.any? do |pattern| env_no_proxy.any? do |pattern|
@ -73,7 +73,7 @@ class Gem::Request::ConnectionPools # :nodoc:
end end
end end
def net_http_args uri, proxy_uri def net_http_args(uri, proxy_uri)
# URI::Generic#hostname was added in ruby 1.9.3, use it if exists, otherwise # URI::Generic#hostname was added in ruby 1.9.3, use it if exists, otherwise
# don't support IPv6 literals and use host. # don't support IPv6 literals and use host.
hostname = uri.respond_to?(:hostname) ? uri.hostname : uri.host hostname = uri.respond_to?(:hostname) ? uri.hostname : uri.host
@ -81,7 +81,7 @@ class Gem::Request::ConnectionPools # :nodoc:
no_proxy = get_no_proxy_from_env no_proxy = get_no_proxy_from_env
if proxy_uri and not no_proxy?(hostname, no_proxy) then if proxy_uri and not no_proxy?(hostname, no_proxy)
proxy_hostname = proxy_uri.respond_to?(:hostname) ? proxy_uri.hostname : proxy_uri.host proxy_hostname = proxy_uri.respond_to?(:hostname) ? proxy_uri.hostname : proxy_uri.host
net_http_args + [ net_http_args + [
proxy_hostname, proxy_hostname,
@ -89,7 +89,7 @@ class Gem::Request::ConnectionPools # :nodoc:
Gem::UriFormatter.new(proxy_uri.user).unescape, Gem::UriFormatter.new(proxy_uri.user).unescape,
Gem::UriFormatter.new(proxy_uri.password).unescape, Gem::UriFormatter.new(proxy_uri.password).unescape,
] ]
elsif no_proxy? hostname, no_proxy then elsif no_proxy? hostname, no_proxy
net_http_args + [nil, nil] net_http_args + [nil, nil]
else else
net_http_args net_http_args
@ -97,4 +97,3 @@ class Gem::Request::ConnectionPools # :nodoc:
end end
end end

Просмотреть файл

@ -8,7 +8,7 @@
class Gem::Request::HTTPPool # :nodoc: class Gem::Request::HTTPPool # :nodoc:
attr_reader :cert_files, :proxy_uri attr_reader :cert_files, :proxy_uri
def initialize http_args, cert_files, proxy_uri def initialize(http_args, cert_files, proxy_uri)
@http_args = http_args @http_args = http_args
@cert_files = cert_files @cert_files = cert_files
@proxy_uri = proxy_uri @proxy_uri = proxy_uri
@ -20,7 +20,7 @@ class Gem::Request::HTTPPool # :nodoc:
@queue.pop || make_connection @queue.pop || make_connection
end end
def checkin connection def checkin(connection)
@queue.push connection @queue.push connection
end end
@ -39,10 +39,9 @@ class Gem::Request::HTTPPool # :nodoc:
setup_connection Gem::Request::ConnectionPools.client.new(*@http_args) setup_connection Gem::Request::ConnectionPools.client.new(*@http_args)
end end
def setup_connection connection def setup_connection(connection)
connection.start connection.start
connection connection
end end
end end

Просмотреть файл

@ -2,10 +2,8 @@
class Gem::Request::HTTPSPool < Gem::Request::HTTPPool # :nodoc: class Gem::Request::HTTPSPool < Gem::Request::HTTPPool # :nodoc:
private private
def setup_connection connection def setup_connection(connection)
Gem::Request.configure_connection_for_https(connection, @cert_files) Gem::Request.configure_connection_for_https(connection, @cert_files)
super super
end end
end end

Просмотреть файл

@ -91,7 +91,7 @@ class Gem::RequestSet
# #
# set = Gem::RequestSet.new nokogiri, pg # set = Gem::RequestSet.new nokogiri, pg
def initialize *deps def initialize(*deps)
@dependencies = deps @dependencies = deps
@always_install = [] @always_install = []
@ -119,8 +119,8 @@ class Gem::RequestSet
## ##
# Declare that a gem of name +name+ with +reqs+ requirements is needed. # Declare that a gem of name +name+ with +reqs+ requirements is needed.
def gem name, *reqs def gem(name, *reqs)
if dep = @dependency_names[name] then if dep = @dependency_names[name]
dep.requirement.concat reqs dep.requirement.concat reqs
else else
dep = Gem::Dependency.new name, *reqs dep = Gem::Dependency.new name, *reqs
@ -132,7 +132,7 @@ class Gem::RequestSet
## ##
# Add +deps+ Gem::Dependency objects to the set. # Add +deps+ Gem::Dependency objects to the set.
def import deps def import(deps)
@dependencies.concat deps @dependencies.concat deps
end end
@ -143,7 +143,7 @@ class Gem::RequestSet
# The +installer+ will be +nil+ if a gem matching the request was already # The +installer+ will be +nil+ if a gem matching the request was already
# installed. # installed.
def install options, &block # :yields: request, installer def install(options, &block) # :yields: request, installer
if dir = options[:install_dir] if dir = options[:install_dir]
requests = install_into dir, false, options, &block requests = install_into dir, false, options, &block
return requests return requests
@ -181,10 +181,10 @@ class Gem::RequestSet
# Install requested gems after they have been downloaded # Install requested gems after they have been downloaded
sorted_requests.each do |req| sorted_requests.each do |req|
if req.installed? then if req.installed?
req.spec.spec.build_extensions req.spec.spec.build_extensions
if @always_install.none? { |spec| spec == req.spec.spec } then if @always_install.none? { |spec| spec == req.spec.spec }
yield req, nil if block_given? yield req, nil if block_given?
next next
end end
@ -230,7 +230,7 @@ class Gem::RequestSet
# If +:without_groups+ is given in the +options+, those groups in the gem # If +:without_groups+ is given in the +options+, those groups in the gem
# dependencies file are not used. See Gem::Installer for other +options+. # dependencies file are not used. See Gem::Installer for other +options+.
def install_from_gemdeps options, &block def install_from_gemdeps(options, &block)
gemdeps = options[:gemdeps] gemdeps = options[:gemdeps]
@install_dir = options[:install_dir] || Gem.dir @install_dir = options[:install_dir] || Gem.dir
@ -255,7 +255,7 @@ class Gem::RequestSet
else else
installed = install options, &block installed = install options, &block
if options.fetch :lock, true then if options.fetch :lock, true
lockfile = lockfile =
Gem::RequestSet::Lockfile.build self, gemdeps, gem_deps_api.dependencies Gem::RequestSet::Lockfile.build self, gemdeps, gem_deps_api.dependencies
lockfile.write lockfile.write
@ -265,7 +265,7 @@ class Gem::RequestSet
end end
end end
def install_into dir, force = true, options = {} def install_into(dir, force = true, options = {})
gem_home, ENV['GEM_HOME'] = ENV['GEM_HOME'], dir gem_home, ENV['GEM_HOME'] = ENV['GEM_HOME'], dir
existing = force ? [] : specs_in(dir) existing = force ? [] : specs_in(dir)
@ -283,7 +283,7 @@ class Gem::RequestSet
sorted_requests.each do |request| sorted_requests.each do |request|
spec = request.spec spec = request.spec
if existing.find { |s| s.full_name == spec.full_name } then if existing.find { |s| s.full_name == spec.full_name }
yield request, nil if block_given? yield request, nil if block_given?
next next
end end
@ -305,7 +305,7 @@ class Gem::RequestSet
## ##
# Call hooks on installed gems # Call hooks on installed gems
def install_hooks requests, options def install_hooks(requests, options)
specs = requests.map do |request| specs = requests.map do |request|
case request case request
when Gem::Resolver::ActivationRequest then when Gem::Resolver::ActivationRequest then
@ -327,7 +327,7 @@ class Gem::RequestSet
## ##
# Load a dependency management file. # Load a dependency management file.
def load_gemdeps path, without_groups = [], installing = false def load_gemdeps(path, without_groups = [], installing = false)
@git_set = Gem::Resolver::GitSet.new @git_set = Gem::Resolver::GitSet.new
@vendor_set = Gem::Resolver::VendorSet.new @vendor_set = Gem::Resolver::VendorSet.new
@source_set = Gem::Resolver::SourceSet.new @source_set = Gem::Resolver::SourceSet.new
@ -348,29 +348,29 @@ class Gem::RequestSet
gf.load gf.load
end end
def pretty_print q # :nodoc: def pretty_print(q) # :nodoc:
q.group 2, '[RequestSet:', ']' do q.group 2, '[RequestSet:', ']' do
q.breakable q.breakable
if @remote then if @remote
q.text 'remote' q.text 'remote'
q.breakable q.breakable
end end
if @prerelease then if @prerelease
q.text 'prerelease' q.text 'prerelease'
q.breakable q.breakable
end end
if @development_shallow then if @development_shallow
q.text 'shallow development' q.text 'shallow development'
q.breakable q.breakable
elsif @development then elsif @development
q.text 'development' q.text 'development'
q.breakable q.breakable
end end
if @soft_missing then if @soft_missing
q.text 'soft missing' q.text 'soft missing'
end end
@ -394,7 +394,7 @@ class Gem::RequestSet
# Resolve the requested dependencies and return an Array of Specification # Resolve the requested dependencies and return an Array of Specification
# objects to be activated. # objects to be activated.
def resolve set = Gem::Resolver::BestSet.new def resolve(set = Gem::Resolver::BestSet.new)
@sets << set @sets << set
@sets << @git_set @sets << @git_set
@sets << @vendor_set @sets << @vendor_set
@ -443,17 +443,17 @@ class Gem::RequestSet
@specs ||= @requests.map { |r| r.full_spec } @specs ||= @requests.map { |r| r.full_spec }
end end
def specs_in dir def specs_in(dir)
Gem::Util.glob_files_in_dir("*.gemspec", File.join(dir, "specifications")).map do |g| Gem::Util.glob_files_in_dir("*.gemspec", File.join(dir, "specifications")).map do |g|
Gem::Specification.load g Gem::Specification.load g
end end
end end
def tsort_each_node &block # :nodoc: def tsort_each_node(&block) # :nodoc:
@requests.each(&block) @requests.each(&block)
end end
def tsort_each_child node # :nodoc: def tsort_each_child(node) # :nodoc:
node.spec.dependencies.each do |dep| node.spec.dependencies.each do |dep|
next if dep.type == :development and not @development next if dep.type == :development and not @development
@ -461,7 +461,7 @@ class Gem::RequestSet
dep.match? r.spec.name, r.spec.version, @prerelease dep.match? r.spec.name, r.spec.version, @prerelease
} }
unless match then unless match
next if dep.type == :development and @development_shallow next if dep.type == :development and @development_shallow
next if @soft_missing next if @soft_missing
raise Gem::DependencyError, raise Gem::DependencyError,

Просмотреть файл

@ -191,7 +191,7 @@ class Gem::RequestSet::GemDependencyAPI
# Creates a new GemDependencyAPI that will add dependencies to the # Creates a new GemDependencyAPI that will add dependencies to the
# Gem::RequestSet +set+ based on the dependency API description in +path+. # Gem::RequestSet +set+ based on the dependency API description in +path+.
def initialize set, path def initialize(set, path)
@set = set @set = set
@path = path @path = path
@ -228,7 +228,7 @@ class Gem::RequestSet::GemDependencyAPI
# Adds +dependencies+ to the request set if any of the +groups+ are allowed. # Adds +dependencies+ to the request set if any of the +groups+ are allowed.
# This is used for gemspec dependencies. # This is used for gemspec dependencies.
def add_dependencies groups, dependencies # :nodoc: def add_dependencies(groups, dependencies) # :nodoc:
return unless (groups & @without_groups).empty? return unless (groups & @without_groups).empty?
dependencies.each do |dep| dependencies.each do |dep|
@ -241,7 +241,7 @@ class Gem::RequestSet::GemDependencyAPI
## ##
# Finds a gemspec with the given +name+ that lives at +path+. # Finds a gemspec with the given +name+ that lives at +path+.
def find_gemspec name, path # :nodoc: def find_gemspec(name, path) # :nodoc:
glob = File.join path, "#{name}.gemspec" glob = File.join path, "#{name}.gemspec"
spec_files = Dir[glob] spec_files = Dir[glob]
@ -269,7 +269,7 @@ class Gem::RequestSet::GemDependencyAPI
# In installing mode certain restrictions are ignored such as ruby version # In installing mode certain restrictions are ignored such as ruby version
# mismatch checks. # mismatch checks.
def installing= installing # :nodoc: def installing=(installing) # :nodoc:
@installing = installing @installing = installing
end end
@ -353,7 +353,7 @@ class Gem::RequestSet::GemDependencyAPI
# tag: :: # tag: ::
# Use the given tag for git:, gist: and github: dependencies. # Use the given tag for git:, gist: and github: dependencies.
def gem name, *requirements def gem(name, *requirements)
options = requirements.pop if requirements.last.kind_of?(Hash) options = requirements.pop if requirements.last.kind_of?(Hash)
options ||= {} options ||= {}
@ -369,9 +369,9 @@ class Gem::RequestSet::GemDependencyAPI
duplicate = @dependencies.include? name duplicate = @dependencies.include? name
@dependencies[name] = @dependencies[name] =
if requirements.empty? and not source_set then if requirements.empty? and not source_set
Gem::Requirement.default Gem::Requirement.default
elsif source_set then elsif source_set
Gem::Requirement.source_set Gem::Requirement.source_set
else else
Gem::Requirement.create requirements Gem::Requirement.create requirements
@ -387,7 +387,7 @@ class Gem::RequestSet::GemDependencyAPI
gem_requires name, options gem_requires name, options
if duplicate then if duplicate
warn <<-WARNING warn <<-WARNING
Gem dependencies file #{@path} requires #{name} more than once. Gem dependencies file #{@path} requires #{name} more than once.
WARNING WARNING
@ -401,8 +401,8 @@ Gem dependencies file #{@path} requires #{name} more than once.
# #
# Returns +true+ if the gist or git option was handled. # Returns +true+ if the gist or git option was handled.
def gem_git name, options # :nodoc: def gem_git(name, options) # :nodoc:
if gist = options.delete(:gist) then if gist = options.delete(:gist)
options[:git] = "https://gist.github.com/#{gist}.git" options[:git] = "https://gist.github.com/#{gist}.git"
end end
@ -424,7 +424,7 @@ Gem dependencies file #{@path} requires #{name} more than once.
# #
# Returns reference for the git gem. # Returns reference for the git gem.
def gem_git_reference options # :nodoc: def gem_git_reference(options) # :nodoc:
ref = options.delete :ref ref = options.delete :ref
branch = options.delete :branch branch = options.delete :branch
tag = options.delete :tag tag = options.delete :tag
@ -457,7 +457,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# #
# Returns +true+ if the custom source option was handled. # Returns +true+ if the custom source option was handled.
def gem_git_source name, options # :nodoc: def gem_git_source(name, options) # :nodoc:
return unless git_source = (@git_sources.keys & options.keys).last return unless git_source = (@git_sources.keys & options.keys).last
source_callback = @git_sources[git_source] source_callback = @git_sources[git_source]
@ -478,7 +478,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# Handles the :group and :groups +options+ for the gem with the given # Handles the :group and :groups +options+ for the gem with the given
# +name+. # +name+.
def gem_group name, options # :nodoc: def gem_group(name, options) # :nodoc:
g = options.delete :group g = options.delete :group
all_groups = g ? Array(g) : [] all_groups = g ? Array(g) : []
@ -497,7 +497,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# #
# Returns +true+ if the path option was handled. # Returns +true+ if the path option was handled.
def gem_path name, options # :nodoc: def gem_path(name, options) # :nodoc:
return unless directory = options.delete(:path) return unless directory = options.delete(:path)
pin_gem_source name, :path, directory pin_gem_source name, :path, directory
@ -514,7 +514,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# #
# Returns +true+ if the source option was handled. # Returns +true+ if the source option was handled.
def gem_source name, options # :nodoc: def gem_source(name, options) # :nodoc:
return unless source = options.delete(:source) return unless source = options.delete(:source)
pin_gem_source name, :source, source pin_gem_source name, :source, source
@ -530,7 +530,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# Handles the platforms: option from +options+. Returns true if the # Handles the platforms: option from +options+. Returns true if the
# platform matches the current platform. # platform matches the current platform.
def gem_platforms options # :nodoc: def gem_platforms(options) # :nodoc:
platform_names = Array(options.delete :platform) platform_names = Array(options.delete :platform)
platform_names.concat Array(options.delete :platforms) platform_names.concat Array(options.delete :platforms)
platform_names.concat @current_platforms if @current_platforms platform_names.concat @current_platforms if @current_platforms
@ -543,7 +543,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
next false unless Gem::Platform.match platform next false unless Gem::Platform.match platform
if engines = ENGINE_MAP[platform_name] then if engines = ENGINE_MAP[platform_name]
next false unless engines.include? Gem.ruby_engine next false unless engines.include? Gem.ruby_engine
end end
@ -564,9 +564,9 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# Records the require: option from +options+ and adds those files, or the # Records the require: option from +options+ and adds those files, or the
# default file to the require list for +name+. # default file to the require list for +name+.
def gem_requires name, options # :nodoc: def gem_requires(name, options) # :nodoc:
if options.include? :require then if options.include? :require
if requires = options.delete(:require) then if requires = options.delete(:require)
@requires[name].concat Array requires @requires[name].concat Array requires
end end
else else
@ -587,7 +587,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# gem 'activerecord' # gem 'activerecord'
# end # end
def git repository def git(repository)
@current_repository = repository @current_repository = repository
yield yield
@ -601,7 +601,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# for use in gems built from git repositories. You must provide a block # for use in gems built from git repositories. You must provide a block
# that accepts a git repository name for expansion. # that accepts a git repository name for expansion.
def git_source name, &callback def git_source(name, &callback)
@git_sources[name] = callback @git_sources[name] = callback
end end
@ -634,7 +634,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# The group to add development dependencies to. By default this is # The group to add development dependencies to. By default this is
# :development. Only one group may be specified. # :development. Only one group may be specified.
def gemspec options = {} def gemspec(options = {})
name = options.delete(:name) || '{,*}' name = options.delete(:name) || '{,*}'
path = options.delete(:path) || '.' path = options.delete(:path) || '.'
development_group = options.delete(:development_group) || :development development_group = options.delete(:development_group) || :development
@ -679,7 +679,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# development`. See `gem help install` and `gem help gem_dependencies` for # development`. See `gem help install` and `gem help gem_dependencies` for
# further details. # further details.
def group *groups def group(*groups)
@current_groups = groups @current_groups = groups
yield yield
@ -692,7 +692,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# Pins the gem +name+ to the given +source+. Adding a gem with the same # Pins the gem +name+ to the given +source+. Adding a gem with the same
# name from a different +source+ will raise an exception. # name from a different +source+ will raise an exception.
def pin_gem_source name, type = :default, source = nil def pin_gem_source(name, type = :default, source = nil)
source_description = source_description =
case type case type
when :default then '(default)' when :default then '(default)'
@ -754,7 +754,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# NOTE: There is inconsistency in what environment a platform matches. You # NOTE: There is inconsistency in what environment a platform matches. You
# may need to read the source to know the exact details. # may need to read the source to know the exact details.
def platform *platforms def platform(*platforms)
@current_platforms = platforms @current_platforms = platforms
yield yield
@ -781,7 +781,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# version. This matching is performed by using the RUBY_ENGINE and # version. This matching is performed by using the RUBY_ENGINE and
# engine_specific VERSION constants. (For JRuby, JRUBY_VERSION). # engine_specific VERSION constants. (For JRuby, JRUBY_VERSION).
def ruby version, options = {} def ruby(version, options = {})
engine = options[:engine] engine = options[:engine]
engine_version = options[:engine_version] engine_version = options[:engine_version]
@ -791,24 +791,24 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
return true if @installing return true if @installing
unless RUBY_VERSION == version then unless RUBY_VERSION == version
message = "Your Ruby version is #{RUBY_VERSION}, " + message = "Your Ruby version is #{RUBY_VERSION}, " +
"but your #{gem_deps_file} requires #{version}" "but your #{gem_deps_file} requires #{version}"
raise Gem::RubyVersionMismatch, message raise Gem::RubyVersionMismatch, message
end end
if engine and engine != Gem.ruby_engine then if engine and engine != Gem.ruby_engine
message = "Your Ruby engine is #{Gem.ruby_engine}, " + message = "Your Ruby engine is #{Gem.ruby_engine}, " +
"but your #{gem_deps_file} requires #{engine}" "but your #{gem_deps_file} requires #{engine}"
raise Gem::RubyVersionMismatch, message raise Gem::RubyVersionMismatch, message
end end
if engine_version then if engine_version
my_engine_version = Object.const_get "#{Gem.ruby_engine.upcase}_VERSION" my_engine_version = Object.const_get "#{Gem.ruby_engine.upcase}_VERSION"
if engine_version != my_engine_version then if engine_version != my_engine_version
message = message =
"Your Ruby engine version is #{Gem.ruby_engine} #{my_engine_version}, " + "Your Ruby engine version is #{Gem.ruby_engine} #{my_engine_version}, " +
"but your #{gem_deps_file} requires #{engine} #{engine_version}" "but your #{gem_deps_file} requires #{engine} #{engine_version}"
@ -834,7 +834,7 @@ Gem dependencies file #{@path} includes git reference for both ref/branch and ta
# * The +prepend:+ option is not supported. If you wish to order sources # * The +prepend:+ option is not supported. If you wish to order sources
# then list them in your preferred order. # then list them in your preferred order.
def source url def source(url)
Gem.sources.clear if @default_sources Gem.sources.clear if @default_sources
@default_sources = false @default_sources = false

Просмотреть файл

@ -29,7 +29,7 @@ class Gem::RequestSet::Lockfile
# Raises a ParseError with the given +message+ which was encountered at a # Raises a ParseError with the given +message+ which was encountered at a
# +line+ and +column+ while parsing. # +line+ and +column+ while parsing.
def initialize message, column, line, path def initialize(message, column, line, path)
@line = line @line = line
@column = column @column = column
@path = path @path = path
@ -41,13 +41,13 @@ class Gem::RequestSet::Lockfile
# Creates a new Lockfile for the given +request_set+ and +gem_deps_file+ # Creates a new Lockfile for the given +request_set+ and +gem_deps_file+
# location. # location.
def self.build request_set, gem_deps_file, dependencies = nil def self.build(request_set, gem_deps_file, dependencies = nil)
request_set.resolve request_set.resolve
dependencies ||= requests_to_deps request_set.sorted_requests dependencies ||= requests_to_deps request_set.sorted_requests
new request_set, gem_deps_file, dependencies new request_set, gem_deps_file, dependencies
end end
def self.requests_to_deps requests # :nodoc: def self.requests_to_deps(requests) # :nodoc:
deps = {} deps = {}
requests.each do |request| requests.each do |request|
@ -56,7 +56,7 @@ class Gem::RequestSet::Lockfile
requirement = request.request.dependency.requirement requirement = request.request.dependency.requirement
deps[name] = if [Gem::Resolver::VendorSpecification, deps[name] = if [Gem::Resolver::VendorSpecification,
Gem::Resolver::GitSpecification].include? spec.class then Gem::Resolver::GitSpecification].include? spec.class
Gem::Requirement.source_set Gem::Requirement.source_set
else else
requirement requirement
@ -71,7 +71,7 @@ class Gem::RequestSet::Lockfile
attr_reader :platforms attr_reader :platforms
def initialize request_set, gem_deps_file, dependencies def initialize(request_set, gem_deps_file, dependencies)
@set = request_set @set = request_set
@dependencies = dependencies @dependencies = dependencies
@gem_deps_file = File.expand_path(gem_deps_file) @gem_deps_file = File.expand_path(gem_deps_file)
@ -82,7 +82,7 @@ class Gem::RequestSet::Lockfile
@platforms = [] @platforms = []
end end
def add_DEPENDENCIES out # :nodoc: def add_DEPENDENCIES(out) # :nodoc:
out << "DEPENDENCIES" out << "DEPENDENCIES"
out.concat @dependencies.sort_by { |name,| name }.map { |name, requirement| out.concat @dependencies.sort_by { |name,| name }.map { |name, requirement|
@ -92,7 +92,7 @@ class Gem::RequestSet::Lockfile
out << nil out << nil
end end
def add_GEM out, spec_groups # :nodoc: def add_GEM(out, spec_groups) # :nodoc:
return if spec_groups.empty? return if spec_groups.empty?
source_groups = spec_groups.values.flatten.group_by do |request| source_groups = spec_groups.values.flatten.group_by do |request|
@ -122,7 +122,7 @@ class Gem::RequestSet::Lockfile
end end
end end
def add_GIT out, git_requests def add_GIT(out, git_requests)
return if git_requests.empty? return if git_requests.empty?
by_repository_revision = git_requests.group_by do |request| by_repository_revision = git_requests.group_by do |request|
@ -148,11 +148,11 @@ class Gem::RequestSet::Lockfile
end end
end end
def relative_path_from dest, base # :nodoc: def relative_path_from(dest, base) # :nodoc:
dest = File.expand_path(dest) dest = File.expand_path(dest)
base = File.expand_path(base) base = File.expand_path(base)
if dest.index(base) == 0 then if dest.index(base) == 0
offset = dest[base.size+1..-1] offset = dest[base.size+1..-1]
return '.' unless offset return '.' unless offset
@ -163,7 +163,7 @@ class Gem::RequestSet::Lockfile
end end
end end
def add_PATH out, path_requests # :nodoc: def add_PATH(out, path_requests) # :nodoc:
return if path_requests.empty? return if path_requests.empty?
out << "PATH" out << "PATH"
@ -178,7 +178,7 @@ class Gem::RequestSet::Lockfile
out << nil out << nil
end end
def add_PLATFORMS out # :nodoc: def add_PLATFORMS(out) # :nodoc:
out << "PLATFORMS" out << "PLATFORMS"
platforms = requests.map { |request| request.spec.platform }.uniq platforms = requests.map { |request| request.spec.platform }.uniq

Просмотреть файл

@ -3,7 +3,7 @@ class Gem::RequestSet::Lockfile::Parser
### ###
# Parses lockfiles # Parses lockfiles
def initialize tokenizer, set, platforms, filename = nil def initialize(tokenizer, set, platforms, filename = nil)
@tokens = tokenizer @tokens = tokenizer
@filename = filename @filename = filename
@set = set @set = set
@ -41,10 +41,10 @@ class Gem::RequestSet::Lockfile::Parser
## ##
# Gets the next token for a Lockfile # Gets the next token for a Lockfile
def get expected_types = nil, expected_value = nil # :nodoc: def get(expected_types = nil, expected_value = nil) # :nodoc:
token = @tokens.shift token = @tokens.shift
if expected_types and not Array(expected_types).include? token.type then if expected_types and not Array(expected_types).include? token.type
unget token unget token
message = "unexpected token [#{token.type.inspect}, #{token.value.inspect}], " + message = "unexpected token [#{token.type.inspect}, #{token.value.inspect}], " +
@ -53,7 +53,7 @@ class Gem::RequestSet::Lockfile::Parser
raise Gem::RequestSet::Lockfile::ParseError.new message, token.column, token.line, @filename raise Gem::RequestSet::Lockfile::ParseError.new message, token.column, token.line, @filename
end end
if expected_value and expected_value != token.value then if expected_value and expected_value != token.value
unget token unget token
message = "unexpected token [#{token.type.inspect}, #{token.value.inspect}], " + message = "unexpected token [#{token.type.inspect}, #{token.value.inspect}], " +
@ -93,7 +93,7 @@ class Gem::RequestSet::Lockfile::Parser
get :r_paren get :r_paren
if peek[0] == :bang then if peek[0] == :bang
requirements.clear requirements.clear
requirements << pinned_requirement(token.value) requirements << pinned_requirement(token.value)
@ -144,7 +144,7 @@ class Gem::RequestSet::Lockfile::Parser
type = token.type type = token.type
data = token.value data = token.value
if type == :text and column == 4 then if type == :text and column == 4
version, platform = data.split '-', 2 version, platform = data.split '-', 2
platform = platform =
@ -183,7 +183,7 @@ class Gem::RequestSet::Lockfile::Parser
type = peek.type type = peek.type
value = peek.value value = peek.value
if type == :entry and %w[branch ref tag].include? value then if type == :entry and %w[branch ref tag].include? value
get get
get :text get :text
@ -214,7 +214,7 @@ class Gem::RequestSet::Lockfile::Parser
type = token.type type = token.type
data = token.value data = token.value
if type == :text and column == 4 then if type == :text and column == 4
last_spec = set.add_git_spec name, data, repository, revision, true last_spec = set.add_git_spec name, data, repository, revision, true
else else
dependency = parse_dependency name, data dependency = parse_dependency name, data
@ -261,7 +261,7 @@ class Gem::RequestSet::Lockfile::Parser
type = token.type type = token.type
data = token.value data = token.value
if type == :text and column == 4 then if type == :text and column == 4
last_spec = set.add_vendor_gem name, directory last_spec = set.add_vendor_gem name, directory
else else
dependency = parse_dependency name, data dependency = parse_dependency name, data
@ -294,7 +294,7 @@ class Gem::RequestSet::Lockfile::Parser
# Parses the requirements following the dependency +name+ and the +op+ for # Parses the requirements following the dependency +name+ and the +op+ for
# the first token of the requirements and returns a Gem::Dependency object. # the first token of the requirements and returns a Gem::Dependency object.
def parse_dependency name, op # :nodoc: def parse_dependency(name, op) # :nodoc:
return Gem::Dependency.new name, op unless peek[0] == :text return Gem::Dependency.new name, op unless peek[0] == :text
version = get(:text).value version = get(:text).value
@ -314,7 +314,7 @@ class Gem::RequestSet::Lockfile::Parser
private private
def skip type # :nodoc: def skip(type) # :nodoc:
@tokens.skip type @tokens.skip type
end end
@ -325,7 +325,7 @@ class Gem::RequestSet::Lockfile::Parser
@tokens.peek @tokens.peek
end end
def pinned_requirement name # :nodoc: def pinned_requirement(name) # :nodoc:
requirement = Gem::Dependency.new name requirement = Gem::Dependency.new name
specification = @set.sets.flat_map { |set| specification = @set.sets.flat_map { |set|
set.find_all(requirement) set.find_all(requirement)
@ -337,7 +337,7 @@ class Gem::RequestSet::Lockfile::Parser
## ##
# Ungets the last token retrieved by #get # Ungets the last token retrieved by #get
def unget token # :nodoc: def unget(token) # :nodoc:
@tokens.unshift token @tokens.unshift token
end end
end end

Просмотреть файл

@ -5,11 +5,11 @@ class Gem::RequestSet::Lockfile::Tokenizer
Token = Struct.new :type, :value, :column, :line Token = Struct.new :type, :value, :column, :line
EOF = Token.new :EOF EOF = Token.new :EOF
def self.from_file file def self.from_file(file)
new File.read(file), file new File.read(file), file
end end
def initialize input, filename = nil, line = 0, pos = 0 def initialize(input, filename = nil, line = 0, pos = 0)
@line = line @line = line
@line_pos = pos @line_pos = pos
@tokens = [] @tokens = []
@ -17,7 +17,7 @@ class Gem::RequestSet::Lockfile::Tokenizer
tokenize input tokenize input
end end
def make_parser set, platforms def make_parser(set, platforms)
Gem::RequestSet::Lockfile::Parser.new self, set, platforms, @filename Gem::RequestSet::Lockfile::Parser.new self, set, platforms, @filename
end end
@ -25,7 +25,7 @@ class Gem::RequestSet::Lockfile::Tokenizer
@tokens.map { |token| [token.type, token.value, token.column, token.line] } @tokens.map { |token| [token.type, token.value, token.column, token.line] }
end end
def skip type def skip(type)
@tokens.shift while not @tokens.empty? and peek.type == type @tokens.shift while not @tokens.empty? and peek.type == type
end end
@ -33,7 +33,7 @@ class Gem::RequestSet::Lockfile::Tokenizer
# Calculates the column (by byte) and the line of the current token based on # Calculates the column (by byte) and the line of the current token based on
# +byte_offset+. # +byte_offset+.
def token_pos byte_offset # :nodoc: def token_pos(byte_offset) # :nodoc:
[byte_offset - @line_pos, @line] [byte_offset - @line_pos, @line]
end end
@ -41,7 +41,7 @@ class Gem::RequestSet::Lockfile::Tokenizer
@tokens.empty? @tokens.empty?
end end
def unshift token def unshift(token)
@tokens.unshift token @tokens.unshift token
end end
@ -56,7 +56,7 @@ class Gem::RequestSet::Lockfile::Tokenizer
private private
def tokenize input def tokenize(input)
require 'strscan' require 'strscan'
s = StringScanner.new input s = StringScanner.new input
@ -65,7 +65,7 @@ class Gem::RequestSet::Lockfile::Tokenizer
pos = s.pos if leading_whitespace = s.scan(/ +/) pos = s.pos if leading_whitespace = s.scan(/ +/)
if s.scan(/[<|=>]{7}/) then if s.scan(/[<|=>]{7}/)
message = "your #{@filename} contains merge conflict markers" message = "your #{@filename} contains merge conflict markers"
column, line = token_pos pos column, line = token_pos pos
@ -80,7 +80,7 @@ class Gem::RequestSet::Lockfile::Tokenizer
@line += 1 @line += 1
token token
when s.scan(/[A-Z]+/) then when s.scan(/[A-Z]+/) then
if leading_whitespace then if leading_whitespace
text = s.matched text = s.matched
text += s.scan(/[^\s)]*/).to_s # in case of no match text += s.scan(/[^\s)]*/).to_s # in case of no match
Token.new(:text, text, *token_pos(pos)) Token.new(:text, text, *token_pos(pos))

Просмотреть файл

@ -32,7 +32,7 @@ class Gem::Requirement
## ##
# A regular expression that matches a requirement # A regular expression that matches a requirement
PATTERN = /\A#{PATTERN_RAW}\z/ PATTERN = /\A#{PATTERN_RAW}\z/.freeze
## ##
# The default requirement matches any version # The default requirement matches any version
@ -51,7 +51,7 @@ class Gem::Requirement
# If the input is "weird", the default version requirement is # If the input is "weird", the default version requirement is
# returned. # returned.
def self.create *inputs def self.create(*inputs)
return new inputs if inputs.length > 1 return new inputs if inputs.length > 1
input = inputs.shift input = inputs.shift
@ -64,7 +64,7 @@ class Gem::Requirement
when '!' then when '!' then
source_set source_set
else else
if input.respond_to? :to_str then if input.respond_to? :to_str
new [input.to_str] new [input.to_str]
else else
default default
@ -98,7 +98,7 @@ class Gem::Requirement
# parse("1.0") # => ["=", Gem::Version.new("1.0")] # parse("1.0") # => ["=", Gem::Version.new("1.0")]
# parse(Gem::Version.new("1.0")) # => ["=, Gem::Version.new("1.0")] # parse(Gem::Version.new("1.0")) # => ["=, Gem::Version.new("1.0")]
def self.parse obj def self.parse(obj)
return ["=", obj] if Gem::Version === obj return ["=", obj] if Gem::Version === obj
unless PATTERN =~ obj.to_s unless PATTERN =~ obj.to_s
@ -124,7 +124,7 @@ class Gem::Requirement
# requirements are ignored. An empty set of +requirements+ is the # requirements are ignored. An empty set of +requirements+ is the
# same as <tt>">= 0"</tt>. # same as <tt>">= 0"</tt>.
def initialize *requirements def initialize(*requirements)
requirements = requirements.flatten requirements = requirements.flatten
requirements.compact! requirements.compact!
requirements.uniq! requirements.uniq!
@ -140,7 +140,7 @@ class Gem::Requirement
## ##
# Concatenates the +new+ requirements onto this requirement. # Concatenates the +new+ requirements onto this requirement.
def concat new def concat(new)
new = new.flatten new = new.flatten
new.compact! new.compact!
new.uniq! new.uniq!
@ -198,7 +198,7 @@ class Gem::Requirement
[@requirements] [@requirements]
end end
def marshal_load array # :nodoc: def marshal_load(array) # :nodoc:
@requirements = array[0] @requirements = array[0]
fix_syck_default_key_in_requirements fix_syck_default_key_in_requirements
@ -213,7 +213,7 @@ class Gem::Requirement
fix_syck_default_key_in_requirements fix_syck_default_key_in_requirements
end end
def init_with coder # :nodoc: def init_with(coder) # :nodoc:
yaml_initialize coder.tag, coder.map yaml_initialize coder.tag, coder.map
end end
@ -221,7 +221,7 @@ class Gem::Requirement
["@requirements"] ["@requirements"]
end end
def encode_with coder # :nodoc: def encode_with(coder) # :nodoc:
coder.add 'requirements', @requirements coder.add 'requirements', @requirements
end end
@ -233,7 +233,7 @@ class Gem::Requirement
requirements.any? { |r| r.last.prerelease? } requirements.any? { |r| r.last.prerelease? }
end end
def pretty_print q # :nodoc: def pretty_print(q) # :nodoc:
q.group 1, 'Gem::Requirement.new(', ')' do q.group 1, 'Gem::Requirement.new(', ')' do
q.pp as_list q.pp as_list
end end
@ -242,7 +242,7 @@ class Gem::Requirement
## ##
# True if +version+ satisfies this Requirement. # True if +version+ satisfies this Requirement.
def satisfied_by? version def satisfied_by?(version)
raise ArgumentError, "Need a Gem::Version: #{version.inspect}" unless raise ArgumentError, "Need a Gem::Version: #{version.inspect}" unless
Gem::Version === version Gem::Version === version
# #28965: syck has a bug with unquoted '=' YAML.loading as YAML::DefaultKey # #28965: syck has a bug with unquoted '=' YAML.loading as YAML::DefaultKey
@ -265,7 +265,7 @@ class Gem::Requirement
as_list.join ", " as_list.join ", "
end end
def == other # :nodoc: def ==(other) # :nodoc:
return unless Gem::Requirement === other return unless Gem::Requirement === other
requirements == other.requirements requirements == other.requirements
end end

Просмотреть файл

@ -59,7 +59,7 @@ class Gem::Resolver
# uniform manner. If one of the +sets+ is itself a ComposedSet its sets are # uniform manner. If one of the +sets+ is itself a ComposedSet its sets are
# flattened into the result ComposedSet. # flattened into the result ComposedSet.
def self.compose_sets *sets def self.compose_sets(*sets)
sets.compact! sets.compact!
sets = sets.map do |set| sets = sets.map do |set|
@ -87,7 +87,7 @@ class Gem::Resolver
# Creates a Resolver that queries only against the already installed gems # Creates a Resolver that queries only against the already installed gems
# for the +needed+ dependencies. # for the +needed+ dependencies.
def self.for_current_gems needed def self.for_current_gems(needed)
new needed, Gem::Resolver::CurrentSet.new new needed, Gem::Resolver::CurrentSet.new
end end
@ -99,7 +99,7 @@ class Gem::Resolver
# satisfy the Dependencies. This defaults to IndexSet, which will query # satisfy the Dependencies. This defaults to IndexSet, which will query
# rubygems.org. # rubygems.org.
def initialize needed, set = nil def initialize(needed, set = nil)
@set = set || Gem::Resolver::IndexSet.new @set = set || Gem::Resolver::IndexSet.new
@needed = needed @needed = needed
@ -112,14 +112,14 @@ class Gem::Resolver
@stats = Gem::Resolver::Stats.new @stats = Gem::Resolver::Stats.new
end end
def explain stage, *data # :nodoc: def explain(stage, *data) # :nodoc:
return unless DEBUG_RESOLVER return unless DEBUG_RESOLVER
d = data.map { |x| x.pretty_inspect }.join(", ") d = data.map { |x| x.pretty_inspect }.join(", ")
$stderr.printf "%10s %s\n", stage.to_s.upcase, d $stderr.printf "%10s %s\n", stage.to_s.upcase, d
end end
def explain_list stage # :nodoc: def explain_list(stage) # :nodoc:
return unless DEBUG_RESOLVER return unless DEBUG_RESOLVER
data = yield data = yield
@ -133,7 +133,7 @@ class Gem::Resolver
# #
# Returns the Specification and the ActivationRequest # Returns the Specification and the ActivationRequest
def activation_request dep, possible # :nodoc: def activation_request(dep, possible) # :nodoc:
spec = possible.pop spec = possible.pop
explain :activate, [spec.full_name, possible.size] explain :activate, [spec.full_name, possible.size]
@ -145,7 +145,7 @@ class Gem::Resolver
return spec, activation_request return spec, activation_request
end end
def requests s, act, reqs=[] # :nodoc: def requests(s, act, reqs=[]) # :nodoc:
return reqs if @ignore_dependencies return reqs if @ignore_dependencies
s.fetch_development_dependencies if @development s.fetch_development_dependencies if @development
@ -197,7 +197,7 @@ class Gem::Resolver
# Extracts the specifications that may be able to fulfill +dependency+ and # Extracts the specifications that may be able to fulfill +dependency+ and
# returns those that match the local platform and all those that match. # returns those that match the local platform and all those that match.
def find_possible dependency # :nodoc: def find_possible(dependency) # :nodoc:
all = @set.find_all dependency all = @set.find_all dependency
if (skip_dep_gems = skip_gems[dependency.name]) && !skip_dep_gems.empty? if (skip_dep_gems = skip_gems[dependency.name]) && !skip_dep_gems.empty?
@ -216,7 +216,7 @@ class Gem::Resolver
## ##
# Returns the gems in +specs+ that match the local platform. # Returns the gems in +specs+ that match the local platform.
def select_local_platforms specs # :nodoc: def select_local_platforms(specs) # :nodoc:
specs.select do |spec| specs.select do |spec|
Gem::Platform.installable? spec Gem::Platform.installable? spec
end end

Просмотреть файл

@ -22,13 +22,13 @@ class Gem::Resolver::ActivationRequest
# +others_possible+ indicates that other specifications may also match this # +others_possible+ indicates that other specifications may also match this
# activation request. # activation request.
def initialize spec, request, others_possible = true def initialize(spec, request, others_possible = true)
@spec = spec @spec = spec
@request = request @request = request
@others_possible = others_possible @others_possible = others_possible
end end
def == other # :nodoc: def ==(other) # :nodoc:
case other case other
when Gem::Specification when Gem::Specification
@spec == other @spec == other
@ -49,7 +49,7 @@ class Gem::Resolver::ActivationRequest
## ##
# Downloads a gem at +path+ and returns the file path. # Downloads a gem at +path+ and returns the file path.
def download path def download(path)
Gem.ensure_gem_subdirectories path Gem.ensure_gem_subdirectories path
if @spec.respond_to? :sources if @spec.respond_to? :sources
@ -97,7 +97,7 @@ class Gem::Resolver::ActivationRequest
when false then # TODO remove at RubyGems 3 when false then # TODO remove at RubyGems 3
nil nil
else else
unless @others_possible.empty? then unless @others_possible.empty?
others = @others_possible.map { |s| s.full_name } others = @others_possible.map { |s| s.full_name }
" (others possible: #{others.join ', '})" " (others possible: #{others.join ', '})"
end end
@ -152,7 +152,7 @@ class Gem::Resolver::ActivationRequest
@request.requester @request.requester
end end
def pretty_print q # :nodoc: def pretty_print(q) # :nodoc:
q.group 2, '[Activation request', ']' do q.group 2, '[Activation request', ']' do
q.breakable q.breakable
q.pp @spec q.pp @spec
@ -167,7 +167,7 @@ class Gem::Resolver::ActivationRequest
q.breakable q.breakable
q.text 'others possible' q.text 'others possible'
else else
unless @others_possible.empty? then unless @others_possible.empty?
q.breakable q.breakable
q.text 'others ' q.text 'others '
q.pp @others_possible.map { |s| s.full_name } q.pp @others_possible.map { |s| s.full_name }

Просмотреть файл

@ -25,7 +25,7 @@ class Gem::Resolver::APISet < Gem::Resolver::Set
# API URL +dep_uri+ which is described at # API URL +dep_uri+ which is described at
# http://guides.rubygems.org/rubygems-org-api # http://guides.rubygems.org/rubygems-org-api
def initialize dep_uri = 'https://rubygems.org/api/v1/dependencies' def initialize(dep_uri = 'https://rubygems.org/api/v1/dependencies')
super() super()
dep_uri = URI dep_uri unless URI === dep_uri # for ruby 1.8 dep_uri = URI dep_uri unless URI === dep_uri # for ruby 1.8
@ -43,7 +43,7 @@ class Gem::Resolver::APISet < Gem::Resolver::Set
# Return an array of APISpecification objects matching # Return an array of APISpecification objects matching
# DependencyRequest +req+. # DependencyRequest +req+.
def find_all req def find_all(req)
res = [] res = []
return res unless @remote return res unless @remote
@ -65,7 +65,7 @@ class Gem::Resolver::APISet < Gem::Resolver::Set
# A hint run by the resolver to allow the Set to fetch # A hint run by the resolver to allow the Set to fetch
# data for DependencyRequests +reqs+. # data for DependencyRequests +reqs+.
def prefetch reqs def prefetch(reqs)
return unless @remote return unless @remote
names = reqs.map { |r| r.dependency.name } names = reqs.map { |r| r.dependency.name }
needed = names - @data.keys - @to_fetch needed = names - @data.keys - @to_fetch
@ -93,7 +93,7 @@ class Gem::Resolver::APISet < Gem::Resolver::Set
end end
end end
def pretty_print q # :nodoc: def pretty_print(q) # :nodoc:
q.group 2, '[APISet', ']' do q.group 2, '[APISet', ']' do
q.breakable q.breakable
q.text "URI: #{@dep_uri}" q.text "URI: #{@dep_uri}"
@ -107,7 +107,7 @@ class Gem::Resolver::APISet < Gem::Resolver::Set
## ##
# Return data for all versions of the gem +name+. # Return data for all versions of the gem +name+.
def versions name # :nodoc: def versions(name) # :nodoc:
if @data.key?(name) if @data.key?(name)
return @data[name] return @data[name]
end end
@ -123,4 +123,3 @@ class Gem::Resolver::APISet < Gem::Resolver::Set
end end
end end

Просмотреть файл

@ -27,7 +27,7 @@ class Gem::Resolver::APISpecification < Gem::Resolver::Specification
end end
end end
def == other # :nodoc: def ==(other) # :nodoc:
self.class === other and self.class === other and
@set == other.set and @set == other.set and
@name == other.name and @name == other.name and
@ -46,7 +46,7 @@ class Gem::Resolver::APISpecification < Gem::Resolver::Specification
Gem::Platform.match @platform Gem::Platform.match @platform
end end
def pretty_print q # :nodoc: def pretty_print(q) # :nodoc:
q.group 2, '[APISpecification', ']' do q.group 2, '[APISpecification', ']' do
q.breakable q.breakable
q.text "name: #{name}" q.text "name: #{name}"
@ -88,4 +88,3 @@ class Gem::Resolver::APISpecification < Gem::Resolver::Specification
end end
end end

Просмотреть файл

@ -10,7 +10,7 @@ class Gem::Resolver::BestSet < Gem::Resolver::ComposedSet
# Creates a BestSet for the given +sources+ or Gem::sources if none are # Creates a BestSet for the given +sources+ or Gem::sources if none are
# specified. +sources+ must be a Gem::SourceList. # specified. +sources+ must be a Gem::SourceList.
def initialize sources = Gem.sources def initialize(sources = Gem.sources)
super() super()
@sources = sources @sources = sources
@ -25,7 +25,7 @@ class Gem::Resolver::BestSet < Gem::Resolver::ComposedSet
end end
end end
def find_all req # :nodoc: def find_all(req) # :nodoc:
pick_sets if @remote and @sets.empty? pick_sets if @remote and @sets.empty?
super super
@ -35,13 +35,13 @@ class Gem::Resolver::BestSet < Gem::Resolver::ComposedSet
retry retry
end end
def prefetch reqs # :nodoc: def prefetch(reqs) # :nodoc:
pick_sets if @remote and @sets.empty? pick_sets if @remote and @sets.empty?
super super
end end
def pretty_print q # :nodoc: def pretty_print(q) # :nodoc:
q.group 2, '[BestSet', ']' do q.group 2, '[BestSet', ']' do
q.breakable q.breakable
q.text 'sets:' q.text 'sets:'
@ -58,7 +58,7 @@ class Gem::Resolver::BestSet < Gem::Resolver::ComposedSet
# #
# The calling method must retry the exception to repeat the lookup. # The calling method must retry the exception to repeat the lookup.
def replace_failed_api_set error # :nodoc: def replace_failed_api_set(error) # :nodoc:
uri = error.uri uri = error.uri
uri = URI uri unless URI === uri uri = URI uri unless URI === uri
uri.query = nil uri.query = nil
@ -76,4 +76,3 @@ class Gem::Resolver::BestSet < Gem::Resolver::ComposedSet
end end
end end

Просмотреть файл

@ -16,7 +16,7 @@ class Gem::Resolver::ComposedSet < Gem::Resolver::Set
# Creates a new ComposedSet containing +sets+. Use # Creates a new ComposedSet containing +sets+. Use
# Gem::Resolver::compose_sets instead. # Gem::Resolver::compose_sets instead.
def initialize *sets def initialize(*sets)
super() super()
@sets = sets @sets = sets
@ -26,7 +26,7 @@ class Gem::Resolver::ComposedSet < Gem::Resolver::Set
# When +allow_prerelease+ is set to +true+ prereleases gems are allowed to # When +allow_prerelease+ is set to +true+ prereleases gems are allowed to
# match dependencies. # match dependencies.
def prerelease= allow_prerelease def prerelease=(allow_prerelease)
super super
sets.each do |set| sets.each do |set|
@ -37,7 +37,7 @@ class Gem::Resolver::ComposedSet < Gem::Resolver::Set
## ##
# Sets the remote network access for all composed sets. # Sets the remote network access for all composed sets.
def remote= remote def remote=(remote)
super super
@sets.each { |set| set.remote = remote } @sets.each { |set| set.remote = remote }
@ -50,7 +50,7 @@ class Gem::Resolver::ComposedSet < Gem::Resolver::Set
## ##
# Finds all specs matching +req+ in all sets. # Finds all specs matching +req+ in all sets.
def find_all req def find_all(req)
@sets.map do |s| @sets.map do |s|
s.find_all req s.find_all req
end.flatten end.flatten
@ -59,9 +59,8 @@ class Gem::Resolver::ComposedSet < Gem::Resolver::Set
## ##
# Prefetches +reqs+ in all sets. # Prefetches +reqs+ in all sets.
def prefetch reqs def prefetch(reqs)
@sets.each { |s| s.prefetch(reqs) } @sets.each { |s| s.prefetch(reqs) }
end end
end end

Просмотреть файл

@ -27,7 +27,7 @@ class Gem::Resolver::Conflict
@failed_dep = failed_dep @failed_dep = failed_dep
end end
def == other # :nodoc: def ==(other) # :nodoc:
self.class === other and self.class === other and
@dependency == other.dependency and @dependency == other.dependency and
@activated == other.activated and @activated == other.activated and
@ -57,7 +57,7 @@ class Gem::Resolver::Conflict
requirement = dependency.requirement requirement = dependency.requirement
alternates = dependency.matching_specs.map { |spec| spec.full_name } alternates = dependency.matching_specs.map { |spec| spec.full_name }
unless alternates.empty? then unless alternates.empty?
matching = <<-MATCHING.chomp matching = <<-MATCHING.chomp
Gems matching %s: Gems matching %s:
@ -97,7 +97,7 @@ class Gem::Resolver::Conflict
@dependency.name == spec.name @dependency.name == spec.name
end end
def pretty_print q # :nodoc: def pretty_print(q) # :nodoc:
q.group 2, '[Dependency conflict: ', ']' do q.group 2, '[Dependency conflict: ', ']' do
q.breakable q.breakable
@ -109,7 +109,7 @@ class Gem::Resolver::Conflict
q.pp @dependency q.pp @dependency
q.breakable q.breakable
if @dependency == @failed_dep then if @dependency == @failed_dep
q.text ' failed' q.text ' failed'
else else
q.text ' failed dependency ' q.text ' failed dependency '
@ -121,7 +121,7 @@ class Gem::Resolver::Conflict
## ##
# Path of activations from the +current+ list. # Path of activations from the +current+ list.
def request_path current def request_path(current)
path = [] path = []
while current do while current do

Просмотреть файл

@ -6,9 +6,8 @@
class Gem::Resolver::CurrentSet < Gem::Resolver::Set class Gem::Resolver::CurrentSet < Gem::Resolver::Set
def find_all req def find_all(req)
req.dependency.matching_specs req.dependency.matching_specs
end end
end end

Просмотреть файл

@ -19,12 +19,12 @@ class Gem::Resolver::DependencyRequest
# Creates a new DependencyRequest for +dependency+ from +requester+. # Creates a new DependencyRequest for +dependency+ from +requester+.
# +requester may be nil if the request came from a user. # +requester may be nil if the request came from a user.
def initialize dependency, requester def initialize(dependency, requester)
@dependency = dependency @dependency = dependency
@requester = requester @requester = requester
end end
def == other # :nodoc: def ==(other) # :nodoc:
case other case other
when Gem::Dependency when Gem::Dependency
@dependency == other @dependency == other
@ -48,7 +48,7 @@ class Gem::Resolver::DependencyRequest
# NOTE: #match? only matches prerelease versions when #dependency is a # NOTE: #match? only matches prerelease versions when #dependency is a
# prerelease dependency. # prerelease dependency.
def match? spec, allow_prerelease = false def match?(spec, allow_prerelease = false)
@dependency.match? spec, nil, allow_prerelease @dependency.match? spec, nil, allow_prerelease
end end
@ -95,7 +95,7 @@ class Gem::Resolver::DependencyRequest
@requester ? @requester.request : "(unknown)" @requester ? @requester.request : "(unknown)"
end end
def pretty_print q # :nodoc: def pretty_print(q) # :nodoc:
q.group 2, '[Dependency request ', ']' do q.group 2, '[Dependency request ', ']' do
q.breakable q.breakable
q.text @dependency.to_s q.text @dependency.to_s

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше