Class: Ask::Tools::Grep
- Inherits:
-
Ask::Tool
- Object
- Ask::Tool
- Ask::Tools::Grep
- Defined in:
- lib/ask/tools/shell/grep.rb
Overview
Search file contents using a regex pattern.
Constant Summary collapse
- MAX_MATCHES =
100- MAX_LINE_LENGTH =
500- EXCLUDE_DIRS =
%w[.git node_modules vendor .bundle tmp log].freeze
Instance Method Summary collapse
Instance Method Details
#execute(pattern:, path: nil, include: nil) ⇒ Object
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 53 54 55 56 57 58 59 60 |
# File 'lib/ask/tools/shell/grep.rb', line 19 def execute(pattern:, path: nil, include: nil) base = path ? File.(path) : Dir.pwd unless File.directory?(base) return Ask::Result.error(message: "Directory does not exist: #{base}") end begin regex = Regexp.new(pattern, Regexp::IGNORECASE) rescue RegexpError => e return Ask::Result.error(message: "Invalid regex: #{e.}") end matches = [] glob = include || "**/*" Dir.glob(File.join(base, glob)).each do |file| next unless File.file?(file) next if EXCLUDE_DIRS.any? { |d| file.include?("/#{d}/") } begin File.readlines(file).each_with_index do |line, i| next unless regex.match?(line) line_text = line.chomp line_text = line_text[0, MAX_LINE_LENGTH] + "..." if line_text.length > MAX_LINE_LENGTH matches << "#{file}:#{i + 1}: #{line_text}" if matches.size >= MAX_MATCHES return Ask::Result.ok(data: matches.join("\n") + "\n... (too many matches)", metadata: { count: matches.size, truncated: true }) end end rescue => e matches << "#{file}: error reading: #{e.}" end end if matches.empty? return Ask::Result.error(message: "No matches found for: #{pattern}") end Ask::Result.ok(data: matches.join("\n"), metadata: { count: matches.size, truncated: false }) end |