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



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/xpgrep.rb', line 87

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>',
         'extract the value of the given attribute') {|attr|
      @options[:attribute] = attr
    }
    o.on('-t', '--html', 'parse file(s) as HTML') {
      @options.parse_as_html = true
    }
    o.on_tail('--help', "print this message and exit") { puts o; exit }
  end.parse!(args)
end

.run(args = ARGV) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/xpgrep.rb', line 117

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