diff options
author | drbrain <drbrain@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2009-06-09 21:38:59 +0000 |
---|---|---|
committer | drbrain <drbrain@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2009-06-09 21:38:59 +0000 |
commit | 31c94ffeb5f09d09ac2c86fc9e6614e38251a43d () | |
tree | 10e44506238c7af3d7c9d822111996731726e38d /lib/rubygems | |
parent | a6afbaeb3be396c0fdea3b9077d9256c59edcfca (diff) |
Update to RubyGems 1.3.4 r2223
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@23659 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
67 files changed, 4854 insertions, 2685 deletions
@@ -4,81 +4,83 @@ # See LICENSE.txt for permissions. #++ -module Gem ## - # The Builder class processes RubyGem specification files - # to produce a .gem file. # - class Builder - - include UserInteraction - ## - # Constructs a builder instance for the provided specification - # - # spec:: [Gem::Specification] The specification instance - # - def initialize(spec) - require "yaml" - require "rubygems/package" - require "rubygems/security" - - @spec = spec - end - ## - # Builds the gem from the specification. Returns the name of the file - # written. - # - def build - @spec.mark_version - @spec.validate - @signer = sign - write_package - say success - @spec.file_name - end - def success - <<-EOM Successfully built RubyGem Name: #{@spec.name} Version: #{@spec.version} File: #{@spec.full_name+'.gem'} EOM - end - private - - def sign - # if the signing key was specified, then load the file, and swap - # to the public key (TODO: we should probably just omit the - # signing key in favor of the signing certificate, but that's for - # the future, also the signature algorithm should be configurable) - signer = nil - if @spec.respond_to?(:signing_key) && @spec.signing_key - signer = Gem::Security::Signer.new(@spec.signing_key, @spec.cert_chain) - @spec.signing_key = nil - @spec.cert_chain = signer.cert_chain.map { |cert| cert.to_s } - end - signer end - def write_package - open @spec.file_name, 'wb' do |gem_io| - Gem::Package.open gem_io, 'w', @signer do |pkg| - pkg.metadata = @spec.to_yaml - @spec.files.each do |file| - next if File.directory? file - stat = File.stat file - mode = stat.mode & 0777 - size = stat.size - pkg.add_file_simple file, mode, size do |tar_io| - tar_io.write open(file, "rb") { |f| f.read } - end end end end @@ -5,402 +5,507 @@ #++ require 'optparse' - require 'rubygems/user_interaction' -module Gem - # Base class for all Gem commands. When creating a new gem command, define - # #arguments, #defaults_str, #description and #usage (as appropriate). - class Command - include UserInteraction - # The name of the command. - attr_reader :command - # The options for the command. - attr_reader :options - # The default options for the command. - attr_accessor :defaults - # The name of the command for command-line invocation. - attr_accessor :program_name - # A short description of the command. - attr_accessor :summary - # Initializes a generic gem command named +command+. +summary+ is a short - # description displayed in `gem help commands`. +defaults+ are the - # default options. Defaults should be mirrored in #defaults_str, unless - # there are none. - # - # Use add_option to add command-line switches. - def initialize(command, summary=nil, defaults={}) - @command = command - @summary = summary - @program_name = "gem #{command}" - @defaults = defaults - @options = defaults.dup - @option_groups = Hash.new { |h,k| h[k] = [] } - @parser = nil - @when_invoked = nil - end - # True if +long+ begins with the characters from +short+. - def begins?(long, short) - return false if short.nil? - long[0, short.length] == short - end - # Override to provide command handling. - def execute - fail "Generic command has no actions" - end - # Get all gem names from the command line. - def get_all_gem_names - args = options[:args] - if args.nil? or args.empty? then - raise Gem::CommandLineError, - "Please specify at least one gem name (e.g. gem build GEMNAME)" - end - gem_names = args.select { |arg| arg !~ /^-/ } - end - # Get the single gem name from the command line. Fail if there is no gem - # name or if there is more than one gem name given. - def get_one_gem_name - args = options[:args] - if args.nil? or args.empty? then - raise Gem::CommandLineError, - "Please specify a gem name on the command line (e.g. gem build GEMNAME)" - end - if args.size > 1 then - raise Gem::CommandLineError, - "Too many gem names (#{args.join(', ')}); please specify only one" - end - args.first - end - # Get a single optional argument from the command line. If more than one - # argument is given, return only the first. Return nil if none are given. - def get_one_optional_argument - args = options[:args] || [] - args.first end - # Override to provide details of the arguments a command takes. - # It should return a left-justified string, one argument per line. - def arguments - "" - end - # Override to display the default values of the command - # options. (similar to +arguments+, but displays the default - # values). - def defaults_str - "" - end - # Override to display a longer description of what this command does. - def description - nil - end - # Override to display the usage for an individual gem command. - def usage - program_name - end - # Display the help message for the command. - def show_help - parser.program_name = usage - say parser - end - # Invoke the command with the given list of arguments. - def invoke(*args) - handle_options(args) - if options[:help] - show_help - elsif @when_invoked - @when_invoked.call(options) - else - execute - end end - - # Call the given block when invoked. - # - # Normal command invocations just executes the +execute+ method of - # the command. Specifying an invocation block allows the test - # methods to override the normal action of a command to determine - # that it has been invoked correctly. - def when_invoked(&block) - @when_invoked = block end - # Add a command-line option and handler to the command. - # - # See OptionParser#make_switch for an explanation of +opts+. - # - # +handler+ will be called with two values, the value of the argument and - # the options hash. - def add_option(*opts, &handler) # :yields: value, options - group_name = Symbol === opts.first ? opts.shift : :options - @option_groups[group_name] << [opts, handler] - end - # Remove previously defined command-line argument +name+. - def remove_option(name) - @option_groups.each do |_, option_list| - option_list.reject! { |args, _| args.any? { |x| x =~ /^#{name}/ } } - end - end - # Merge a set of command options with the set of default options - # (without modifying the default option hash). - def merge_options(new_options) - @options = @defaults.clone - new_options.each do |k,v| @options[k] = v end end - # True if the command handles the given argument list. - def handles?(args) - begin - parser.parse!(args.dup) - return true - rescue - return false - end end - # Handle the given list of arguments by parsing them and recording - # the results. - def handle_options(args) - args = add_extra_args(args) - @options = @defaults.clone - parser.parse!(args) - @options[:args] = args end - - def add_extra_args(args) - result = [] - s_extra = Command.specific_extra_args(@command) - extra = Command.extra_args + s_extra - while ! extra.empty? - ex = [] - ex << extra.shift - ex << extra.shift if extra.first.to_s =~ /^[^-]/ - result << ex if handles?(ex) - end - result.flatten! - result.concat(args) - result end - - private - - # Create on demand parser. - def parser - create_option_parser if @parser.nil? - @parser end - def create_option_parser - @parser = OptionParser.new - - @parser.separator("") - regular_options = @option_groups.delete :options - - configure_options "", regular_options - - @option_groups.sort_by { |n,_| n.to_s }.each do |group_name, option_list| - configure_options group_name, option_list - end - - configure_options "Common", Command.common_options - @parser.separator("") - unless arguments.empty? - @parser.separator(" Arguments:") - arguments.split(/\n/).each do |arg_desc| - @parser.separator(" #{arg_desc}") - end - @parser.separator("") - end - @parser.separator(" Summary:") - wrap(@summary, 80 - 4).split("\n").each do |line| - @parser.separator(" #{line.strip}") - end - if description then - formatted = description.split("\n\n").map do |chunk| - wrap(chunk, 80 - 4) - end.join("\n") - @parser.separator "" - @parser.separator " Description:" - formatted.split("\n").each do |line| - @parser.separator " #{line.rstrip}" - end - end - unless defaults_str.empty? - @parser.separator("") - @parser.separator(" Defaults:") - defaults_str.split(/\n/).each do |line| - @parser.separator(" #{line}") - end - end end - def configure_options(header, option_list) - return if option_list.nil? or option_list.empty? - header = header.to_s.empty? ? '' : "#{header} " - @parser.separator " #{header}Options:" - option_list.each do |args, handler| - dashes = args.select { |arg| arg =~ /^-/ } - @parser.on(*args) do |value| - handler.call(value, @options) - end - end - @parser.separator '' - end - # Wraps +text+ to +width+ - def wrap(text, width) - text.gsub(/(.{1,#{width}})( +|$\n?)|(.{1,#{width}})/, "\\1\\3\n") - end - - ################################################################## - # Class methods for Command. - class << self - def common_options - @common_options ||= [] - end - def add_common_option(*args, &handler) - Gem::Command.common_options << [args, handler] - end - def extra_args - @extra_args ||= [] - end - - def extra_args=(value) - case value - when Array - @extra_args = value - when String - @extra_args = value.split - end - end - # Return an array of extra arguments for the command. The extra - # arguments come from the gem configuration file read at program - # startup. - def specific_extra_args(cmd) - specific_extra_args_hash[cmd] - end - # Add a list of extra arguments for the given command. +args+ - # may be an array or a string to be split on white space. - def add_specific_extra_args(cmd,args) - args = args.split(/\s+/) if args.kind_of? String - specific_extra_args_hash[cmd] = args - end - # Accessor for the specific extra args hash (self initializing). - def specific_extra_args_hash - @specific_extra_args_hash ||= Hash.new do |h,k| - h[k] = Array.new - end end end - # ---------------------------------------------------------------- - # Add the options common to all commands. - - add_common_option('-h', '--help', - 'Get help on this command') do - |value, options| - options[:help] = true end - add_common_option('-V', '--[no-]verbose', - 'Set the verbose level of output') do |value, options| - # Set us to "really verbose" so the progress meter works - if Gem.configuration.verbose and value then - Gem.configuration.verbose = 1 - else - Gem.configuration.verbose = value end end - add_common_option('-q', '--quiet', 'Silence commands') do |value, options| - Gem.configuration.verbose = false end - # Backtrace and config-file are added so they show up in the help - # commands. Both options are actually handled before the other - # options get parsed. - add_common_option('--config-file FILE', - "Use this config file instead of default") do - end - add_common_option('--backtrace', - 'Show stack backtrace on errors') do end - add_common_option('--debug', - 'Turn on Ruby debugging') do - end - # :stopdoc: - HELP = %{ - RubyGems is a sophisticated package manager for Ruby. This is a - basic help message containing pointers to more information. - Usage: - gem -h/--help - gem -v/--version - gem command [arguments...] [options...] - Examples: - gem install rake - gem list --local - gem build package.gemspec - gem help install - Further help: - gem help commands list all 'gem' commands - gem help examples show some examples of usage - gem help platforms show information about platforms - gem help <COMMAND> show help on COMMAND - (e.g. 'gem help install') - Further information: - http://rubygems.rubyforge.org - }.gsub(/^ /, "") - # :startdoc: - end # class - # This is where Commands will be placed in the namespace - module Commands; end end @@ -8,139 +8,167 @@ require 'timeout' require 'rubygems/command' require 'rubygems/user_interaction' -module Gem - #################################################################### - # The command manager registers and installs all the individual - # sub-commands supported by the gem command. - class CommandManager - include UserInteraction - # Return the authoritative instance of the command manager. - def self.instance - @command_manager ||= CommandManager.new - end - # Register all the subcommands supported by the gem command. - def initialize - @commands = {} - register_command :build - register_command :cert - register_command :check - register_command :cleanup - register_command :contents - register_command :dependency - register_command :environment - register_command :fetch - register_command :generate_index - register_command :help - register_command :install - register_command :list - register_command :lock - register_command :mirror - register_command :outdated - register_command :pristine - register_command :query - register_command :rdoc - register_command :search - register_command :server - register_command :sources - register_command :specification - register_command :stale - register_command :uninstall - register_command :unpack - register_command :update - register_command :which - end - # Register the command object. - def register_command(command_obj) - @commands[command_obj] = false - end - # Return the registered command from the command name. - def [](command_name) - command_name = command_name.intern - return nil if @commands[command_name].nil? - @commands[command_name] ||= load_and_instantiate(command_name) - end - # Return a list of all command names (as strings). - def command_names - @commands.keys.collect {|key| key.to_s}.sort - end - # Run the config specified by +args+. - def run(args) - process_args(args) - rescue StandardError, Timeout::Error => ex - alert_error "While executing gem ... (#{ex.class})\n #{ex.to_s}" - ui.errs.puts "\t#{ex.backtrace.join "\n\t"}" if - Gem.configuration.backtrace terminate_interaction(1) - rescue Interrupt - alert_error "Interrupted" terminate_interaction(1) end - def process_args(args) - args = args.to_str.split(/\s+/) if args.respond_to?(:to_str) - if args.size == 0 - say Gem::Command::HELP - terminate_interaction(1) - end - case args[0] - when '-h', '--help' - say Gem::Command::HELP - terminate_interaction(0) - when '-v', '--version' - say Gem::RubyGemsVersion - terminate_interaction(0) - when /^-/ - alert_error "Invalid option: #{args[0]}. See 'gem --help'." - terminate_interaction(1) - else - cmd_name = args.shift.downcase - cmd = find_command(cmd_name) - cmd.invoke(*args) - end end - def find_command(cmd_name) - possibilities = find_command_possibilities(cmd_name) - if possibilities.size > 1 - raise "Ambiguous command #{cmd_name} matches [#{possibilities.join(', ')}]" - end - if possibilities.size < 1 - raise "Unknown command #{cmd_name}" - end - self[possibilities.first] - end - def find_command_possibilities(cmd_name) - len = cmd_name.length - self.command_names.select { |n| cmd_name == n[0,len] } - end - private - - def load_and_instantiate(command_name) - command_name = command_name.to_s - retried = false - - begin - const_name = command_name.capitalize.gsub(/_(.)/) { $1.upcase } - Gem::Commands.const_get("#{const_name}Command").new - rescue NameError - if retried then - raise - else - retried = true - require "rubygems/commands/#{command_name}_command" - retry - end end end end end @@ -21,6 +21,10 @@ class Gem::Commands::CheckCommand < Gem::Command options[:alien] = true end add_option('-t', '--test', "Run unit tests for gem") do |value, options| options[:test] = true end @@ -38,16 +42,17 @@ class Gem::Commands::CheckCommand < Gem::Command if options[:alien] say "Performing the 'alien' operation" - Gem::Validator.new.alien.each do |key, val| - if(val.size > 0) say "#{key} has #{val.size} problems" val.each do |error_entry| - say "\t#{error_entry.path}:" - say "\t#{error_entry.problem}" - say end else - say "#{key} is error-free" end say end @@ -1,6 +1,7 @@ require 'rubygems/command' require 'rubygems/source_index' require 'rubygems/dependency_list' class Gem::Commands::CleanupCommand < Gem::Command @@ -22,6 +23,13 @@ class Gem::Commands::CleanupCommand < Gem::Command "--no-dryrun" end def usage # :nodoc: "#{program_name} [GEMNAME ...]" end @@ -41,7 +49,8 @@ class Gem::Commands::CleanupCommand < Gem::Command unless options[:args].empty? then options[:args].each do |gem_name| - specs = Gem.cache.search(/^#{gem_name}$/i) specs.each do |spec| gems_to_cleanup << spec end @@ -56,7 +65,6 @@ class Gem::Commands::CleanupCommand < Gem::Command primary_gems[spec.name].version != spec.version } - uninstall_command = Gem::CommandManager.instance['uninstall'] deplist = Gem::DependencyList.new gems_to_cleanup.uniq.each do |spec| deplist.add spec end @@ -69,14 +77,21 @@ class Gem::Commands::CleanupCommand < Gem::Command say "Attempting to uninstall #{spec.full_name}" options[:args] = [spec.name] - options[:version] = "= #{spec.version}" - options[:executables] = false - uninstaller = Gem::Uninstaller.new spec.name, options begin uninstaller.uninstall - rescue Gem::DependencyRemovalException, Gem::GemNotInHomeException => e say "Unable to uninstall #{spec.full_name}:" say "\t#{e.class}: #{e.message}" @@ -11,6 +11,11 @@ class Gem::Commands::ContentsCommand < Gem::Command add_version_option add_option('-s', '--spec-dir a,b,c', Array, "Search for gems under specific paths") do |spec_dirs, options| options[:specdirs] = spec_dirs @@ -20,6 +25,11 @@ class Gem::Commands::ContentsCommand < Gem::Command "Only return files in the Gem's lib_dirs") do |lib_only, options| options[:lib_only] = lib_only end end def arguments # :nodoc: @@ -27,46 +37,60 @@ class Gem::Commands::ContentsCommand < Gem::Command end def defaults_str # :nodoc: - "--no-lib-only" end def usage # :nodoc: - "#{program_name} GEMNAME" end def execute version = options[:version] || Gem::Requirement.default - gem = get_one_gem_name - s = options[:specdirs].map do |i| [i, File.join(i, "specifications")] end.flatten - path_kind = if s.empty? then - s = Gem::SourceIndex.installed_spec_directories "default gem paths" else "specified path" end - si = Gem::SourceIndex.from_gems_in(*s) - gem_spec = si.find_name(gem, version).last - unless gem_spec then - say "Unable to find gem '#{gem}' in #{path_kind}" - if Gem.configuration.verbose then - say "\nDirectories searched:" - s.each { |dir| say dir } end - terminate_interaction - end - files = options[:lib_only] ? gem_spec.lib_files : gem_spec.files - files.each do |f| - say File.join(gem_spec.full_gem_path, f) end end @@ -1,55 +1,131 @@ require 'rubygems/command' require 'rubygems/indexer' class Gem::Commands::GenerateIndexCommand < Gem::Command def initialize super 'generate_index', 'Generates the index files for a gem server directory', - :directory => '.' add_option '-d', '--directory=DIRNAME', 'repository base dir containing gems subdir' do |dir, options| options[:directory] = File.expand_path dir end end def defaults_str # :nodoc: - "--directory ." end def description # :nodoc: <<-EOF The generate_index command creates a set of indexes for serving gems statically. The command expects a 'gems' directory under the path given to -the --directory option. When done, it will generate a set of files like this: - gems/ # .gem files you want to index quick/index quick/index.rz # quick index manifest - quick/<gemname>.gemspec.rz # legacy YAML quick index file - quick/Marshal.<version>/<gemname>.gemspec.rz # Marshal quick index file Marshal.<version> - Marshal.<version>.Z # Marshal full index yaml - yaml.Z # legacy YAML full index -The .Z and .rz extension files are compressed with the inflate algorithm. The -Marshal version number comes from ruby's Marshal::MAJOR_VERSION and -Marshal::MINOR_VERSION constants. It is used to ensure compatibility. The -yaml indexes exist for legacy RubyGems clients and fallback in case of Marshal -version changes. EOF end def execute if not File.exist?(options[:directory]) or not File.directory?(options[:directory]) then alert_error "unknown directory name #{directory}." terminate_interaction 1 else - indexer = Gem::Indexer.new options[:directory] - indexer.generate_index end end @@ -6,6 +6,11 @@ require 'rubygems/local_remote_options' require 'rubygems/validator' require 'rubygems/version_option' class Gem::Commands::InstallCommand < Gem::Command include Gem::VersionOption @@ -14,11 +19,11 @@ class Gem::Commands::InstallCommand < Gem::Command def initialize defaults = Gem::DependencyInstaller::DEFAULT_OPTIONS.merge({ - :generate_rdoc => true, - :generate_ri => true, :format_executable => false, - :test => false, - :version => Gem::Requirement.default, }) super 'install', 'Install a gem into the local repository', defaults @@ -43,11 +48,51 @@ class Gem::Commands::InstallCommand < Gem::Command The install command installs local or remote gem into a gem repository. For gems with executables ruby installs a wrapper file into the executable -directory by deault. This can be overridden with the --no-wrappers option. The wrapper allows you to choose among alternate gem versions using _version_. For example `rake _0.7.3_ --version` will run rake version 0.7.3 if a newer version is also installed. EOF end @@ -65,24 +110,11 @@ version is also installed. ENV.delete 'GEM_PATH' if options[:install_dir].nil? and RUBY_VERSION > '1.9' - install_options = { - :env_shebang => options[:env_shebang], - :domain => options[:domain], - :force => options[:force], - :format_executable => options[:format_executable], - :ignore_dependencies => options[:ignore_dependencies], - :install_dir => options[:install_dir], - :security_policy => options[:security_policy], - :wrappers => options[:wrappers], - :bin_dir => options[:bin_dir], - :development => options[:development], - } - exit_code = 0 get_all_gem_names.each do |gem_name| begin - inst = Gem::DependencyInstaller.new install_options inst.install gem_name, options[:version] inst.installed_gems.each do |spec| @@ -96,46 +128,40 @@ version is also installed. rescue Gem::GemNotFoundException => e alert_error e.message exit_code |= 2 -# rescue => e -# # TODO: Fix this handle to allow the error to propagate to -# # the top level handler. Examine the other errors as -# # well. This implementation here looks suspicious to me -- -# # JimWeirich (4/Jan/05) -# alert_error "Error installing gem #{gem_name}: #{e.message}" -# return end end unless installed_gems.empty? then gems = installed_gems.length == 1 ? 'gem' : 'gems' say "#{installed_gems.length} #{gems} installed" - end - # NOTE: *All* of the RI documents must be generated first. - # For some reason, RI docs cannot be generated after any RDoc - # documents are generated. - if options[:generate_ri] then - installed_gems.each do |gem| - Gem::DocManager.new(gem, options[:rdoc_args]).generate_ri - end - Gem::DocManager.update_ri_cache - end - if options[:generate_rdoc] then - installed_gems.each do |gem| - Gem::DocManager.new(gem, options[:rdoc_args]).generate_rdoc end - end - if options[:test] then - installed_gems.each do |spec| - gem_spec = Gem::SourceIndex.from_installed_gems.search(spec.name, spec.version.version).first - result = Gem::Validator.new.unit_test(gem_spec) - if result and not result.passed? - unless ask_yes_no("...keep Gem?", true) then - Gem::Uninstaller.new(spec.name, :version => spec.version.version).uninstall end end end @@ -2,9 +2,11 @@ require 'rubygems/command' require 'rubygems/local_remote_options' require 'rubygems/spec_fetcher' require 'rubygems/version_option' class Gem::Commands::QueryCommand < Gem::Command include Gem::LocalRemoteOptions include Gem::VersionOption @@ -43,6 +45,11 @@ class Gem::Commands::QueryCommand < Gem::Command options[:all] = value end add_local_remote_options end @@ -54,6 +61,7 @@ class Gem::Commands::QueryCommand < Gem::Command exit_code = 0 name = options[:name] if options[:installed] then if name.source.empty? then @@ -72,6 +80,10 @@ class Gem::Commands::QueryCommand < Gem::Command dep = Gem::Dependency.new name, Gem::Requirement.default if local? then if ui.outs.tty? or both? then say say "*** LOCAL GEMS ***" @@ -98,8 +110,13 @@ class Gem::Commands::QueryCommand < Gem::Command begin fetcher = Gem::SpecFetcher.fetcher - spec_tuples = fetcher.find_matching dep, all, false rescue Gem::RemoteFetcher::FetchError => e raise unless fetcher.warn_legacy e do require 'rubygems/source_info_cache' @@ -145,6 +162,12 @@ class Gem::Commands::QueryCommand < Gem::Command version end.reverse seen = {} matching_tuples.delete_if do |(name, version,_),_| @@ -174,6 +197,28 @@ class Gem::Commands::QueryCommand < Gem::Command end entry << "\n" authors = "Author#{spec.authors.length > 1 ? 's' : ''}: " authors << spec.authors.join(', ') entry << format_text(authors, 68, 4) @@ -187,6 +232,12 @@ class Gem::Commands::QueryCommand < Gem::Command entry << "\n" << format_text("Homepage: #{spec.homepage}", 68, 4) end if spec.loaded_from then if matching_tuples.length == 1 then loaded_from = File.dirname File.dirname(spec.loaded_from) @@ -209,25 +260,5 @@ class Gem::Commands::QueryCommand < Gem::Command say output.join(options[:details] ? "\n\n" : "\n") end - ## - # Used for wrapping and indenting text - - def format_text(text, wrap, indent=0) - result = [] - work = text.dup - - while work.length > wrap - if work =~ /^(.{0,#{wrap}})[ \n]/o then - result << $1 - work.slice!(0, $&.length) - else - result << work.slice!(0, wrap) - end - end - - result << work if work.length.nonzero? - result.join("\n").gsub(/^/, " " * indent) - end - end @@ -2,81 +2,75 @@ require 'rubygems/command' require 'rubygems/version_option' require 'rubygems/doc_manager' -module Gem - module Commands - class RdocCommand < Command - include VersionOption - - def initialize - super('rdoc', - 'Generates RDoc for pre-installed gems', - { - :version => Gem::Requirement.default, - :include_rdoc => true, - :include_ri => true, - }) - add_option('--all', - 'Generate RDoc/RI documentation for all', - 'installed gems') do |value, options| - options[:all] = value - end - add_option('--[no-]rdoc', - 'Include RDoc generated documents') do - |value, options| - options[:include_rdoc] = value - end - add_option('--[no-]ri', - 'Include RI generated documents' - ) do |value, options| - options[:include_ri] = value - end - add_version_option - end - def arguments # :nodoc: - "GEMNAME gem to generate documentation for (unless --all)" - end - def defaults_str # :nodoc: - "--version '#{Gem::Requirement.default}' --rdoc --ri" - end - def usage # :nodoc: - "#{program_name} [args]" end - def execute - if options[:all] - specs = Gem::SourceIndex.from_installed_gems.collect { |name, spec| - spec - } - else - gem_name = get_one_gem_name - specs = Gem::SourceIndex.from_installed_gems.search( - gem_name, options[:version]) - end - - if specs.empty? - fail "Failed to find gem #{gem_name} to generate RDoc for #{options[:version]}" - end - - if options[:include_ri] - specs.each do |spec| - Gem::DocManager.new(spec).generate_ri - end - - Gem::DocManager.update_ri_cache - end - - if options[:include_rdoc] - specs.each do |spec| - Gem::DocManager.new(spec).generate_rdoc - end - end - - true end end end end @@ -1,37 +1,31 @@ require 'rubygems/command' require 'rubygems/commands/query_command' -module Gem - module Commands - - class SearchCommand < QueryCommand - - def initialize - super( - 'search', - 'Display all gems whose name contains STRING' - ) - remove_option('--name-matches') - end - - def arguments # :nodoc: - "STRING fragment of gem name to search for" - end - - def defaults_str # :nodoc: - "--local --no-details" - end - - def usage # :nodoc: - "#{program_name} [STRING]" - end - - def execute - string = get_one_optional_argument - options[:name] = /#{string}/i - super - end - end end end @@ -7,7 +7,23 @@ class Gem::Commands::ServerCommand < Gem::Command super 'server', 'Documentation and gem repository HTTP server', :port => 8808, :gemdir => Gem.dir, :daemon => false - add_option '-p', '--port=PORT', Integer, 'port to listen on' do |port, options| options[:port] = port end @@ -37,6 +53,12 @@ for gem installation. To install gems from a running server, use `gem install GEMNAME --source http://gem_server_host:8808` EOF end @@ -0,0 +1,353 @@ @@ -3,9 +3,12 @@ require 'rubygems/command' require 'rubygems/remote_fetcher' require 'rubygems/source_info_cache' require 'rubygems/spec_fetcher' class Gem::Commands::SourcesCommand < Gem::Command def initialize super 'sources', 'Manage the sources and cache file RubyGems uses to search for gems' @@ -30,6 +33,8 @@ class Gem::Commands::SourcesCommand < Gem::Command add_option '-u', '--update', 'Update source cache' do |value, options| options[:update] = value end end def defaults_str @@ -12,7 +12,8 @@ class Gem::Commands::SpecificationCommand < Gem::Command def initialize super 'specification', 'Display gem specification (in yaml)', - :domain => :local, :version => Gem::Requirement.default add_version_option('examine') add_platform_option @@ -22,26 +23,62 @@ class Gem::Commands::SpecificationCommand < Gem::Command options[:all] = true end add_local_remote_options end def arguments # :nodoc: - "GEMFILE name of gem to show the gemspec for" end def defaults_str # :nodoc: - "--local --version '#{Gem::Requirement.default}'" end def usage # :nodoc: - "#{program_name} [GEMFILE]" end def execute specs = [] - gem = get_one_gem_name dep = Gem::Dependency.new gem, options[:version] if local? then if File.exist? gem then specs << Gem::Format.from_file_by_path(gem).spec rescue nil @@ -63,7 +100,17 @@ class Gem::Commands::SpecificationCommand < Gem::Command terminate_interaction 1 end - output = lambda { |s| say s.to_yaml; say "\n" } if options[:all] then specs.each(&output) @@ -2,72 +2,82 @@ require 'rubygems/command' require 'rubygems/version_option' require 'rubygems/uninstaller' -module Gem - module Commands - class UninstallCommand < Command - - include VersionOption - - def initialize - super 'uninstall', 'Uninstall gems from the local repository', - :version => Gem::Requirement.default - - add_option('-a', '--[no-]all', - 'Uninstall all matching versions' - ) do |value, options| - options[:all] = value - end - - add_option('-I', '--[no-]ignore-dependencies', - 'Ignore dependency requirements while', - 'uninstalling') do |value, options| - options[:ignore] = value - end - - add_option('-x', '--[no-]executables', - 'Uninstall applicable executables without', - 'confirmation') do |value, options| - options[:executables] = value - end - - add_option('-i', '--install-dir DIR', - 'Directory to uninstall gem from') do |value, options| - options[:install_dir] = File.expand_path(value) - end - - add_option('-n', '--bindir DIR', - 'Directory to remove binaries from') do |value, options| - options[:bin_dir] = File.expand_path(value) - end - - add_version_option - add_platform_option - end - def arguments # :nodoc: - "GEMNAME name of gem to uninstall" - end - def defaults_str # :nodoc: - "--version '#{Gem::Requirement.default}' --no-force " \ - "--install-dir #{Gem.dir}" - end - def usage # :nodoc: - "#{program_name} GEMNAME [GEMNAME ...]" - end - def execute - get_all_gem_names.each do |gem_name| - begin - Gem::Uninstaller.new(gem_name, options).uninstall - rescue Gem::GemNotInHomeException => e - spec = e.spec - alert("In order to remove #{spec.name}, please execute:\n" \ - "\tgem uninstall #{spec.name} --install-dir=#{spec.installation_path}") - end - end end end end end @@ -12,7 +12,7 @@ class Gem::Commands::UnpackCommand < Gem::Command :version => Gem::Requirement.default, :target => Dir.pwd - add_option('--target', 'target directory for unpacking') do |value, options| options[:target] = value end @@ -35,18 +35,20 @@ class Gem::Commands::UnpackCommand < Gem::Command # TODO: allow, e.g., 'gem unpack rake-0.3.1'. Find a general solution for # this, so that it works for uninstall as well. (And check other commands # at the same time.) def execute - gemname = get_one_gem_name - path = get_path(gemname, options[:version]) - - if path then - basename = File.basename(path).sub(/\.gem$/, '') - target_dir = File.expand_path File.join(options[:target], basename) - FileUtils.mkdir_p target_dir - Gem::Installer.new(path, :unpack => true).unpack target_dir - say "Unpacked gem: '#{target_dir}'" - else - alert_error "Gem '#{gemname}' not installed." end end @@ -16,9 +16,9 @@ class Gem::Commands::UpdateCommand < Gem::Command super 'update', 'Update the named gems (or all installed gems) in the local repository', :generate_rdoc => true, - :generate_ri => true, - :force => false, - :test => false add_install_update_options @@ -80,20 +80,27 @@ class Gem::Commands::UpdateCommand < Gem::Command gems_to_update.uniq.sort.each do |name| next if updated.any? { |spec| spec.name == name } say "Updating #{name}" - installer.install name installer.installed_gems.each do |spec| updated << spec - say "Successfully installed #{spec.full_name}" end end if gems_to_update.include? "rubygems-update" then Gem.source_index.refresh! - update_gems = Gem.source_index.search 'rubygems-update' latest_update_gem = update_gems.sort_by { |s| s.version }.last @@ -106,6 +113,20 @@ class Gem::Commands::UpdateCommand < Gem::Command say "Nothing to update" else say "Gems updated: #{updated.map { |spec| spec.name }.join ', '}" end end end @@ -46,7 +46,7 @@ class Gem::Commands::WhichCommand < Gem::Command end say "(checking gem #{spec.full_name} for #{arg})" if - Gem.configuration.verbose end paths = find_paths arg, dirs @@ -5,7 +5,6 @@ #++ require 'yaml' -require 'rubygems' # Store the gem command options specified in the configuration file. The # config file object acts much like a hash. @@ -36,7 +35,8 @@ class Gem::ConfigFile CSIDL_COMMON_APPDATA = 0x0023 path = 0.chr * 260 - SHGetFolderPath = Win32API.new 'shell32', 'SHGetFolderPath', 'PLPLP', 'L', :stdcall SHGetFolderPath.call nil, CSIDL_COMMON_APPDATA, nil, 1, path path.strip @@ -20,8 +20,13 @@ module Gem if defined? RUBY_FRAMEWORK_VERSION then File.join File.dirname(ConfigMap[:sitedir]), 'Gems', ConfigMap[:ruby_version] else - ConfigMap[:sitelibdir].sub(%r'/site_ruby/(?=[^/]+)', '/gems/') end end @@ -37,15 +42,25 @@ module Gem # Default gem load path def self.default_path - [user_dir, default_dir] end ## # Deduce Ruby's --program-prefix and --program-suffix from its install name def self.default_exec_format - baseruby = ConfigMap[:BASERUBY] || 'ruby' - ConfigMap[:RUBY_INSTALL_NAME].sub(baseruby, '%s') rescue '%s' end ## @@ -4,8 +4,6 @@ # See LICENSE.txt for permissions. #++ -require 'rubygems' - ## # The Dependency class holds a Gem name and a Gem::Requirement @@ -72,7 +70,7 @@ class Gem::Dependency alias requirements_list requirement_list def normalize - ver = @version_requirement.instance_eval { @version } @version_requirements = Gem::Requirement.new([ver]) @version_requirement = nil end @@ -81,6 +79,21 @@ class Gem::Dependency "#{name} (#{version_requirements}, #{@type || :runtime})" end def ==(other) # :nodoc: self.class === other && self.name == other.name && @@ -89,15 +102,22 @@ class Gem::Dependency end ## - # Uses this dependency as a pattern to compare to the dependency +other+. - # This dependency will match if the name matches the other's name, and other - # has only an equal version requirement that satisfies this dependency. def =~(other) - return false unless self.class === other pattern = @name - pattern = /\A#{@name}\Z/ unless Regexp === pattern return false unless pattern =~ other.name @@ -111,9 +131,18 @@ class Gem::Dependency version_requirements.satisfied_by? version end - def hash # :nodoc: name.hash + type.hash + version_requirements.hash end end @@ -20,8 +20,9 @@ class Gem::DependencyInstaller :force => false, :format_executable => false, # HACK dup :ignore_dependencies => false, :security_policy => nil, # HACK NoSecurity requires OpenSSL. AlmostNo? Low? - :wrappers => true } ## @@ -37,6 +38,7 @@ class Gem::DependencyInstaller # :format_executable:: See Gem::Installer#initialize. # :ignore_dependencies:: Don't install any dependencies. # :install_dir:: See Gem::Installer#install. # :security_policy:: See Gem::Installer::new and Gem::Security. # :user_install:: See Gem::Installer.new # :wrappers:: See Gem::Installer::new @@ -58,6 +60,7 @@ class Gem::DependencyInstaller @force = options[:force] @format_executable = options[:format_executable] @ignore_dependencies = options[:ignore_dependencies] @security_policy = options[:security_policy] @user_install = options[:user_install] @wrappers = options[:wrappers] @@ -90,10 +93,10 @@ class Gem::DependencyInstaller req end - all = requirements.length > 1 || - (requirements.first != ">=" and requirements.first != ">") - found = Gem::SpecFetcher.fetcher.fetch dep, all gems_and_sources.push(*found) rescue Gem::RemoteFetcher::FetchError => e @@ -8,6 +8,7 @@ require 'tsort' class Gem::DependencyList include TSort def self.from_source_index(src_index) @@ -24,24 +25,27 @@ class Gem::DependencyList @specs = [] end # Adds +gemspecs+ to the dependency list. def add(*gemspecs) @specs.push(*gemspecs) end - # Return a list of the specifications in the dependency list, - # sorted in order so that no spec in the list depends on a gem - # earlier in the list. # - # This is useful when removing gems from a set of installed gems. - # By removing them in the returned order, you don't get into as - # many dependency issues. # - # If there are circular dependencies (yuck!), then gems will be - # returned in order until only the circular dependents and anything - # they reference are left. Then arbitrary gemspecs will be returned - # until the circular dependency is broken, after which gems will be - # returned in dependency order again. def dependency_order sorted = strongly_connected_components.flatten @@ -62,11 +66,20 @@ class Gem::DependencyList result.reverse end def find_name(full_name) @specs.find { |spec| spec.full_name == full_name } end # Are all the dependencies in the list satisfied? def ok? @specs.all? do |spec| spec.runtime_dependencies.all? do |dep| @@ -75,10 +88,12 @@ class Gem::DependencyList end end # Is is ok to remove a gem from the dependency list? # - # If removing the gemspec creates breaks a currently ok dependency, - # then it is NOT ok to remove the gem. def ok_to_remove?(full_name) gem_to_remove = find_name full_name @@ -106,9 +121,10 @@ class Gem::DependencyList @specs.delete_if { |spec| spec.full_name == full_name } end - # Return a hash of predecessors. <tt>result[spec]</tt> is an - # Array of gemspecs that have a dependency satisfied by the named - # spec. def spec_predecessors result = Hash.new { |h,k| h[k] = [] } @@ -151,13 +167,17 @@ class Gem::DependencyList private # Count the number of gemspecs in the list +specs+ that are not in # +ignored+. def active_count(specs, ignored) result = 0 specs.each do |spec| result += 1 unless ignored[spec.full_name] end result end @@ -41,12 +41,23 @@ class Gem::DocManager begin require 'rdoc/rdoc' rescue LoadError => e raise Gem::DocumentError, - "ERROR: RDoc documentation generator not installed!" end end ## # Updates the RI cache for RDoc 2 if it is installed @@ -94,10 +105,8 @@ class Gem::DocManager # RI docs generation to fail if run after RDoc). def generate_ri - if @spec.has_rdoc then - setup_rdoc - install_ri # RDoc bug, ri goes first - end FileUtils.mkdir_p @doc_dir unless File.exist?(@doc_dir) end @@ -110,10 +119,8 @@ class Gem::DocManager # RI docs generation to fail if run after RDoc). def generate_rdoc - if @spec.has_rdoc then - setup_rdoc - install_rdoc - end FileUtils.mkdir_p @doc_dir unless File.exist?(@doc_dir) end @@ -151,8 +158,17 @@ class Gem::DocManager args << '--quiet' args << @spec.require_paths.clone args << @spec.extra_rdoc_files args = args.flatten.map do |arg| arg.to_s end r = RDoc::RDoc.new old_pwd = Dir.pwd @@ -194,20 +210,20 @@ class Gem::DocManager original_name = [ @spec.name, @spec.version, @spec.original_platform].join '-' - doc_dir = File.join @spec.installation_path, 'doc', @spec.full_name - unless File.directory? doc_dir then - doc_dir = File.join @spec.installation_path, 'doc', original_name - end - FileUtils.rm_rf doc_dir - ri_dir = File.join @spec.installation_path, 'ri', @spec.full_name - unless File.directory? ri_dir then - ri_dir = File.join @spec.installation_path, 'ri', original_name - end - FileUtils.rm_rf ri_dir end end @@ -1,5 +1,3 @@ -require 'rubygems' - ## # Base exception class for RubyGems. All exception raised by RubyGems are a # subclass of this one. @@ -4,8 +4,6 @@ # See LICENSE.txt for permissions. #++ -require 'rubygems/ext' - class Gem::Ext::Builder def self.class_name @@ -15,7 +13,7 @@ class Gem::Ext::Builder def self.make(dest_path, results) unless File.exist? 'Makefile' then - raise Gem::InstallError, "Makefile not found:\n\n#{results.join "\n"}" end mf = File.read('Makefile') @@ -11,6 +11,7 @@ class Gem::Ext::ConfigureBuilder < Gem::Ext::Builder def self.build(extension, directory, dest_path, results) unless File.exist?('Makefile') then cmd = "sh ./configure --prefix=#{dest_path}" run cmd, results end @@ -5,12 +5,13 @@ #++ require 'rubygems/ext/builder' class Gem::Ext::ExtConfBuilder < Gem::Ext::Builder def self.build(extension, directory, dest_path, results) cmd = "#{Gem.ruby} #{File.basename extension}" - cmd << " #{ARGV.join ' '}" unless ARGV.empty? run cmd, results @@ -5,17 +5,21 @@ #++ require 'rubygems/ext/builder' class Gem::Ext::RakeBuilder < Gem::Ext::Builder def self.build(extension, directory, dest_path, results) if File.basename(extension) =~ /mkrf_conf/i then cmd = "#{Gem.ruby} #{File.basename extension}" - cmd << " #{ARGV.join " "}" unless ARGV.empty? run cmd, results end - cmd = ENV['rake'] || 'rake' cmd += " RUBYARCHDIR=#{dest_path} RUBYLIBDIR=#{dest_path}" # ENV is frozen run cmd, results @@ -8,80 +8,80 @@ require 'fileutils' require 'rubygems/package' -module Gem ## - # The format class knows the guts of the RubyGem .gem file format - # and provides the capability to read gem files # - class Format - attr_accessor :spec, :file_entries, :gem_path - extend Gem::UserInteraction - - ## - # Constructs an instance of a Format object, representing the gem's - # data structure. - # - # gem:: [String] The file name of the gem - # - def initialize(gem_path) - @gem_path = gem_path end - ## - # Reads the named gem file and returns a Format object, representing - # the data from the gem file - # - # file_path:: [String] Path to the gem file - # - def self.from_file_by_path(file_path, security_policy = nil) - format = nil - - unless File.exist?(file_path) - raise Gem::Exception, "Cannot load gem at [#{file_path}] in #{Dir.pwd}" end - # check for old version gem - if File.read(file_path, 20).include?("MD5SUM =") - require 'rubygems/old_format' - format = OldFormat.from_file_by_path(file_path) - else - open file_path, Gem.binary_mode do |io| - format = from_io io, file_path, security_policy - end - end - return format - end - ## - # Reads a gem from an io stream and returns a Format object, representing - # the data from the gem file - # - # io:: [IO] Stream from which to read the gem - # - def self.from_io(io, gem_path="(io)", security_policy = nil) - format = new gem_path - - Package.open io, 'r', security_policy do |pkg| - format.spec = pkg.metadata - format.file_entries = [] - - pkg.each do |entry| - size = entry.header.size - mode = entry.header.mode - - format.file_entries << [{ - "size" => size, "mode" => mode, "path" => entry.full_name, - }, - entry.read - ] - end - end - format end end end @@ -4,23 +4,30 @@ # See LICENSE.txt for permissions. #++ # Some system might not have OpenSSL installed, therefore the core # library file openssl might not be available. We localize testing # for the presence of OpenSSL in this file. module Gem class << self # Is SSL (used by the signing commands) available on this # platform? def ssl_available? - require 'rubygems/gem_openssl' @ssl_available end - # Set the value of the ssl_available flag. attr_writer :ssl_available # Ensure that SSL is available. Throw an exception if it is not. def ensure_ssl_available unless ssl_available? fail Gem::Exception, "SSL is not installed on this system" @@ -61,6 +68,8 @@ rescue LoadError, StandardError Gem.ssl_available = false end module Gem::SSL # We make our own versions of the constants here. This allows us @@ -70,7 +79,7 @@ module Gem::SSL # These constants are only used during load time. At runtime, any # method that makes a direct reference to SSL software must be # protected with a Gem.ensure_ssl_available call. - # if Gem.ssl_available? then PKEY_RSA = OpenSSL::PKey::RSA DIGEST_SHA1 = OpenSSL::Digest::SHA1 @@ -81,3 +90,5 @@ module Gem::SSL end @@ -4,8 +4,6 @@ # See LICENSE.txt for permissions. #++ -require 'rubygems' - ## # GemPathSearcher has the capability to find loadable files inside # gems. It generates data up front to speed up searches later. @@ -80,11 +78,15 @@ class Gem::GemPathSearcher ## # Return a list of all installed gemspecs, sorted by alphabetical order and - # in reverse version order. def init_gemspecs - Gem.source_index.map { |_, spec| spec }.sort { |a,b| - (a.name <=> b.name).nonzero? || (b.version <=> a.version) } end @@ -8,51 +8,71 @@ require 'rubygems/command_manager' require 'rubygems/config_file' require 'rubygems/doc_manager' -module Gem - #################################################################### - # Run an instance of the gem program. - # - class GemRunner - def initialize(options={}) - @command_manager_class = options[:command_manager] || Gem::CommandManager - @config_file_class = options[:config_file] || Gem::ConfigFile - @doc_manager_class = options[:doc_manager] || Gem::DocManager end - # Run the gem command with the following arguments. - def run(args) - start_time = Time.now - do_configuration(args) - cmd = @command_manager_class.instance - cmd.command_names.each do |command_name| - config_args = Gem.configuration[command_name] - config_args = case config_args - when String - config_args.split ' ' - else - Array(config_args) - end - Command.add_specific_extra_args command_name, config_args - end - cmd.run(Gem.configuration.args) - end_time = Time.now - if Gem.configuration.benchmark - printf "\nExecution time: %0.2f seconds.\n", end_time-start_time - puts "Press Enter to finish" - STDIN.gets - end end - private - def do_configuration(args) - Gem.configuration = @config_file_class.new(args) - Gem.use_paths(Gem.configuration[:gemhome], Gem.configuration[:gempath]) - Gem::Command.extra_args = Gem.configuration[:gem] - @doc_manager_class.configured_args = Gem.configuration[:rdoc] end - end # class -end # module @@ -6,6 +6,7 @@ require 'rubygems' require 'rubygems/format' begin require 'builder/xchar' rescue LoadError end @@ -18,11 +19,36 @@ class Gem::Indexer include Gem::UserInteraction ## # Index install location attr_reader :dest_directory ## # Index build directory attr_reader :directory @@ -30,12 +56,21 @@ class Gem::Indexer ## # Create an indexer that will index the gems in +directory+. - def initialize(directory) unless ''.respond_to? :to_xs then fail "Gem::Indexer requires that the XML Builder library be installed:" \ "\n\tgem install builder" end @dest_directory = directory @directory = File.join Dir.tmpdir, "gem_generate_index_#{$$}" @@ -54,22 +89,19 @@ class Gem::Indexer @specs_index = File.join @directory, "specs.#{Gem.marshal_version}" @latest_specs_index = File.join @directory, "latest_specs.#{Gem.marshal_version}" - files = [ - @specs_index, - "#{@specs_index}.gz", - @latest_specs_index, - "#{@latest_specs_index}.gz", - @quick_dir, - @master_index, - "#{@master_index}.Z", - @marshal_index, - "#{@marshal_index}.Z", - ] - - @files = files.map do |path| - path.sub @directory, '' - end end ## @@ -91,159 +123,367 @@ class Gem::Indexer # Build various indicies def build_indicies(index) progress = ui.progress_reporter index.size, - "Generating quick index gemspecs for #{index.size} gems", "Complete" - index.each do |original_name, spec| - spec_file_name = "#{original_name}.gemspec.rz" - yaml_name = File.join @quick_dir, spec_file_name - marshal_name = File.join @quick_marshal_dir, spec_file_name - yaml_zipped = Gem.deflate spec.to_yaml - open yaml_name, 'wb' do |io| io.write yaml_zipped end - marshal_zipped = Gem.deflate Marshal.dump(spec) - open marshal_name, 'wb' do |io| io.write marshal_zipped end - progress.updated original_name end - progress.done - - say "Generating specs index" - open @specs_index, 'wb' do |io| - specs = index.sort.map do |_, spec| - platform = spec.original_platform - platform = Gem::Platform::RUBY if platform.nil? or platform.empty? - [spec.name, spec.version, platform] end - - specs = compact_specs specs - - Marshal.dump specs, io end - say "Generating latest specs index" - open @latest_specs_index, 'wb' do |io| - specs = index.latest_specs.sort.map do |spec| - platform = spec.original_platform - platform = Gem::Platform::RUBY if platform.nil? or platform.empty? - [spec.name, spec.version, platform] end - specs = compact_specs specs - Marshal.dump specs, io end - say "Generating quick index" - quick_index = File.join @quick_dir, 'index' - open quick_index, 'wb' do |io| - io.puts index.sort.map { |_, spec| spec.original_name } - end - say "Generating latest index" - latest_index = File.join @quick_dir, 'latest_index' - open latest_index, 'wb' do |io| - io.puts index.latest_specs.sort.map { |spec| spec.original_name } end - say "Generating Marshal master index" - open @marshal_index, 'wb' do |io| - io.write index.dump - end progress = ui.progress_reporter index.size, - "Generating YAML master index for #{index.size} gems (this may take a while)", "Complete" - open @master_index, 'wb' do |io| - io.puts "--- !ruby/object:#{index.class}" - io.puts "gems:" - gems = index.sort_by { |name, gemspec| gemspec.sort_obj } - gems.each do |original_name, gemspec| - yaml = gemspec.to_yaml.gsub(/^/, ' ') - yaml = yaml.sub(/\A ---/, '') # there's a needed extra ' ' here - io.print " #{original_name}:" - io.puts yaml progress.updated original_name end end - progress.done - say "Compressing indicies" - # use gzip for future files. - compress quick_index, 'rz' - paranoid quick_index, 'rz' - compress latest_index, 'rz' - paranoid latest_index, 'rz' - compress @marshal_index, 'Z' - paranoid @marshal_index, 'Z' - compress @master_index, 'Z' - paranoid @master_index, 'Z' - gzip @specs_index - gzip @latest_specs_index end ## # Collect specifications from .gem files from the gem directory. - def collect_specs index = Gem::SourceIndex.new - progress = ui.progress_reporter gem_file_list.size, - "Loading #{gem_file_list.size} gems from #{@dest_directory}", "Loaded all gems" - gem_file_list.each do |gemfile| - if File.size(gemfile.to_s) == 0 then - alert_warning "Skipping zero-length gem: #{gemfile}" - next - end - - begin - spec = Gem::Format.from_file_by_path(gemfile).spec - - unless gemfile =~ /\/#{Regexp.escape spec.original_name}.*\.gem\z/i then - alert_warning "Skipping misnamed gem: #{gemfile} => #{spec.full_name} (#{spec.original_name})" next end - abbreviate spec - sanitize spec - index.gems[spec.original_name] = spec - progress.updated spec.original_name - rescue SignalException => e - alert_error "Received signal, exiting" - raise - rescue Exception => e - alert_error "Unable to process #{gemfile}\n#{e.message} (#{e.class})\n\t#{e.backtrace.join "\n\t"}" end - end - progress.done index end ## # Compacts Marshal output for the specs index data source by using identical # objects as much as possible. @@ -282,7 +522,7 @@ class Gem::Indexer end ## - # Builds and installs indexicies. def generate_index make_temp_directories @@ -311,7 +551,27 @@ class Gem::Indexer say "Moving index into production dir #{@dest_directory}" if verbose - @files.each do |file| src_name = File.join @directory, file dst_name = File.join @dest_directory, file @@ -366,5 +626,87 @@ class Gem::Indexer string ? string.to_s.to_xs : string end end @@ -9,9 +9,12 @@ require 'rubygems/security' ## # Mixin methods for install and update options for Gem::Commands module Gem::InstallUpdateOptions # Add the install/update options to the option parser. def add_install_update_options OptionParser.accept Gem::Security::Policy do |value| value = Gem::Security::Policies[value] @@ -92,7 +95,7 @@ module Gem::InstallUpdateOptions add_option(:"Install/Update", '--[no-]user-install', 'Install in user\'s home directory instead', - 'of GEM_HOME. Defaults to using home directory', 'only if GEM_HOME is not writable.') do |value, options| options[:user_install] = value end @@ -102,9 +105,18 @@ module Gem::InstallUpdateOptions "dependencies") do |value, options| options[:development] = true end end # Default options for the gem install command. def install_update_defaults_str '--rdoc --no-force --no-test --wrappers' end @@ -13,17 +13,28 @@ require 'rubygems/ext' require 'rubygems/require_paths_builder' ## -# The installer class processes RubyGem .gem files and installs the -# files contained in the .gem into the Gem.path. # # Gem::Installer does the work of putting files in all the right places on the # filesystem including unpacking the gem into its gem dir, installing the # gemspec in the specifications dir, storing the cached gem in the cache dir, # and installing either wrappers or symlinks for executables. class Gem::Installer ## # Raised when there is an error while building extensions. # class ExtensionBuildError < Gem::InstallError; end @@ -71,8 +82,6 @@ class Gem::Installer end - ENV_PATHS = %w[/usr/bin/env /bin/env] - ## # Constructs an Installer instance that will install the gem located at # +gem+. +options+ is a Hash with the following keys: @@ -100,17 +109,17 @@ class Gem::Installer :source_index => Gem.source_index, }.merge options - @env_shebang = options[:env_shebang] - @force = options[:force] - gem_home = options[:install_dir] - @gem_home = Pathname.new(gem_home).expand_path @ignore_dependencies = options[:ignore_dependencies] - @format_executable = options[:format_executable] - @security_policy = options[:security_policy] - @wrappers = options[:wrappers] - @bin_dir = options[:bin_dir] - @development = options[:development] - @source_index = options[:source_index] begin @format = Gem::Format.from_file_by_path @gem, @security_policy @@ -121,7 +130,7 @@ class Gem::Installer begin FileUtils.mkdir_p @gem_home rescue Errno::EACCES, Errno::ENOTDIR - # We'll divert to ~/.gem below end if not File.writable? @gem_home or @@ -131,7 +140,7 @@ class Gem::Installer if options[:user_install] == false then # You don't want to use ~ raise Gem::FilePermissionError, @gem_home elsif options[:user_install].nil? then - unless self.class.home_install_warning then alert_warning "Installing to ~/.gem since #{@gem_home} and\n\t #{Gem.bindir} aren't both writable." self.class.home_install_warning = true end @@ -392,19 +401,21 @@ class Gem::Installer ruby_name = Gem::ConfigMap[:ruby_install_name] if @env_shebang path = File.join @gem_dir, @spec.bindir, bin_file_name first_line = File.open(path, "rb") {|file| file.gets} if /\A#!/ =~ first_line then # Preserve extra words on shebang line, like "-w". Thanks RPA. shebang = first_line.sub(/\A\#!.*?ruby\S*(?=(\s+\S+))/, "#!#{Gem.ruby}") opts = $1 shebang.strip! # Avoid nasty ^M issues. end - if !ruby_name "#!#{Gem.ruby}#{opts}" - elsif opts - %{#!/bin/sh\n'exec' #{ruby_name.dump} '-x' "$0" "$@"\n#{shebang}} else # Create a plain shebang line. - @env_path ||= ENV_PATHS.find {|path| File.executable?(path)} "#!#{@env_path} #{ruby_name}" end end @@ -432,7 +443,7 @@ if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then end gem '#{@spec.name}', version -load '#{bin_file_name}' TEXT end @@ -443,10 +454,10 @@ TEXT <<-TEXT @ECHO OFF IF NOT "%~f0" == "~f0" GOTO :WinNT -@"#{File.basename(Gem.ruby)}" "#{File.join(bindir, bin_file_name)}" %1 %2 %3 %4 %5 %6 %7 %8 %9 GOTO :EOF :WinNT -@"#{File.basename(Gem.ruby)}" "%~dpn0" %* TEXT end @@ -531,6 +542,7 @@ Results logged to #{File.join(Dir.pwd, 'gem_make.out')} raise Gem::InstallError, msg end FileUtils.mkdir_p File.dirname(path) File.open(path, "wb") do |out| @@ -23,7 +23,9 @@ module Gem::LocalRemoteOptions raise OptionParser::InvalidArgument, value end - raise OptionParser::InvalidArgument, value unless uri.scheme == 'http' value end @@ -90,7 +92,7 @@ module Gem::LocalRemoteOptions source << '/' if source !~ /\/\z/ if options[:added_source] then - Gem.sources << source else options[:added_source] = true Gem.sources.replace [source] @@ -99,10 +101,9 @@ module Gem::LocalRemoteOptions end ## - # Add the --update-source option def add_update_sources_option - add_option(:"Local/Remote", '-u', '--[no-]update-sources', 'Update local source cache') do |value, options| Gem.configuration.update_sources = value @@ -4,145 +4,149 @@ # See LICENSE.txt for permissions. #++ require 'fileutils' require 'yaml' require 'zlib' -module Gem ## - # The format class knows the guts of the RubyGem .gem file format - # and provides the capability to read gem files # - class OldFormat - attr_accessor :spec, :file_entries, :gem_path - - ## - # Constructs an instance of a Format object, representing the gem's - # data structure. - # - # gem:: [String] The file name of the gem - # - def initialize(gem_path) - @gem_path = gem_path - end - ## - # Reads the named gem file and returns a Format object, representing - # the data from the gem file - # - # file_path:: [String] Path to the gem file - # - def self.from_file_by_path(file_path) - unless File.exist?(file_path) - raise Gem::Exception, "Cannot load gem file [#{file_path}]" - end - File.open(file_path, 'rb') do |file| - from_io(file, file_path) - end end - ## - # Reads a gem from an io stream and returns a Format object, representing - # the data from the gem file - # - # io:: [IO] Stream from which to read the gem - # - def self.from_io(io, gem_path="(io)") - format = self.new(gem_path) - skip_ruby(io) - format.spec = read_spec(io) - format.file_entries = [] - read_files_from_gem(io) do |entry, file_data| - format.file_entries << [entry, file_data] - end - format end - private - ## - # Skips the Ruby self-install header. After calling this method, the - # IO index will be set after the Ruby code. - # - # file:: [IO] The IO to process (skip the Ruby code) - # - def self.skip_ruby(file) - end_seen = false - loop { - line = file.gets - if(line == nil || line.chomp == "__END__") then - end_seen = true - break - end - } - if(end_seen == false) then - raise Gem::Exception.new("Failed to find end of ruby script while reading gem") - end end - ## - # Reads the specification YAML from the supplied IO and constructs - # a Gem::Specification from it. After calling this method, the - # IO index will be set after the specification header. - # - # file:: [IO] The IO to process - # - def self.read_spec(file) - yaml = '' - begin - read_until_dashes(file) do |line| - yaml << line - end - Specification.from_yaml(yaml) - rescue YAML::Error => e - raise Gem::Exception.new("Failed to parse gem specification out of gem file") - rescue ArgumentError => e - raise Gem::Exception.new("Failed to parse gem specification out of gem file") end end - ## - # Reads lines from the supplied IO until a end-of-yaml (---) is - # reached - # - # file:: [IO] The IO to process - # block:: [String] The read line - # - def self.read_until_dashes(file) - while((line = file.gets) && line.chomp.strip != "---") do - yield line - end end - ## - # Reads the embedded file data from a gem file, yielding an entry - # containing metadata about the file and the file contents themselves - # for each file that's archived in the gem. - # NOTE: Many of these methods should be extracted into some kind of - # Gem file read/writer - # - # gem_file:: [IO] The IO to process - # - def self.read_files_from_gem(gem_file) - errstr = "Error reading files from gem" - header_yaml = '' - begin self.read_until_dashes(gem_file) do |line| - header_yaml << line - end - header = YAML.load(header_yaml) - raise Gem::Exception.new(errstr) unless header - header.each do |entry| - file_data = '' - self.read_until_dashes(gem_file) do |line| - file_data << line - end - yield [entry, Zlib::Inflate.inflate(file_data.strip.unpack("m")[0])] end - rescue Exception,Zlib::DataError => e - raise Gem::Exception.new(errstr) end end end end @@ -3,8 +3,6 @@ # See LICENSE.txt for additional licensing information. #-- -require 'rubygems/package' - module Gem::Package::FSyncDir private @@ -3,8 +3,6 @@ # See LICENSE.txt for additional licensing information. #-- -require 'rubygems/package' - ## #-- # struct tarfile_entry_posix { @@ -26,9 +24,13 @@ require 'rubygems/package' # char prefix[155]; # ASCII + (Z unless filled) # }; #++ class Gem::Package::TarHeader FIELDS = [ :checksum, :devmajor, @@ -48,6 +50,9 @@ class Gem::Package::TarHeader :version, ] PACK_FORMAT = 'a100' + # name 'a8' + # mode 'a8' + # uid @@ -65,6 +70,9 @@ class Gem::Package::TarHeader 'a8' + # devminor 'a155' # prefix UNPACK_FORMAT = 'A100' + # name 'A8' + # mode 'A8' + # uid @@ -84,6 +92,9 @@ class Gem::Package::TarHeader attr_reader(*FIELDS) def self.from(stream) header = stream.read 512 empty = (header == "\0" * 512) @@ -147,6 +158,9 @@ class Gem::Package::TarHeader # :empty => empty end def initialize(vals) unless vals[:name] && vals[:size] && vals[:prefix] && vals[:mode] then raise ArgumentError, ":name, :size, :prefix and :mode required" @@ -171,11 +185,14 @@ class Gem::Package::TarHeader @empty = vals[:empty] end def empty? @empty end - def ==(other) self.class === other and @checksum == other.checksum and @devmajor == other.devmajor and @@ -195,11 +212,14 @@ class Gem::Package::TarHeader @version == other.version end - def to_s update_checksum header end def update_checksum header = header " " * 8 @checksum = oct calculate_checksum(header), 6 @@ -3,8 +3,6 @@ # See LICENSE.txt for additional licensing information. #-- -require 'rubygems/package' - class Gem::Package::TarInput include Gem::Package::FSyncDir @@ -72,9 +70,9 @@ class Gem::Package::TarInput # map trust policy from string to actual class (or a serialized YAML # file, if that exists) if String === security_policy then - if Gem::Security::Policy.key? security_policy then # load one of the pre-defined security policies - security_policy = Gem::Security::Policy[security_policy] elsif File.exist? security_policy then # FIXME: this doesn't work yet security_policy = YAML.load File.read(security_policy) @@ -136,10 +134,10 @@ class Gem::Package::TarInput def extract_entry(destdir, entry, expected_md5sum = nil) if entry.directory? then - dest = File.join(destdir, entry.full_name) - if File.dir? dest then - @fileops.chmod entry.header.mode, dest, :verbose=>false else @fileops.mkdir_p dest, :mode => entry.header.mode, :verbose => false end @@ -3,8 +3,6 @@ # See LICENSE.txt for additional licensing information. #-- -require 'rubygems/package' - ## # TarOutput is a wrapper to TarWriter that builds gem-format tar file. # @@ -66,8 +64,10 @@ class Gem::Package::TarOutput Zlib::GzipWriter.wrap(sio || inner) do |os| Gem::Package::TarWriter.new os do |data_tar_writer| def data_tar_writer.metadata() @metadata end def data_tar_writer.metadata=(metadata) @metadata = metadata end yield data_tar_writer @@ -3,14 +3,21 @@ # See LICENSE.txt for additional licensing information. #-- -require 'rubygems/package' class Gem::Package::TarReader include Gem::Package class UnexpectedEOF < StandardError; end def self.new(io) reader = super @@ -25,14 +32,24 @@ class Gem::Package::TarReader nil end def initialize(io) @io = io @init_pos = io.pos end def close end def each loop do return if @io.eof? @@ -84,3 +101,5 @@ class Gem::Package::TarReader end @@ -3,12 +3,19 @@ # See LICENSE.txt for additional licensing information. #-- -require 'rubygems/package' class Gem::Package::TarReader::Entry attr_reader :header def initialize(header, io) @closed = false @header = header @@ -21,24 +28,39 @@ class Gem::Package::TarReader::Entry raise IOError, "closed #{self.class}" if closed? end def bytes_read @read end def close @closed = true end def closed? @closed end def eof? check_closed @read >= @header.size end def full_name if @header.prefix != "" then File.join @header.prefix, @header.name @@ -47,6 +69,9 @@ class Gem::Package::TarReader::Entry end end def getc check_closed @@ -58,20 +83,33 @@ class Gem::Package::TarReader::Entry ret end def directory? @header.typeflag == "5" end def file? @header.typeflag == "0" end def pos check_closed bytes_read end def read(len = nil) check_closed @@ -86,6 +124,9 @@ class Gem::Package::TarReader::Entry ret end def rewind check_closed @@ -3,15 +3,30 @@ # See LICENSE.txt for additional licensing information. #-- -require 'rubygems/package' class Gem::Package::TarWriter class FileOverflow < StandardError; end class BoundedStream - attr_reader :limit, :written def initialize(io, limit) @io = io @@ -19,6 +34,10 @@ class Gem::Package::TarWriter @written = 0 end def write(data) if data.size + @written > @limit raise FileOverflow, "You tried to feed more data than fits in the file." @@ -30,18 +49,30 @@ class Gem::Package::TarWriter end class RestrictedStream def initialize(io) @io = io end def write(data) @io.write data end end def self.new(io) writer = super @@ -56,12 +87,19 @@ class Gem::Package::TarWriter nil end def initialize(io) @io = io @closed = false end - def add_file(name, mode) check_closed raise Gem::Package::NonSeekableIO unless @io.respond_to? :pos= @@ -90,7 +128,11 @@ class Gem::Package::TarWriter self end - def add_file_simple(name, mode, size) check_closed name, prefix = split_name name @@ -112,10 +154,16 @@ class Gem::Package::TarWriter self end def check_closed raise IOError, "closed #{self.class}" if closed? end def close check_closed @@ -125,16 +173,25 @@ class Gem::Package::TarWriter @closed = true end def closed? @closed end def flush check_closed @io.flush if @io.respond_to? :flush end def mkdir(name, mode) check_closed @@ -149,6 +206,9 @@ class Gem::Package::TarWriter self end def split_name(name) # :nodoc: raise Gem::Package::TooLongFileName if name.size > 256 @@ -169,7 +229,7 @@ class Gem::Package::TarWriter name = newname if name.size > 100 or prefix.size > 155 then - raise Gem::Package::TooLongFileName end end @@ -0,0 +1,118 @@ @@ -1,5 +1,3 @@ -require 'rubygems' - ## # Available list of platforms for targeting Gem installations. @@ -105,6 +103,10 @@ class Gem::Platform def to_s to_a.compact.join '-' end ## # Is +other+ equal to this platform? Two platforms are equal if they have @@ -143,14 +145,14 @@ class Gem::Platform when String then # This data is from http://gems.rubyforge.org/gems/yaml on 19 Aug 2007 other = case other - when /^i686-darwin(\d)/ then ['x86', 'darwin', $1] - when /^i\d86-linux/ then ['x86', 'linux', nil] - when 'java', 'jruby' then [nil, 'java', nil] - when /mswin32(\_(\d+))?/ then ['x86', 'mswin32', $2] - when 'powerpc-darwin' then ['powerpc', 'darwin', nil] - when /powerpc-darwin(\d)/ then ['powerpc', 'darwin', $1] - when /sparc-solaris2.8/ then ['sparc', 'solaris', '2.8'] - when /universal-darwin(\d)/ then ['universal', 'darwin', $1] else other end @@ -55,7 +55,7 @@ class Gem::RemoteFetcher # HTTP_PROXY_PASS) # * <tt>:no_proxy</tt>: ignore environment variables and _don't_ use a proxy - def initialize(proxy) Socket.do_not_reverse_lookup = true @connections = {} @@ -86,7 +86,11 @@ class Gem::RemoteFetcher FileUtils.mkdir_p cache_dir rescue nil unless File.exist? cache_dir - source_uri = URI.parse source_uri unless URI::Generic === source_uri scheme = source_uri.scheme # URI.parse gets confused by MS Windows paths with forward slashes. @@ -101,7 +105,7 @@ class Gem::RemoteFetcher remote_gem_path = source_uri + "gems/#{gem_file_name}" - gem = Gem::RemoteFetcher.fetcher.fetch_path remote_gem_path rescue Gem::RemoteFetcher::FetchError raise if spec.original_platform == spec.platform @@ -112,16 +116,34 @@ class Gem::RemoteFetcher remote_gem_path = source_uri + "gems/#{alternate_name}" - gem = Gem::RemoteFetcher.fetcher.fetch_path remote_gem_path end File.open local_gem_path, 'wb' do |fp| fp.write gem end end - when nil, 'file' then # TODO test for local overriding cache begin - FileUtils.cp source_uri.to_s, local_gem_path rescue Errno::EACCES local_gem_path = source_uri.to_s end @@ -177,7 +199,7 @@ class Gem::RemoteFetcher return nil if env_proxy.nil? or env_proxy.empty? - uri = URI.parse env_proxy if uri and uri.user.nil? and uri.password.nil? then # Probably we have http_proxy_* variables? @@ -233,10 +255,25 @@ class Gem::RemoteFetcher def open_uri_or_path(uri, last_modified = nil, head = false, depth = 0) raise "block is dead" if block_given? - return open(get_file_uri_path(uri)) if file_uri? uri - uri = URI.parse uri unless URI::Generic === uri - raise ArgumentError, 'uri is not an HTTP URI' unless URI::HTTP === uri fetch_type = head ? Net::HTTP::Head : Net::HTTP::Get response = request uri, fetch_type, last_modified @@ -326,19 +363,5 @@ class Gem::RemoteFetcher connection.start end - ## - # Checks if the provided string is a file:// URI. - - def file_uri?(uri) - uri =~ %r{\Afile://} - end - - ## - # Given a file:// URI, returns its local path. - - def get_file_uri_path(uri) - uri.sub(%r{\Afile://}, '') - end - end @@ -1,15 +1,17 @@ -module Gem - module RequirePathsBuilder - def write_require_paths_file_if_needed(spec = @spec, gem_home = @gem_home) - return if spec.require_paths == ["lib"] && (spec.bindir.nil? || spec.bindir == "bin") - file_name = File.join(gem_home, 'gems', "#{@spec.full_name}", ".require_paths") - file_name.untaint - File.open(file_name, "w") do |file| - spec.require_paths.each do |path| - file.puts path - end - file.puts spec.bindir if spec.bindir end end end -end \ No newline at end of file @@ -4,8 +4,6 @@ # See LICENSE.txt for permissions. #++ -require 'rubygems/version' - ## # Requirement version includes a prefaced comparator in addition # to a version number. @@ -26,10 +24,10 @@ class Gem::Requirement "<" => lambda { |v, r| v < r }, ">=" => lambda { |v, r| v >= r }, "<=" => lambda { |v, r| v <= r }, - "~>" => lambda { |v, r| v >= r && v < r.bump } } - OP_RE = /#{OPS.keys.map{ |k| Regexp.quote k }.join '|'}/o ## # Factory method to create a Gem::Requirement object. Input may be a @@ -65,7 +63,7 @@ class Gem::Requirement ## # Constructs a Requirement from +requirements+ which can be a String, a - # Gem::Version, or an Array of those. See parse for details on the # formatting of requirement strings. def initialize(requirements) @@ -99,11 +97,15 @@ class Gem::Requirement as_list.join(", ") end def as_list normalize - @requirements.collect { |req| - "#{req[0]} #{req[1]}" - } end def normalize @@ -129,18 +131,23 @@ class Gem::Requirement OPS[op].call(version, required_version) end ## # Parse the version requirement obj returning the operator and version. # # The requirement can be a String or a Gem::Version. A String can be an - # operator (<, <=, =, =>, >, !=, ~>), a version number, or both, operator # first. def parse(obj) case obj - when /^\s*(#{OP_RE})\s*([0-9.]+)\s*$/o then [$1, Gem::Version.new($2)] - when /^\s*([0-9.]+)\s*$/ then ['=', Gem::Version.new($1)] when /^\s*(#{OP_RE})\s*$/o then [$1, Gem::Version.new('0')] @@ -1,6 +1,19 @@ # DO NOT EDIT # This file is auto-generated by build scripts. # See: rake update_version module Gem - RubyGemsVersion = '1.3.1' end @@ -218,7 +218,7 @@ require 'rubygems/gem_openssl' # # # signing key (still kept in an undisclosed location!) # s.signing_key = '/mnt/floppy/alf-private_key.pem' -# # # certificate chain (includes the issuer certificate now too) # s.cert_chain = ['/home/alf/doc/seattlerb-public_cert.pem', # '/home/alf/doc/alf_at_seattle-public_cert.pem'] @@ -274,7 +274,7 @@ require 'rubygems/gem_openssl' # # convert a PEM format X509 certificate into DER format: # # (note: Windows .cer files are X509 certificates in DER format) # $ openssl x509 -in input.pem -outform der -out output.der -# # # print out the certificate in a human-readable format: # $ openssl x509 -in input.pem -noout -text # @@ -282,7 +282,7 @@ require 'rubygems/gem_openssl' # # # convert a PEM format RSA key into DER format: # $ openssl rsa -in input_key.pem -outform der -out output_key.der -# # # print out the key in a human readable format: # $ openssl rsa -in input_key.pem -noout -text # @@ -17,6 +17,7 @@ require 'rubygems/doc_manager' # name/version/platform index # * "/quick/" - Individual gemspecs # * "/gems" - Direct access to download the installable gems # * legacy indexes: # * "/Marshal.#{Gem.marshal_version}" - Full SourceIndex dump of metadata # for installed gems @@ -32,9 +33,20 @@ require 'rubygems/doc_manager' class Gem::Server include Gem::UserInteraction - DOC_TEMPLATE = <<-'WEBPAGE' <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" @@ -47,6 +59,7 @@ class Gem::Server </head> <body> <div id="fileHeader"> <h1>RubyGems Documentation Index</h1> </div> <!-- banner header --> @@ -114,10 +127,10 @@ class Gem::Server </div> </body> </html> - WEBPAGE # CSS is copy & paste from rdoc-style.css, RDoc V1.0.1 - 20041108 - RDOC_CSS = <<-RDOCCSS body { font-family: Verdana,Arial,Helvetica,sans-serif; font-size: 90%; @@ -325,7 +338,92 @@ div.method-source-code pre { color: #ffdead; overflow: hidden; } .ruby-comment { color: #b22222; font-weight: bold; background: transparent; } .ruby-regexp { color: #ffa07a; background: transparent; } .ruby-value { color: #7fffd4; background: transparent; } - RDOCCSS def self.run(options) new(options[:gemdir], options[:port], options[:daemon]).run @@ -533,6 +631,90 @@ div.method-source-code pre { color: #ffdead; overflow: hidden; } res.body = result end def run @server.listen nil, @port @@ -564,6 +746,8 @@ div.method-source-code pre { color: #ffdead; overflow: hidden; } @server.mount_proc "/", method(:root) paths = { "/gems" => "/cache/", "/doc_root" => "/doc/" } paths.each do |mount_point, mount_dir| @server.mount(mount_point, WEBrick::HTTPServlet::FileHandler, @@ -4,12 +4,14 @@ # See LICENSE.txt for permissions. #++ -require 'rubygems' require 'rubygems/user_interaction' require 'rubygems/specification' module Gem - autoload(:SpecFetcher, 'rubygems/spec_fetcher') end ## # The SourceIndex object indexes all the gems available from a @@ -28,7 +30,7 @@ class Gem::SourceIndex include Gem::UserInteraction - attr_reader :gems # :nodoc: ## # Directories to use to refresh this SourceIndex when calling refresh! @@ -81,13 +83,15 @@ class Gem::SourceIndex # loaded spec. def load_specification(file_name) - begin - spec_code = if RUBY_VERSION < '1.9' then - File.read file_name - else - File.read file_name, :encoding => 'UTF-8' - end.untaint gemspec = eval spec_code, binding, file_name if gemspec.is_a?(Gem::Specification) @@ -104,24 +108,33 @@ class Gem::SourceIndex alert_warning "#{e.inspect}\n#{spec_code}" alert_warning "Invalid .gemspec format in '#{file_name}'" end return nil end end ## - # Constructs a source index instance from the provided - # specifications - # - # specifications:: - # [Hash] hash of [Gem name, Gem::Specification] pairs def initialize(specifications={}) - @gems = specifications @spec_dirs = nil end ## # Reconstruct the source index from the specifications in +spec_dirs+. def load_gems_in(*spec_dirs) @@ -170,14 +183,29 @@ class Gem::SourceIndex result[name] << spec end result.values.flatten end ## # Add a gem specification to the source index. - def add_spec(gem_spec) - @gems[gem_spec.full_name] = gem_spec end ## @@ -193,7 +221,11 @@ class Gem::SourceIndex # Remove a gem specification named +full_name+. def remove_spec(full_name) - @gems.delete(full_name) end ## @@ -215,18 +247,18 @@ class Gem::SourceIndex # change in the index. def index_signature - require 'rubygems/digest/sha2' - Gem::SHA256.new.hexdigest(@gems.keys.sort.join(',')).to_s end ## # The signature for the given gem specification. def gem_signature(gem_full_name) - require 'rubygems/digest/sha2' - Gem::SHA256.new.hexdigest(@gems[gem_full_name].to_yaml).to_s end def size @@ -238,7 +270,7 @@ class Gem::SourceIndex # Find a gem by an exact match on the short name. def find_name(gem_name, version_requirement = Gem::Requirement.default) - dep = Gem::Dependency.new(/^#{gem_name}$/, version_requirement) search dep end @@ -257,7 +289,7 @@ class Gem::SourceIndex # TODO - Remove support and warning for legacy arguments after 2008/11 unless Gem::Dependency === gem_pattern - warn "#{Gem.location_of_caller.join ':'}:Warning: Gem::SourceIndex#search support for #{gem_pattern.class} patterns is deprecated" end case gem_pattern @@ -282,7 +314,7 @@ class Gem::SourceIndex version_requirement = Gem::Requirement.create version_requirement end - specs = @gems.values.select do |spec| spec.name =~ gem_pattern and version_requirement.satisfied_by? spec.version end @@ -376,7 +408,7 @@ class Gem::SourceIndex end def ==(other) # :nodoc: - self.class === other and @gems == other.gems end def dump @@ -545,15 +577,15 @@ class Gem::SourceIndex end module Gem - # :stopdoc: - # Cache is an alias for SourceIndex to allow older YAMLized source index # objects to load properly. - Cache = SourceIndex - # :startdoc: end @@ -286,7 +286,7 @@ class Gem::SourceInfoCache next unless Gem.sources.include? source_uri # TODO - Remove this gunk after 2008/11 unless pattern.kind_of?(Gem::Dependency) - pattern = Gem::Dependency.new(pattern, Gem::Requirement.default) end sic_entry.source_index.search pattern, platform_only end.flatten.compact @@ -306,7 +306,7 @@ class Gem::SourceInfoCache # TODO - Remove this gunk after 2008/11 unless pattern.kind_of?(Gem::Dependency) - pattern = Gem::Dependency.new(pattern, Gem::Requirement.default) end sic_entry.source_index.search(pattern, only_platform).each do |spec| @@ -13,8 +13,8 @@ class Gem::SourceInfoCacheEntry attr_reader :source_index ## - # The size of the of the source entry. Used to determine if the - # source index has changed. attr_reader :size @@ -1,6 +1,6 @@ require 'zlib' -require 'rubygems' require 'rubygems/remote_fetcher' require 'rubygems/user_interaction' @@ -26,6 +26,11 @@ class Gem::SpecFetcher attr_reader :specs # :nodoc: @fetcher = nil def self.fetcher @@ -42,6 +47,7 @@ class Gem::SpecFetcher @specs = {} @latest_specs = {} @fetcher = Gem::RemoteFetcher.fetcher end @@ -56,10 +62,10 @@ class Gem::SpecFetcher ## # Fetch specs matching +dependency+. If +all+ is true, all matching # versions are returned. If +matching_platform+ is false, all platforms are - # returned. - def fetch(dependency, all = false, matching_platform = true) - specs_and_sources = find_matching dependency, all, matching_platform specs_and_sources.map do |spec_tuple, source_uri| [fetch_spec(spec_tuple, URI.parse(source_uri)), source_uri] @@ -110,10 +116,10 @@ class Gem::SpecFetcher # versions are returned. If +matching_platform+ is false, gems for all # platforms are returned. - def find_matching(dependency, all = false, matching_platform = true) found = {} - list(all).each do |source_uri, specs| found[source_uri] = specs.select do |spec_name, version, spec_platform| dependency =~ Gem::Dependency.new(spec_name, version) and (not matching_platform or Gem::Platform.match(spec_platform)) @@ -155,28 +161,37 @@ class Gem::SpecFetcher ## # Returns a list of gems available for each source in Gem::sources. If - # +all+ is true, all versions are returned instead of only latest versions. - def list(all = false) list = {} - file = all ? 'specs' : 'latest_specs' Gem.sources.each do |source_uri| source_uri = URI.parse source_uri - if all and @specs.include? source_uri then - list[source_uri] = @specs[source_uri] - elsif not all and @latest_specs.include? source_uri then - list[source_uri] = @latest_specs[source_uri] - else - specs = load_specs source_uri, file - - cache = all ? @specs : @latest_specs - - cache[source_uri] = specs - list[source_uri] = specs end end list @@ -206,7 +221,14 @@ class Gem::SpecFetcher loaded = true end - specs = Marshal.load spec_dump if loaded and @update_cache then begin @@ -4,1260 +4,1440 @@ # See LICENSE.txt for permissions. #++ -require 'rubygems' require 'rubygems/version' require 'rubygems/requirement' require 'rubygems/platform' # :stopdoc: -# Time::today has been deprecated in 0.9.5 and will be removed. -if RUBY_VERSION < '1.9' then - def Time.today - t = Time.now - t - ((t.to_f + t.gmt_offset) % 86400) - end unless defined? Time.today -end - class Date; end # for ruby_code if date.rb wasn't required - # :startdoc: -module Gem ## - # == Gem::Specification - # - # The Specification class contains the metadata for a Gem. Typically - # defined in a .gemspec file or a Rakefile, and looks like this: # - # spec = Gem::Specification.new do |s| - # s.name = 'rfoo' - # s.version = '1.0' - # s.summary = 'Example gem specification' - # ... - # end # - # There are many <em>gemspec attributes</em>, and the best place to learn - # about them in the "Gemspec Reference" linked from the RubyGems wiki. - - class Specification - - ## - # Allows deinstallation of gems with legacy platforms. - - attr_accessor :original_platform # :nodoc: - - ## - # The the version number of a specification that does not specify one - # (i.e. RubyGems 0.7 or earlier). - - NONEXISTENT_SPECIFICATION_VERSION = -1 - - ## - # The specification version applied to any new Specification instances - # created. This should be bumped whenever something in the spec format - # changes. - #-- - # When updating this number, be sure to also update #to_ruby. - # - # NOTE RubyGems < 1.2 cannot load specification versions > 2. - - CURRENT_SPECIFICATION_VERSION = 2 - - ## - # An informal list of changes to the specification. The highest-valued - # key should be equal to the CURRENT_SPECIFICATION_VERSION. - - SPECIFICATION_VERSION_HISTORY = { - -1 => ['(RubyGems versions up to and including 0.7 did not have versioned specifications)'], - 1 => [ - 'Deprecated "test_suite_file" in favor of the new, but equivalent, "test_files"', - '"test_file=x" is a shortcut for "test_files=[x]"' - ], - 2 => [ - 'Added "required_rubygems_version"', - 'Now forward-compatible with future versions', - ], - } - # :stopdoc: - MARSHAL_FIELDS = { -1 => 16, 1 => 16, 2 => 16 } - now = Time.at(Time.now.to_i) - TODAY = now - ((now.to_i + now.gmt_offset) % 86400) - # :startdoc: - ## - # List of Specification instances. - @@list = [] - ## - # Optional block used to gather newly defined instances. - @@gather = nil - ## - # List of attribute names: [:name, :version, ...] - @@required_attributes = [] - ## - # List of _all_ attributes and default values: - # - # [[:name, nil], - # [:bindir, 'bin'], - # ...] - @@attributes = [] - @@nil_attributes = [] - @@non_nil_attributes = [:@original_platform] - ## - # List of array attributes - @@array_attributes = [] - ## - # Map of attribute names to default values. - @@default_value = {} - ## - # Names of all specification attributes - def self.attribute_names - @@attributes.map { |name, default| name } - end - ## - # Default values for specification attributes - def self.attribute_defaults - @@attributes.dup - end - ## - # The default value for specification attribute +name+ - def self.default_value(name) - @@default_value[name] end - ## - # Required specification attributes - def self.required_attributes - @@required_attributes.dup - end - ## - # Is +name+ a required attribute? - def self.required_attribute?(name) - @@required_attributes.include? name.to_sym - end - ## - # Specification attributes that are arrays (appendable and so-forth) - def self.array_attributes - @@array_attributes.dup end - ## - # A list of Specification instances that have been defined in this Ruby - # instance. - def self.list - @@list end - ## - # Specifies the +name+ and +default+ for a specification attribute, and - # creates a reader and writer method like Module#attr_accessor. - # - # The reader method returns the default if the value hasn't been set. - def self.attribute(name, default=nil) - ivar_name = "@#{name}".intern - if default.nil? then - @@nil_attributes << ivar_name - else - @@non_nil_attributes << [ivar_name, default] - end - @@attributes << [name, default] - @@default_value[name] = default - attr_accessor(name) - end - ## - # Same as :attribute, but ensures that values assigned to the attribute - # are array values by applying :to_a to the value. - def self.array_attribute(name) - @@non_nil_attributes << ["@#{name}".intern, []] - @@array_attributes << name - @@attributes << [name, []] - @@default_value[name] = [] - code = %{ - def #{name} - @#{name} ||= [] - end - def #{name}=(value) - @#{name} = Array(value) - end - } - module_eval code, __FILE__, __LINE__ - 9 - end - ## - # Same as attribute above, but also records this attribute as mandatory. - def self.required_attribute(*args) - @@required_attributes << args.first - attribute(*args) - end - ## - # Sometimes we don't want the world to use a setter method for a - # particular attribute. - # - # +read_only+ makes it private so we can still use it internally. - def self.read_only(*names) - names.each do |name| - private "#{name}=" - end end - # Shortcut for creating several attributes at once (each with a default - # value of +nil+). - def self.attributes(*args) - args.each do |arg| - attribute(arg, nil) end end - ## - # Some attributes require special behaviour when they are accessed. This - # allows for that. - def self.overwrite_accessor(name, &block) - remove_method name - define_method(name, &block) - end - ## - # Defines a _singular_ version of an existing _plural_ attribute (i.e. one - # whose value is expected to be an array). This means just creating a - # helper method that takes a single value and appends it to the array. - # These are created for convenience, so that in a spec, one can write - # - # s.require_path = 'mylib' - # - # instead of: - # - # s.require_paths = ['mylib'] - # - # That above convenience is available courtesy of: - # - # attribute_alias_singular :require_path, :require_paths - - def self.attribute_alias_singular(singular, plural) - define_method("#{singular}=") { |val| - send("#{plural}=", [val]) - } - define_method("#{singular}") { - val = send("#{plural}") - val.nil? ? nil : val.first - } - end - ## - # Dump only crucial instance variables. - #-- - # MAINTAIN ORDER! - - def _dump(limit) - Marshal.dump [ - @rubygems_version, - @specification_version, - @name, - @version, - (Time === @date ? @date : (require 'time'; Time.parse(@date.to_s))), - @summary, - @required_ruby_version, - @required_rubygems_version, - @original_platform, - @dependencies, - @rubyforge_project, - @email, - @authors, - @description, - @homepage, - @has_rdoc, - @new_platform, - ] - end - ## - # Load custom marshal format, re-initializing defaults as needed - def self._load(str) - array = Marshal.load str - spec = Gem::Specification.new - spec.instance_variable_set :@specification_version, array[1] - current_version = CURRENT_SPECIFICATION_VERSION - field_count = if spec.specification_version > current_version then - spec.instance_variable_set :@specification_version, - current_version - MARSHAL_FIELDS[current_version] - else - MARSHAL_FIELDS[spec.specification_version] - end - if array.size < field_count then - raise TypeError, "invalid Gem::Specification format #{array.inspect}" - end - spec.instance_variable_set :@rubygems_version, array[0] - # spec version - spec.instance_variable_set :@name, array[2] - spec.instance_variable_set :@version, array[3] - spec.instance_variable_set :@date, array[4] - spec.instance_variable_set :@summary, array[5] - spec.instance_variable_set :@required_ruby_version, array[6] - spec.instance_variable_set :@required_rubygems_version, array[7] - spec.instance_variable_set :@original_platform, array[8] - spec.instance_variable_set :@dependencies, array[9] - spec.instance_variable_set :@rubyforge_project, array[10] - spec.instance_variable_set :@email, array[11] - spec.instance_variable_set :@authors, array[12] - spec.instance_variable_set :@description, array[13] - spec.instance_variable_set :@homepage, array[14] - spec.instance_variable_set :@has_rdoc, array[15] - spec.instance_variable_set :@new_platform, array[16] - spec.instance_variable_set :@platform, array[16].to_s - spec.instance_variable_set :@loaded, false - - spec end - ## - # List of depedencies that will automatically be activated at runtime. - def runtime_dependencies - dependencies.select { |d| d.type == :runtime || d.type == nil } end - ## - # List of dependencies that are used for development - def development_dependencies - dependencies.select { |d| d.type == :development } end - def test_suite_file # :nodoc: - warn 'test_suite_file deprecated, use test_files' - test_files.first end - def test_suite_file=(val) # :nodoc: - warn 'test_suite_file= deprecated, use test_files=' - @test_files = [] unless defined? @test_files - @test_files << val end - ## - # true when this gemspec has been loaded from a specifications directory. - # This attribute is not persisted. - attr_accessor :loaded - ## - # Path this gemspec was loaded from. This attribute is not persisted. - attr_accessor :loaded_from - ## - # Returns an array with bindir attached to each executable in the - # executables list - def add_bindir(executables) - return nil if executables.nil? - if @bindir then - Array(executables).map { |e| File.join(@bindir, e) } - else - executables - end - rescue - return nil - end - ## - # Files in the Gem under one of the require_paths - def lib_files - @files.select do |file| - require_paths.any? do |path| - file.index(path) == 0 - end - end end - ## - # True if this gem was loaded from disk - alias :loaded? :loaded - ## - # True if this gem has files in test_files - def has_unit_tests? - not test_files.empty? - end - alias has_test_suite? has_unit_tests? # :nodoc: deprecated - ## - # Specification constructor. Assigns the default values to the - # attributes, adds this spec to the list of loaded specs (see - # Specification.list), and yields itself for further initialization. - def initialize - @new_platform = nil - assign_defaults - @loaded = false - @loaded_from = nil - @@list << self - yield self if block_given? - @@gather.call(self) if @@gather end - ## - # Each attribute has a default value (possibly nil). Here, we initialize - # all attributes to their default value. This is done through the - # accessor methods, so special behaviours will be honored. Furthermore, - # we take a _copy_ of the default so each specification instance has its - # own empty arrays, etc. - def assign_defaults - @@nil_attributes.each do |name| - instance_variable_set name, nil - end - @@non_nil_attributes.each do |name, default| - value = case default - when Time, Numeric, Symbol, true, false, nil then default - else default.dup - end - instance_variable_set name, value - end - # HACK - instance_variable_set :@new_platform, Gem::Platform::RUBY end - ## - # Special loader for YAML files. When a Specification object is loaded - # from a YAML file, it bypasses the normal Ruby object initialization - # routine (#initialize). This method makes up for that and deals with - # gems of different ages. - # - # 'input' can be anything that YAML.load() accepts: String or IO. - def self.from_yaml(input) - input = normalize_yaml_input input - spec = YAML.load input - if spec && spec.class == FalseClass then - raise Gem::EndOfYAMLException - end - unless Gem::Specification === spec then - raise Gem::Exception, "YAML data doesn't evaluate to gem specification" - end - unless (spec.instance_variables.include? '@specification_version' or - spec.instance_variables.include? :@specification_version) and - spec.instance_variable_get :@specification_version - spec.instance_variable_set :@specification_version, - NONEXISTENT_SPECIFICATION_VERSION - end - spec - end - ## - # Loads ruby format gemspec from +filename+ - - def self.load(filename) - gemspec = nil - fail "NESTED Specification.load calls not allowed!" if @@gather - @@gather = proc { |gs| gemspec = gs } - data = File.read(filename) - eval(data) - gemspec - ensure - @@gather = nil - end - ## - # Make sure the YAML specification is properly formatted with dashes - def self.normalize_yaml_input(input) - result = input.respond_to?(:read) ? input.read : input - result = "--- " + result unless result =~ /^--- / - result - end - ## - # Sets the rubygems_version to the current RubyGems version - def mark_version - @rubygems_version = RubyGemsVersion end - ## - # Ignore unknown attributes while loading - def method_missing(sym, *a, &b) # :nodoc: - if @specification_version > CURRENT_SPECIFICATION_VERSION and - sym.to_s =~ /=$/ then - warn "ignoring #{sym} loading #{full_name}" if $DEBUG - else - super end end - ## - # Adds a development dependency named +gem+ with +requirements+ to this - # Gem. For example: - # - # spec.add_development_dependency 'jabber4r', '> 0.1', '<= 0.5' - # - # Development dependencies aren't installed by default and aren't - # activated when a gem is required. - - def add_development_dependency(gem, *requirements) - add_dependency_with_type(gem, :development, *requirements) end - ## - # Adds a runtime dependency named +gem+ with +requirements+ to this Gem. - # For example: - # - # spec.add_runtime_dependency 'jabber4r', '> 0.1', '<= 0.5' - def add_runtime_dependency(gem, *requirements) - add_dependency_with_type(gem, :runtime, *requirements) end - ## - # Adds a runtime dependency - - alias add_dependency add_runtime_dependency - ## - # Returns the full name (name-version) of this Gem. Platform information - # is included (name-version-platform) if it is specified and not the - # default Ruby platform. - def full_name - if platform == Gem::Platform::RUBY or platform.nil? then - "#{@name}-#{@version}" - else - "#{@name}-#{@version}-#{platform}" end end - ## - # Returns the full name (name-version) of this gemspec using the original - # platform. For use with legacy gems. - def original_name # :nodoc: - if platform == Gem::Platform::RUBY or platform.nil? then - "#{@name}-#{@version}" - else - "#{@name}-#{@version}-#{@original_platform}" end end - ## - # The full path to the gem (install path + full name). - def full_gem_path - path = File.join installation_path, 'gems', full_name - return path if File.directory? path - File.join installation_path, 'gems', original_name - end - ## - # The default (generated) file name of the gem. - def file_name - full_name + ".gem" - end - ## - # The directory that this gem was installed into. - def installation_path - path = File.dirname(@loaded_from).split(File::SEPARATOR)[0..-2] - path = path.join File::SEPARATOR - File.expand_path path end - ## - # Checks if this specification meets the requirement of +dependency+. - def satisfies_requirement?(dependency) - return @name == dependency.name && - dependency.version_requirements.satisfied_by?(@version) end - ## - # Returns an object you can use to sort specifications in #sort_by. - def sort_obj - [@name, @version.to_ints, @new_platform == Gem::Platform::RUBY ? -1 : 1] end - def <=>(other) # :nodoc: - sort_obj <=> other.sort_obj end - ## - # Tests specs for equality (across all attributes). - def ==(other) # :nodoc: - self.class === other && same_attributes?(other) end - alias eql? == # :nodoc: - ## - # True if this gem has the same attributes as +other+. - def same_attributes?(other) - @@attributes.each do |name, default| - return false unless self.send(name) == other.send(name) end - true - end - private :same_attributes? - def hash # :nodoc: - @@attributes.inject(0) { |hash_code, (name, default_value)| - n = self.send(name).hash - hash_code + n - } end - def to_yaml(opts = {}) # :nodoc: - mark_version - - attributes = @@attributes.map { |name,| name.to_s }.sort - attributes = attributes - %w[name version platform] - - yaml = YAML.quick_emit object_id, opts do |out| - out.map taguri, to_yaml_style do |map| - map.add 'name', @name - map.add 'version', @version - platform = case @original_platform - when nil, '' then - 'ruby' - when String then - @original_platform - else - @original_platform.to_s - end - map.add 'platform', platform - - attributes.each do |name| - map.add name, instance_variable_get("@#{name}") - end - end - end end - def yaml_initialize(tag, vals) # :nodoc: - vals.each do |ivar, val| - instance_variable_set "@#{ivar}", val - end - @original_platform = @platform # for backwards compatibility - self.platform = Gem::Platform.new @platform end - ## - # Returns a Ruby code representation of this specification, such that it - # can be eval'ed and reconstruct the same specification later. Attributes - # that still have their default values are omitted. - - def to_ruby - mark_version - result = [] - result << "# -*- encoding: utf-8 -*-" - result << nil - result << "Gem::Specification.new do |s|" - - result << " s.name = #{ruby_code name}" - result << " s.version = #{ruby_code version}" - unless platform.nil? or platform == Gem::Platform::RUBY then - result << " s.platform = #{ruby_code original_platform}" - end - result << "" - result << " s.required_rubygems_version = #{ruby_code required_rubygems_version} if s.respond_to? :required_rubygems_version=" - - handled = [ - :dependencies, - :name, - :platform, - :required_rubygems_version, - :specification_version, - :version, - ] - attributes = @@attributes.sort_by { |attr_name,| attr_name.to_s } - attributes.each do |attr_name, default| - next if handled.include? attr_name - current_value = self.send(attr_name) - if current_value != default or - self.class.required_attribute? attr_name then - result << " s.#{attr_name} = #{ruby_code current_value}" - end - end - result << nil - result << " if s.respond_to? :specification_version then" - result << " current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION" - result << " s.specification_version = #{specification_version}" - result << nil - result << " if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then" - unless dependencies.empty? then - dependencies.each do |dep| - version_reqs_param = dep.requirements_list.inspect - dep.instance_variable_set :@type, :runtime if dep.type.nil? # HACK - result << " s.add_#{dep.type}_dependency(%q<#{dep.name}>, #{version_reqs_param})" - end - end - result << " else" - unless dependencies.empty? then - dependencies.each do |dep| - version_reqs_param = dep.requirements_list.inspect - result << " s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})" - end - end - result << ' end' - result << " else" - dependencies.each do |dep| - version_reqs_param = dep.requirements_list.inspect - result << " s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})" end - result << " end" - result << "end" - result << nil - result.join "\n" - end - ## - # Checks that the specification contains all required fields, and does a - # very basic sanity check. - # - # Raises InvalidSpecificationException if the spec does not pass the - # checks.. - def validate - extend Gem::UserInteraction - normalize - if rubygems_version != RubyGemsVersion then - raise Gem::InvalidSpecificationException, - "expected RubyGems version #{RubyGemsVersion}, was #{rubygems_version}" - end - @@required_attributes.each do |symbol| - unless self.send symbol then - raise Gem::InvalidSpecificationException, - "missing value for attribute #{symbol}" - end - end - if require_paths.empty? then - raise Gem::InvalidSpecificationException, - "specification must have at least one require_path" - end - case platform - when Gem::Platform, Platform::RUBY then # ok - else - raise Gem::InvalidSpecificationException, - "invalid platform #{platform.inspect}, see Gem::Platform" end - unless Array === authors and - authors.all? { |author| String === author } then - raise Gem::InvalidSpecificationException, - 'authors must be Array of Strings' - end - # Warnings - %w[author email homepage rubyforge_project summary].each do |attribute| - value = self.send attribute - alert_warning "no #{attribute} specified" if value.nil? or value.empty? - end - alert_warning "RDoc will not be generated (has_rdoc == false)" unless - has_rdoc - alert_warning "deprecated autorequire specified" if autorequire - executables.each do |executable| - executable_path = File.join bindir, executable - shebang = File.read(executable_path, 2) == '#!' - alert_warning "#{executable_path} is missing #! line" unless shebang - end - true end - ## - # Normalize the list of files so that: - # * All file lists have redundancies removed. - # * Files referenced in the extra_rdoc_files are included in the package - # file list. - # - # Also, the summary and description are converted to a normal format. - - def normalize - if defined?(@extra_rdoc_files) and @extra_rdoc_files then - @extra_rdoc_files.uniq! - @files ||= [] - @files.concat(@extra_rdoc_files) - end - @files.uniq! if @files - end - ## - # Return a list of all gems that have a dependency on this gemspec. The - # list is structured with entries that conform to: - # - # [depending_gem, dependency, [list_of_gems_that_satisfy_dependency]] - - def dependent_gems - out = [] - Gem.source_index.each do |name,gem| - gem.dependencies.each do |dep| - if self.satisfies_requirement?(dep) then - sats = [] - find_all_satisfiers(dep) do |sat| - sats << sat - end - out << [gem, dep, sats] - end - end - end - out end - def to_s - "#<Gem::Specification name=#{@name} version=#{@version}>" - end - def add_dependency_with_type(dependency, type, *requirements) - requirements = if requirements.empty? then - Gem::Requirement.default - else - requirements.flatten - end - unless dependency.respond_to?(:name) && - dependency.respond_to?(:version_requirements) - dependency = Dependency.new(dependency, requirements, type) - end - dependencies << dependency - end - private :add_dependency_with_type - def find_all_satisfiers(dep) - Gem.source_index.each do |name,gem| - if(gem.satisfies_requirement?(dep)) then - yield gem - end - end - end - private :find_all_satisfiers - - ## - # Return a string containing a Ruby code representation of the given - # object. - - def ruby_code(obj) - case obj - when String then '%q{' + obj + '}' - when Array then obj.inspect - when Gem::Version then obj.to_s.inspect - when Date then '%q{' + obj.strftime('%Y-%m-%d') + '}' - when Time then '%q{' + obj.strftime('%Y-%m-%d') + '}' - when Numeric then obj.inspect - when true, false, nil then obj.inspect - when Gem::Platform then "Gem::Platform.new(#{obj.to_a.inspect})" - when Gem::Requirement then "Gem::Requirement.new(#{obj.to_s.inspect})" - else raise Exception, "ruby_code case not handled: #{obj.class}" - end - end - private :ruby_code - # :section: Required gemspec attributes - ## - # The version of RubyGems used to create this gem - required_attribute :rubygems_version, Gem::RubyGemsVersion - ## - # The Gem::Specification version of this gemspec - required_attribute :specification_version, CURRENT_SPECIFICATION_VERSION - ## - # This gem's name - required_attribute :name - ## - # This gem's version - required_attribute :version - ## - # The date this gem was created - required_attribute :date, TODAY - ## - # A short summary of this gem's description. Displayed in `gem list -d`. - required_attribute :summary - ## - # Paths in the gem to add to $LOAD_PATH when this gem is activated - required_attribute :require_paths, ['lib'] - # :section: Optional gemspec attributes - ## - # A contact email for this gem - attribute :email - ## - # The URL of this gem's home page - attribute :homepage - ## - # The rubyforge project this gem lives under. i.e. RubyGems' - # rubyforge_project is "rubygems". - attribute :rubyforge_project - ## - # A long description of this gem - attribute :description - ## - # Autorequire was used by old RubyGems to automatically require a file. - # It no longer is supported. - attribute :autorequire - ## - # The default executable for this gem. - attribute :default_executable - ## - # The path in the gem for executable scripts - attribute :bindir, 'bin' - ## - # True if this gem is RDoc-compliant - attribute :has_rdoc, false - ## - # True if this gem supports RDoc - alias :has_rdoc? :has_rdoc - ## - # The ruby of version required by this gem - attribute :required_ruby_version, Gem::Requirement.default - ## - # The RubyGems version required by this gem - attribute :required_rubygems_version, Gem::Requirement.default - ## - # The platform this gem runs on. See Gem::Platform for details. - attribute :platform, Gem::Platform::RUBY - ## - # The key used to sign this gem. See Gem::Security for details. - attribute :signing_key, nil - ## - # The certificate chain used to sign this gem. See Gem::Security for - # details. - attribute :cert_chain, [] - ## - # A message that gets displayed after the gem is installed - attribute :post_install_message, nil - ## - # The list of authors who wrote this gem - array_attribute :authors - ## - # Files included in this gem - array_attribute :files - ## - # Test files included in this gem - array_attribute :test_files - ## - # An ARGV-style array of options to RDoc - array_attribute :rdoc_options - ## - # Extra files to add to RDoc - array_attribute :extra_rdoc_files - ## - # Executables included in the gem - array_attribute :executables - ## - # Extensions to build when installing the gem. See - # Gem::Installer#build_extensions for valid values. - array_attribute :extensions - ## - # An array or things required by this gem. Not used by anything - # presently. - array_attribute :requirements - ## - # A list of Gem::Dependency objects this gem depends on. Only appendable. - array_attribute :dependencies - read_only :dependencies - # :section: Aliased gemspec attributes - ## - # Singular accessor for executables - attribute_alias_singular :executable, :executables - ## - # Singular accessor for authors - attribute_alias_singular :author, :authors - ## - # Singular accessor for require_paths - attribute_alias_singular :require_path, :require_paths - ## - # Singular accessor for test_files - attribute_alias_singular :test_file, :test_files - overwrite_accessor :version= do |version| - @version = Version.create(version) - end - overwrite_accessor :platform do - @new_platform end - overwrite_accessor :platform= do |platform| - if @original_platform.nil? or - @original_platform == Gem::Platform::RUBY then - @original_platform = platform - end - - case platform - when Gem::Platform::CURRENT then - @new_platform = Gem::Platform.local - @original_platform = @new_platform.to_s - - when Gem::Platform then - @new_platform = platform - - # legacy constants - when nil, Gem::Platform::RUBY then - @new_platform = Gem::Platform::RUBY - when 'mswin32' then # was Gem::Platform::WIN32 - @new_platform = Gem::Platform.new 'x86-mswin32' - when 'mswin64' then - @new_platform = Gem::Platform.new 'x86-mswin64' - when 'i586-linux' then # was Gem::Platform::LINUX_586 - @new_platform = Gem::Platform.new 'x86-linux' - when 'powerpc-darwin' then # was Gem::Platform::DARWIN - @new_platform = Gem::Platform.new 'ppc-darwin' - else - @new_platform = Gem::Platform.new platform - end - @platform = @new_platform.to_s - @new_platform end - overwrite_accessor :required_ruby_version= do |value| - @required_ruby_version = Gem::Requirement.create(value) - end - overwrite_accessor :required_rubygems_version= do |value| - @required_rubygems_version = Gem::Requirement.create(value) - end - overwrite_accessor :date= do |date| - # We want to end up with a Time object with one-day resolution. - # This is the cleanest, most-readable, faster-than-using-Date - # way to do it. - case date - when String then - @date = if /\A(\d{4})-(\d{2})-(\d{2})\Z/ =~ date then - Time.local($1.to_i, $2.to_i, $3.to_i) - else - require 'time' - Time.parse date - end - when Time then - @date = Time.local(date.year, date.month, date.day) - when Date then - @date = Time.local(date.year, date.month, date.day) - else - @date = TODAY - end - end - overwrite_accessor :date do - self.date = nil if @date.nil? # HACK Sets the default value for date - @date - end - overwrite_accessor :summary= do |str| - @summary = if str then - str.strip. - gsub(/(\w-)\n[ \t]*(\w)/, '\1\2'). - gsub(/\n[ \t]*/, " ") - end end - overwrite_accessor :description= do |str| - @description = if str then - str.strip. - gsub(/(\w-)\n[ \t]*(\w)/, '\1\2'). - gsub(/\n[ \t]*/, " ") - end - end - overwrite_accessor :default_executable do - begin - if defined?(@default_executable) and @default_executable - result = @default_executable - elsif @executables and @executables.size == 1 - result = Array(@executables).first - else - result = nil - end - result - rescue - nil - end - end - overwrite_accessor :test_files do - # Handle the possibility that we have @test_suite_file but not - # @test_files. This will happen when an old gem is loaded via - # YAML. - if defined? @test_suite_file then - @test_files = [@test_suite_file].flatten - @test_suite_file = nil - end - if defined?(@test_files) and @test_files then - @test_files else - @test_files = [] end end - overwrite_accessor :files do - result = [] - result.push(*@files) if defined?(@files) - result.push(*@test_files) if defined?(@test_files) - result.push(*(add_bindir(@executables))) - result.push(*@extra_rdoc_files) if defined?(@extra_rdoc_files) - result.push(*@extensions) if defined?(@extensions) - result.uniq.compact end end end @@ -11,9 +11,9 @@ require 'rubygems/remote_fetcher' # @fetcher = Gem::FakeFetcher.new # @fetcher.data['http://gems.example.com/yaml'] = source_index.to_yaml # Gem::RemoteFetcher.fetcher = @fetcher -# # # invoke RubyGems code -# # paths = @fetcher.paths # assert_equal 'http://gems.example.com/yaml', paths.shift # assert paths.empty?, paths.join(', ') @@ -0,0 +1,30 @@ @@ -1,6 +1,6 @@ # -# This file defines a $log variable for logging, and a time() method for recording timing -# information. # #-- # Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others. @@ -8,18 +8,21 @@ # See LICENSE.txt for permissions. #++ $log = Object.new -def $log.debug(str) - STDERR.puts str end -def time(msg, width=25) - t = Time.now - return_value = yield - elapsed = Time.now.to_f - t.to_f - elapsed = sprintf("%3.3f", elapsed) - $log.debug "#{msg.ljust(width)}: #{elapsed}s" - return_value end @@ -12,6 +12,11 @@ require 'rubygems/user_interaction' ## # An Uninstaller. class Gem::Uninstaller @@ -46,8 +51,17 @@ class Gem::Uninstaller @force_ignore = options[:ignore] @bin_dir = options[:bin_dir] spec_dir = File.join @gem_home, 'specifications' @source_index = Gem::SourceIndex.from_gems_in spec_dir end ## @@ -56,9 +70,10 @@ class Gem::Uninstaller def uninstall list = @source_index.find_name @gem, @version if list.empty? then - raise Gem::InstallError, "Unknown gem #{@gem} #{@version}" elsif list.size > 1 and @force_all then remove_all list.dup @@ -91,8 +106,8 @@ class Gem::Uninstaller hook.call self end - specs.each { |s| remove_executables s } - remove spec, specs Gem.post_uninstall_hooks.each do |hook| hook.call self @@ -105,29 +120,29 @@ class Gem::Uninstaller # Removes installed executables and batch files (windows only) for # +gemspec+. - def remove_executables(gemspec) - return if gemspec.nil? - if gemspec.executables.size > 0 then - bindir = @bin_dir ? @bin_dir : (Gem.bindir @gem_home) - list = @source_index.find_name(gemspec.name).delete_if { |spec| - spec.version == gemspec.version } - executables = gemspec.executables.clone - list.each do |spec| - spec.executables.each do |exe_name| - executables.delete(exe_name) end end - return if executables.size == 0 answer = if @force_executables.nil? then ask_yes_no("Remove executables:\n" \ - "\t#{gemspec.executables.join(", ")}\n\nin addition to the gem?", true) # " # appease ruby-mode - don't ask else @force_executables @@ -138,7 +153,7 @@ class Gem::Uninstaller else raise Gem::FilePermissionError, bindir unless File.writable? bindir - gemspec.executables.each do |exe_name| say "Removing #{exe_name}" FileUtils.rm_f File.join(bindir, exe_name) FileUtils.rm_f File.join(bindir, "#{exe_name}.bat") @@ -169,7 +184,8 @@ class Gem::Uninstaller "Uninstallation aborted due to dependent gem(s)" end - unless path_ok? spec then e = Gem::GemNotInHomeException.new \ "Gem is not installed in directory #{@gem_home}" e.spec = spec @@ -210,9 +226,12 @@ class Gem::Uninstaller list.delete spec end - def path_ok?(spec) - full_path = File.join @gem_home, 'gems', spec.full_name - original_path = File.join @gem_home, 'gems', spec.original_name full_path == spec.full_gem_path || original_path == spec.full_gem_path end @@ -221,6 +240,7 @@ class Gem::Uninstaller return true if @force_ignore deplist = Gem::DependencyList.from_source_index @source_index deplist.ok_to_remove?(spec.full_name) || ask_if_ok(spec) end @@ -4,357 +4,387 @@ # See LICENSE.txt for permissions. #++ -module Gem - ## - # Module that defines the default UserInteraction. Any class including this - # module will have access to the +ui+ method that returns the default UI. - module DefaultUserInteraction - ## - # The default UI is a class variable of the singleton class for this - # module. - @ui = nil - ## - # Return the default UI. - def self.ui - @ui ||= Gem::ConsoleUI.new - end - ## - # Set the default UI. If the default UI is never explicitly set, a simple - # console based UserInteraction will be used automatically. - def self.ui=(new_ui) - @ui = new_ui - end - ## - # Use +new_ui+ for the duration of +block+. - - def self.use_ui(new_ui) - old_ui = @ui - @ui = new_ui - yield - ensure - @ui = old_ui - end - ## - # See DefaultUserInteraction::ui - def ui - DefaultUserInteraction.ui - end - ## - # See DefaultUserInteraction::ui= - def ui=(new_ui) - DefaultUserInteraction.ui = new_ui - end - ## - # See DefaultUserInteraction::use_ui - def use_ui(new_ui, &block) - DefaultUserInteraction.use_ui(new_ui, &block) - end - end ## - # Make the default UI accessable without the "ui." prefix. Classes - # including this module may use the interaction methods on the default UI - # directly. Classes may also reference the ui and ui= methods. - # - # Example: - # - # class X - # include Gem::UserInteraction - # - # def get_answer - # n = ask("What is the meaning of life?") - # end - # end - - module UserInteraction - - include DefaultUserInteraction - - [:alert, - :alert_error, - :alert_warning, - :ask, - :ask_yes_no, - :choose_from_list, - :say, - :terminate_interaction ].each do |methname| - class_eval %{ - def #{methname}(*args) - ui.#{methname}(*args) - end - }, __FILE__, __LINE__ - end - end ## - # StreamUI implements a simple stream based user interface. - class StreamUI - attr_reader :ins, :outs, :errs - def initialize(in_stream, out_stream, err_stream=STDERR) - @ins = in_stream - @outs = out_stream - @errs = err_stream - end - ## - # Choose from a list of options. +question+ is a prompt displayed above - # the list. +list+ is a list of option strings. Returns the pair - # [option_name, option_index]. - def choose_from_list(question, list) - @outs.puts question - list.each_with_index do |item, index| - @outs.puts " #{index+1}. #{item}" end - @outs.print "> " - @outs.flush - result = @ins.gets - return nil, nil unless result - result = result.strip.to_i - 1 - return list[result], result end - ## - # Ask a question. Returns a true for yes, false for no. If not connected - # to a tty, raises an exception if default is nil, otherwise returns - # default. - - def ask_yes_no(question, default=nil) - unless @ins.tty? then - if default.nil? then - raise Gem::OperationNotSupportedError, - "Not connected to a tty and no default specified" - else - return default - end - end - qstr = case default - when nil - 'yn' - when true - 'Yn' - else - 'yN' - end - - result = nil - - while result.nil? - result = ask("#{question} [#{qstr}]") - result = case result - when /^[Yy].*/ - true - when /^[Nn].*/ - false - when /^$/ - default - else - nil - end end - return result end - ## - # Ask a question. Returns an answer if connected to a tty, nil otherwise. - def ask(question) - return nil if not @ins.tty? - @outs.print(question + " ") - @outs.flush - result = @ins.gets - result.chomp! if result - result - end - ## - # Display a statement. - def say(statement="") - @outs.puts statement - end - ## - # Display an informational alert. Will ask +question+ if it is not nil. - def alert(statement, question=nil) - @outs.puts "INFO: #{statement}" - ask(question) if question - end - ## - # Display a warning in a location expected to get error messages. Will - # ask +question+ if it is not nil. - def alert_warning(statement, question=nil) - @errs.puts "WARNING: #{statement}" - ask(question) if question - end - ## - # Display an error message in a location expected to get error messages. - # Will ask +question+ if it is not nil. - def alert_error(statement, question=nil) - @errs.puts "ERROR: #{statement}" - ask(question) if question - end - ## - # Terminate the application with exit code +status+, running any exit - # handlers that might have been defined. - def terminate_interaction(status = 0) - raise Gem::SystemExitException, status - end - ## - # Return a progress reporter object chosen from the current verbosity. - - def progress_reporter(*args) - case Gem.configuration.verbose - when nil, false - SilentProgressReporter.new(@outs, *args) - when true - SimpleProgressReporter.new(@outs, *args) - else - VerboseProgressReporter.new(@outs, *args) - end - end - ## - # An absolutely silent progress reporter. - class SilentProgressReporter - attr_reader :count - def initialize(out_stream, size, initial_message, terminal_message = nil) - end - def updated(message) - end - def done - end end - ## - # A basic dotted progress reporter. - class SimpleProgressReporter - include DefaultUserInteraction - attr_reader :count - def initialize(out_stream, size, initial_message, - terminal_message = "complete") - @out = out_stream - @total = size - @count = 0 - @terminal_message = terminal_message - @out.puts initial_message - end - ## - # Prints out a dot and ignores +message+. - def updated(message) - @count += 1 - @out.print "." - @out.flush - end - ## - # Prints out the terminal message. - def done - @out.puts "\n#{@terminal_message}" - end end ## - # A progress reporter that prints out messages about the current progress. - class VerboseProgressReporter - include DefaultUserInteraction - attr_reader :count - def initialize(out_stream, size, initial_message, - terminal_message = 'complete') - @out = out_stream - @total = size - @count = 0 - @terminal_message = terminal_message - @out.puts initial_message - end - ## - # Prints out the position relative to the total and the +message+. - def updated(message) - @count += 1 - @out.puts "#{@count}/#{@total}: #{message}" - end - ## - # Prints out the terminal message. - def done - @out.puts @terminal_message - end end - end - ## - # Subclass of StreamUI that instantiates the user interaction using STDIN, - # STDOUT, and STDERR. - class ConsoleUI < StreamUI - def initialize - super(STDIN, STDOUT, STDERR) end - end - ## - # SilentUI is a UI choice that is absolutely silent. - class SilentUI - def method_missing(sym, *args, &block) - self end end end @@ -6,10 +6,17 @@ require 'find' -require 'rubygems/digest/md5' require 'rubygems/format' require 'rubygems/installer' ## # Validator performs various gem file and gem database validation @@ -33,7 +40,7 @@ class Gem::Validator sum_data = gem_data.gsub(/MD5SUM = "([a-z0-9]+)"/, "MD5SUM = \"#{"F" * 32}\"") - unless Gem::MD5.hexdigest(sum_data) == $1.to_s then raise Gem::VerificationError, 'invalid checksum for gem file' end end @@ -48,7 +55,7 @@ class Gem::Validator gem_data = file.read verify_gem gem_data end - rescue Errno::ENOENT raise Gem::VerificationError, "missing gem file #{gem_path}" end @@ -56,13 +63,11 @@ class Gem::Validator def find_files_for_gem(gem_directory) installed_files = [] - Find.find(gem_directory) {|file_name| - fn = file_name.slice((gem_directory.size)..(file_name.size-1)).sub(/^\//, "") - if(!(fn =~ /CVS/ || File.directory?(fn) || fn == "")) then - installed_files << fn - end - - } installed_files end @@ -81,53 +86,82 @@ class Gem::Validator # # returns a hash of ErrorData objects, keyed on the problem gem's name. - def alien - errors = {} Gem::SourceIndex.from_installed_gems.each do |gem_name, gem_spec| - errors[gem_name] ||= [] - - gem_path = File.join(Gem.dir, "cache", gem_spec.full_name) + ".gem" - spec_path = File.join(Gem.dir, "specifications", gem_spec.full_name) + ".gemspec" - gem_directory = File.join(Gem.dir, "gems", gem_spec.full_name) - - installed_files = find_files_for_gem(gem_directory) unless File.exist? spec_path then - errors[gem_name] << ErrorData.new(spec_path, "Spec file doesn't exist for installed gem") end begin verify_gem_file(gem_path) open gem_path, Gem.binary_mode do |file| format = Gem::Format.from_file_by_path(gem_path) - format.file_entries.each do |entry, data| - # Found this file. Delete it from list - installed_files.delete remove_leading_dot_dir(entry['path']) - next unless data # HACK `gem check -a mkrf` - open File.join(gem_directory, entry['path']), Gem.binary_mode do |f| - unless Gem::MD5.hexdigest(f.read).to_s == - Gem::MD5.hexdigest(data).to_s then - errors[gem_name] << ErrorData.new(entry['path'], "installed file doesn't match original from gem") end end end end rescue Gem::VerificationError => e - errors[gem_name] << ErrorData.new(gem_path, e.message) end - # Clean out directories that weren't explicitly included in the gemspec - # FIXME: This still allows arbitrary incorrect directories. - installed_files.delete_if {|potential_directory| - File.directory?(File.join(gem_directory, potential_directory)) - } - if(installed_files.size > 0) then - errors[gem_name] << ErrorData.new(gem_path, "Unmanaged files in gem: #{installed_files.inspect}") - end end errors @@ -167,7 +201,7 @@ class Gem::Validator def unit_test(gem_spec) start_dir = Dir.pwd Dir.chdir(gem_spec.full_gem_path) - $: << File.join(Gem.dir, "gems", gem_spec.full_name) # XXX: why do we need this gem_spec when we've already got 'spec'? test_files = gem_spec.test_files @@ -200,7 +234,6 @@ class Gem::Validator Dir.chdir(start_dir) end - private def remove_leading_dot_dir(path) path.sub(/^\.\//, "") end @@ -4,27 +4,81 @@ # See LICENSE.txt for permissions. #++ -require 'rubygems' - ## -# The Version class processes string versions into comparable values class Gem::Version include Comparable - attr_reader :ints attr_reader :version - ## - # Returns true if +version+ is a valid version string. - def self.correct?(version) - case version - when Integer, /\A\s*(\d+(\.-?\d+)*)*\s*\z/ then true - else false - end end ## @@ -47,7 +101,7 @@ class Gem::Version ## # Constructs a Version from the +version+ string. A version string is a - # series of digits separated by dots. def initialize(version) raise ArgumentError, "Malformed version number string #{version}" unless @@ -60,46 +114,43 @@ class Gem::Version "#<#{self.class} #{@version.inspect}>" end # Dump only the raw version string, not the complete object def marshal_dump [@version] end # Load custom marshal format def marshal_load(array) self.version = array[0] end ## # Strip ignored trailing zeros. def normalize - @ints = build_array_from_version_string - - return if @ints.length == 1 - - @ints.pop while @ints.last == 0 - - @ints = [0] if @ints.empty? end ## # Returns the text representation of the version - # - # return:: [String] version as string - # def to_s @version end - ## - # Returns an integer array representation of this Version. - - def to_ints - normalize unless @ints - @ints - end - def to_yaml_properties ['@version'] end @@ -109,6 +160,23 @@ class Gem::Version normalize end def yaml_initialize(tag, values) self.version = values['version'] end @@ -120,7 +188,14 @@ class Gem::Version def <=>(other) return nil unless self.class === other return 1 unless other - @ints <=> other.ints end ## @@ -135,24 +210,33 @@ class Gem::Version @version.hash end - # Return a new version object where the next to the last revision - # number is one greater. (e.g. 5.3.1 => 5.4) def bump - ints = build_array_from_version_string - ints.pop if ints.size > 1 - ints[-1] += 1 - self.class.new(ints.join(".")) end - def build_array_from_version_string - @version.to_s.scan(/\d+/).map { |s| s.to_i } end - private :build_array_from_version_string #:stopdoc: require 'rubygems/requirement' # Gem::Requirement's original definition is nested in Version. # Although an inappropriate place, current gems specs reference the nested # class name explicitly. To remain compatible with old software loading @@ -41,6 +41,7 @@ module Gem::VersionOption "Specify version of gem to #{task}", *wrap) do |value, options| options[:version] = value end end |