Module: Roast::Tools::Grep

Extended by:
Grep
Included in:
Grep
Defined in:
lib/roast/tools/grep.rb

Constant Summary collapse

MAX_RESULT_LINES =
100

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

Add this method to be included in other classes



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/roast/tools/grep.rb', line 14

def included(base)
  base.class_eval do
    function(
      :grep,
      'Search for a string in the project using `grep -rni "#{@search_string}" .` in the project root',
      string: { type: "string", description: "The string to search for" },
    ) do |params|
      Roast::Tools::Grep.call(params[:string]).tap do |result|
        Roast::Helpers::Logger.debug(result) if ENV["DEBUG"]
      end
    end
  end
end

Instance Method Details

#call(string) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/roast/tools/grep.rb', line 29

def call(string)
  Roast::Helpers::Logger.info("🔍 Grepping for string: #{string}\n")
  # Escape regex special characters in strings with curly braces
  # Example: "import {render}" becomes "import \{render\}"
  escaped_string = string.gsub(/(\{|\})/, '\\\\\\1')
  %x(rg -C 4 --trim --color=never --heading -F -- "#{escaped_string}" . | head -n #{MAX_RESULT_LINES})
rescue StandardError => e
  "Error grepping for string: #{e.message}".tap do |error_message|
    Roast::Helpers::Logger.error(error_message + "\n")
    Roast::Helpers::Logger.debug(e.backtrace.join("\n") + "\n") if ENV["DEBUG"]
  end
end