Sha256: b0ec8c7205324da487804e1c368c55b21eb2c37d2dd58b147328f5d27076d799

Contents?: true

Size: 1.31 KB

Versions: 1

Compression:

Stored size: 1.31 KB

Contents

require 'stringio'

class Gem::Commands::GrepCommand < Gem::Command
  class CapturedUI < Gem::StreamUI
    def initialize
      super($stdin, StringIO.new, $stderr, false)
    end
  end

  def description
    'Grep the gem for a given name or grep the file for a given require path'
  end

  def initialize
    super('grep', description)
  end

  def execute
    if options[:build_args].empty?
      alert_error('No pattern specified')
      terminate_interaction(1)
    end

    exec(*grep_command(options[:args], options[:build_args]))
  end

  def grep_command path_args, grep_args
    [grep_name, *grep_args, *grep_default_args, capture_path(*path_args)]
  end

  private
  def capture_path *path_args
    ui = CapturedUI.new
    Gem::DefaultUserInteraction.use_ui(ui) do
      Gem::GemRunner.new.run(['path', *path_args])
    end
    ui.outs.string.strip
  end

  def grep_name
    @grep_name ||= ENV['GEM_GREP'] || 'grep'
  end

  def grep_default_args
    case grep_name
    when 'rg'
      []
    else
      ['-nR']
    end
  end

  def exec cmd, *args
    quoted_args = args.map(&method(:quote))
    say("#{cmd} #{quoted_args.join(' ')}")
    super
  end

  def quote arg
    escaped = arg.gsub('\\', '\\\\\\').gsub("'", '\'').gsub('"', '\\"')

    if escaped.include?(' ')
      "'#{escaped}'"
    else
      escaped
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
gem-grep-0.7.0 lib/rubygems/commands/grep_command.rb