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.



346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/syntax_tree/cli.rb', line 346

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.



344
345
346
# File 'lib/syntax_tree/cli.rb', line 344

def search
  @search
end

Instance Method Details

#run(item) ⇒ Object



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/syntax_tree/cli.rb', line 359

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