Class: Legion::CLI::Chat::Tools::SearchContent

Inherits:
RubyLLM::Tool
  • Object
show all
Defined in:
lib/legion/cli/chat/tools/search_content.rb

Instance Method Summary collapse

Instance Method Details

#execute(pattern:, directory: nil, glob: nil) ⇒ Object

rubocop:disable Metrics/CyclomaticComplexity



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/legion/cli/chat/tools/search_content.rb', line 16

def execute(pattern:, directory: nil, glob: nil) # rubocop:disable Metrics/CyclomaticComplexity
  dir = File.expand_path(directory || Dir.pwd)
  return "Error: directory not found: #{dir}" unless Dir.exist?(dir)

  file_pattern = File.join(dir, glob || '**/*')
  files = Dir.glob(file_pattern).select { |f| File.file?(f) }
  regex = Regexp.new(pattern)

  results = []
  files.each do |file|
    begin
      File.readlines(file, encoding: 'utf-8').each_with_index do |line, i|
        if line.match?(regex)
          relative = file.sub("#{dir}/", '')
          results << "#{relative}:#{i + 1}: #{line.rstrip}"
        end
      rescue ArgumentError => e
        Legion::Logging.debug("SearchContent#execute encoding error in #{file}: #{e.message}") if defined?(Legion::Logging)
        next
      end
    rescue StandardError => e
      Legion::Logging.debug("SearchContent#execute skipping #{file}: #{e.message}") if defined?(Legion::Logging)
      next
    end
    break if results.length >= 50
  end

  return "No matches for /#{pattern}/ in #{dir}" if results.empty?

  "#{results.length} matches:\n#{results.join("\n")}"
rescue RegexpError => e
  Legion::Logging.warn("SearchContent#execute invalid regex #{pattern}: #{e.message}") if defined?(Legion::Logging)
  "Error: invalid regex: #{e.message}"
rescue StandardError => e
  Legion::Logging.warn("SearchContent#execute failed: #{e.message}") if defined?(Legion::Logging)
  "Error searching: #{e.message}"
end