Module: XPGrep::CLI

Defined in:
lib/xpgrep.rb

Defined Under Namespace

Classes: Options, UI

Class Method Summary collapse

Class Method Details

.parse_opts!(args = ARGV) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/xpgrep.rb', line 81

def self.parse_opts!(args = ARGV)
  @options = Options.instance
  OptionParser.new do |o|
    o.banner =
      "Usage: #{$0} [options] <xpath-or-css-expr> <file [file ...]>"
    o.on('-H', '--with-filename', "print the filename for each match") {
      @options.print_filename = true
    }
    o.on('-h', '--no-filename', "suppress printing filename for matches") {
      @options.print_filename = false
    }
    o.on('-l', '--files-with-matches',
         "only print filenames containing matches") {
      @options.files_with_matches!
    }
    o.on('-L', '--files-without-match',
         "only print filenames containing no match") {
      @options.files_without_match!
    }
    o.on('-e', '--extract ATTR') {|attr| @options[:attribute] = attr }
    o.on_tail('--help', "print this message and exit") { puts o; exit }
  end.parse!(args)
end

.run(args = ARGV) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/xpgrep.rb', line 105

def self.run(args = ARGV)
  parse_opts!
  expr = args.shift
  @ui = UI.new(args.size)
  args.each do |fn|
    begin
      File.open(fn) do |file|
        nodes = XPGrep.grep(expr, file)
        if @options.files_with_matches
          @ui.puts fn unless nodes.empty?
        elsif @options.files_without_match
          @ui.puts fn if nodes.empty?
        else
          nodes.each {|node| @ui.print_match(fn, node) }
        end
      end
    rescue Errno::ENOENT, Errno::EISDIR => ex
      @ui.perror ex
      next
    end
  end
end