Class: SyntaxTree::CLI::Search

Inherits:
Action
  • Object
show all
Defined in:
lib/syntax_tree/cli.rb

Overview

An action of the CLI that searches for the given pattern matching pattern in the given files.

Instance Attribute Summary collapse

Attributes inherited from Action

#options

Instance Method Summary collapse

Methods inherited from Action

#failure, #success

Constructor Details

#initialize(query) ⇒ Search

Returns a new instance of Search.



260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/syntax_tree/cli.rb', line 260

def initialize(query)
  query = File.read(query) if File.readable?(query)
  pattern =
    begin
      Pattern.new(query).compile
    rescue Pattern::CompilationError => error
      warn(error.message)
      exit(1)
    end

  @search = SyntaxTree::Search.new(pattern)
end

Instance Attribute Details

#searchObject (readonly)

Returns the value of attribute search.



258
259
260
# File 'lib/syntax_tree/cli.rb', line 258

def search
  @search
end

Instance Method Details

#run(item) ⇒ Object



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/syntax_tree/cli.rb', line 273

def run(item)
  search.scan(item.handler.parse(item.source)) do |node|
    location = node.location
    line = location.start_line

    bold_range =
      if line == location.end_line
        location.start_column...location.end_column
      else
        location.start_column..
      end

    source = item.source.lines[line - 1].chomp
    source[bold_range] = Color.bold(source[bold_range]).to_s

    puts("#{item.filepath}:#{line}:#{location.start_column}: #{source}")
  end
end