gem_commands.rb

来自「Amarok是一款在LINUX或其他类UNIX操作系统中运行的音频播放器软件。 」· RB 代码 · 共 1,443 行 · 第 1/3 页

RB
1,443
字号
#!/usr/bin/env ruby#--# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.# All rights reserved.# See LICENSE.txt for permissions.#++module Gem  class CommandLineError < Gem::Exception; end  ####################################################################  # The following mixin methods aid in the retrieving of information  # from the command line.  #  module CommandAids    # 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?        fail Gem::CommandLineError,          "Please specify a gem name on the command line (e.g. gem build GEMNAME)"      end      if args.size > 1        fail 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    # True if +long+ begins with the characters from +short+.    def begins?(long, short)      return false if short.nil?      long[0, short.length] == short    end  end  ####################################################################  # Mixin methods for handling the local/remote command line options.  #  module LocalRemoteOptions    # Add the local/remote options to the command line parser.    def add_local_remote_options      add_option('-l', '--local',	'Restrict operations to the LOCAL domain (default)') do	|value, options|        options[:domain] = :local      end      add_option('-r', '--remote',	'Restrict operations to the REMOTE domain') do	|value, options|        options[:domain] = :remote      end      add_option('-b', '--both',	'Allow LOCAL and REMOTE operations') do	|value, options|        options[:domain] = :both      end    end    # Is local fetching enabled?    def local?      options[:domain] == :local || options[:domain] == :both    end    # Is remote fetching enabled?    def remote?      options[:domain] == :remote || options[:domain] == :both    end  end  ####################################################################  # Mixin methods and OptionParser options specific to the gem install  # command.  #  module InstallUpdateOptions    # Add the install/update options to the option parser.    def add_install_update_options      add_option('-i', '--install-dir DIR',	'Gem repository directory to get installed gems.') do 	|value, options|        options[:install_dir] = File.expand_path(value)      end      add_option('-d', '--[no-]rdoc', 	'Generate RDoc documentation for the gem on install') do	|value, options|        options[:generate_rdoc] = value      end      add_option('--[no-]ri', 	'Generate RI documentation for the gem on install') do	|value, options|        options[:generate_ri] = value      end      add_option('-f', '--[no-]force', 	'Force gem to install, bypassing dependency checks') do 	|value, options|        options[:force] = value      end      add_option('-t', '--[no-]test', 	'Run unit tests prior to installation') do 	|value, options|        options[:test] = value      end      add_option('-w', '--[no-]wrappers', 	'Use bin wrappers for executables',	'Not available on dosish platforms') do 	|value, options|        options[:wrappers] = value      end      add_option('-P', '--trust-policy POLICY', 	'Specify gem trust policy.') do 	|value, options|        options[:security_policy] = value      end      add_option('--ignore-dependencies',	'Do not install any required dependent gems') do 	|value, options|	options[:ignore_dependencies] = value      end      add_option('-y', '--include-dependencies',	'Unconditionally install the required dependent gems') do 	|value, options|	options[:include_dependencies] = value      end    end        # Default options for the gem install command.    def install_update_defaults_str      '--rdoc --no-force --no-test --wrappers'    end  end  ####################################################################  # Mixin methods for the version command.  #  module VersionOption    # Add the options to the option parser.    def add_version_option(taskname)      add_option('-v', '--version VERSION', 	"Specify version of gem to #{taskname}") do 	|value, options|        options[:version] = value      end    end  end  ####################################################################  # Gem install command.  #  class InstallCommand < Command    include CommandAids    include VersionOption    include LocalRemoteOptions    include InstallUpdateOptions    def initialize      super(        'install',        'Install a gem into the local repository',        {          :domain => :both,           :generate_rdoc => true,          :generate_ri   => true,          :force => false,           :test => false,           :wrappers => true,          :version => "> 0",          :install_dir => Gem.dir,	  :security_policy => nil,        })      add_version_option('install')      add_local_remote_options      add_install_update_options    end        def usage      "#{program_name} GEMNAME [options]   or: #{program_name} GEMNAME [options] -- --build-flags"    end    def arguments      "GEMNAME   name of gem to install"    end    def defaults_str      "--both --version '> 0' --rdoc --ri --no-force --no-test\n" +      "--install-dir #{Gem.dir}"    end    def execute      ENV['GEM_PATH'] = options[:install_dir]      if(options[:args].empty?)        fail Gem::CommandLineError,          "Please specify a gem name on the command line (e.g. gem build GEMNAME)"      end      options[:args].each do |gem_name|        if local?          begin	    entries = []	    if(File.exist?(gem_name) && !File.directory?(gem_name))              entries << gem_name	    else              filepattern = gem_name + "*.gem"              entries = Dir[filepattern]             end            unless entries.size > 0              if options[:domain] == :local                alert_error "Local gem file not found: #{filepattern}"              end            else              result = Gem::Installer.new(entries.last, options).install(		options[:force],		options[:install_dir])              installed_gems = [result].flatten              say "Successfully installed #{installed_gems[0].name}, " +		"version #{installed_gems[0].version}" if installed_gems            end          rescue LocalInstallationError => e            say " -> Local installation can't proceed: #{e.message}"          rescue Gem::LoadError => e            say " -> Local installation can't proceed due to LoadError: #{e.message}"          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}[.gem]: #{e.message}"            return          end        end                if remote? && installed_gems.nil?          installer = Gem::RemoteInstaller.new(options)          installed_gems = installer.install(	    gem_name,	    options[:version],	    options[:force],	    options[:install_dir])	  if installed_gems	    installed_gems.compact!	    installed_gems.each do |spec|	      say "Successfully installed #{spec.full_name}"	    end	  end        end                unless installed_gems          alert_error "Could not install a local " +            "or remote copy of the gem: #{gem_name}"          terminate_interaction(1)        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]          installed_gems.each do |gem|            Gem::DocManager.new(gem, options[:rdoc_args]).generate_ri          end        end        if options[:generate_rdoc]          installed_gems.each do |gem|            Gem::DocManager.new(gem, options[:rdoc_args]).generate_rdoc          end        end        if options[:test]          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)            unless result.passed?              unless ask_yes_no("...keep Gem?", true) then                Gem::Uninstaller.new(spec.name, spec.version.version).uninstall              end            end          end        end      end    end      end    ####################################################################  class UninstallCommand < Command    include VersionOption    include CommandAids    def initialize      super('uninstall', 'Uninstall a gem from the local repository', {:version=>"> 0"})      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_version_option('uninstall')    end    def defaults_str      "--version '> 0' --no-force"    end        def usage      "#{program_name} GEMNAME"    end    def arguments      "GEMNAME   name of gem to uninstall"    end    def execute      gem_name = get_one_gem_name      Gem::Uninstaller.new(gem_name, options).uninstall    end  end        class CertCommand < Command    include CommandAids        def initialize      super(        'cert',        'Adjust RubyGems certificate settings',        {        })      add_option('-a', '--add CERT', 'Add a trusted certificate.') do |value, options|        cert = OpenSSL::X509::Certificate.new(File.read(value))        Gem::Security.add_trusted_cert(cert)        puts "Added #{cert.subject.to_s}"      end      add_option('-l', '--list', 'List trusted certificates.') do |value, options|        glob_str = File::join(Gem::Security::OPT[:trust_dir], '*.pem')        Dir::glob(glob_str) do |path|          cert = OpenSSL::X509::Certificate.new(File.read(path))          # this could proably be formatted more gracefully          puts cert.subject.to_s        end      end      add_option('-r', '--remove STRING', 'Remove trusted certificates containing STRING.') do |value, options|        trust_dir = Gem::Security::OPT[:trust_dir]        glob_str = File::join(trust_dir, '*.pem')        Dir::glob(glob_str) do |path|          cert = OpenSSL::X509::Certificate.new(File.read(path))          if cert.subject.to_s.downcase.index(value)            puts "Removing '#{cert.subject.to_s}'"            File.unlink(path)          end        end      end      add_option('-b', '--build EMAIL_ADDR',	'Build private key and self-signed certificate for EMAIL_ADDR.'	) do |value, options|        vals = Gem::Security::build_self_signed_cert(value)        File::chmod(0600, vals[:key_path])        puts "Public Cert: #{vals[:cert_path]}",             "Private Key: #{vals[:key_path]}",             "Don't forget to move the key file to somewhere private..."      end      add_option('-C', '--certificate CERT',	'Certificate for --sign command.'	) do |value, options|        cert = OpenSSL::X509::Certificate.new(File.read(value))        Gem::Security::OPT[:issuer_cert] = cert      end      add_option('-K', '--private-key KEY',	'Private key for --sign command.'	) do |value, options|        key = OpenSSL::PKey::RSA.new(File.read(value))        Gem::Security::OPT[:issuer_key] = key      end      add_option('-s', '--sign NEWCERT', 	'Sign a certificate with my key and certificate.'	) do |value, options|        cert = OpenSSL::X509::Certificate.new(File.read(value))        my_cert = Gem::Security::OPT[:issuer_cert]        my_key = Gem::Security::OPT[:issuer_key]        cert = Gem::Security.sign_cert(cert, my_key, my_cert)        File::open(value, 'wb') { |file| file.write(cert.to_pem) }      end    end    def execute    end  end  ####################################################################  class DependencyCommand < Command    include VersionOption    include CommandAids    def initialize      super('dependency',	'Show the dependencies of an installed gem',	{:version=>"> 0"})      add_version_option('uninstall')      add_option('-r', '--[no-]reverse-dependencies',	'Include reverse dependencies in the output'	) do |value, options|        options[:reverse_dependencies] = value      end      add_option('-p', '--pipe', "Pipe Format (name --version ver)") do |value, options|	options[:pipe_format] = value      end    end    def defaults_str      "--version '> 0' --no-reverse"    end        def usage      "#{program_name} GEMNAME"    end    def arguments      "GEMNAME   name of gems to show"    end    def execute      specs = {}      srcindex = SourceIndex.from_installed_gems      options[:args] << '.' if options[:args].empty?      options[:args].each do |name|	speclist = srcindex.search(name, options[:version])	if speclist.empty?	  say "No match found for #{name} (#{options[:version]})"	else	  speclist.each do |spec|	    specs[spec.full_name] = spec	  end	end      end      reverse = Hash.new { |h, k| h[k] = [] }      if options[:reverse_dependencies]	specs.values.each do |spec|	  reverse[spec.full_name] = find_reverse_dependencies(spec, srcindex)	end

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?