Class: Clacky::Tools::Grep
Constant Summary collapse
- MAX_FILE_SIZE =
Maximum file size to search (1MB)
1_048_576- MAX_LINE_LENGTH =
Maximum line length to display (to avoid huge outputs)
500
Instance Method Summary collapse
- #execute(pattern:, path: ".", file_pattern: "**/*", case_insensitive: false, context_lines: 0, max_files: 50, max_matches_per_file: 50, max_total_matches: 200, max_file_size: MAX_FILE_SIZE, max_files_to_search: 10000, working_dir: nil) ⇒ Object
- #format_call(args) ⇒ Object
- #format_result(result) ⇒ Object
-
#format_result_for_llm(result) ⇒ Object
Format result for LLM consumption - return a compact version to save tokens.
-
#get_line_context(file, match_index, context_lines) ⇒ Object
Get context lines around a match.
- #search_file(file, regex, context_lines, max_matches) ⇒ Object
Methods inherited from Base
#category, #description, #name, #parameters, #to_function_definition
Instance Method Details
#execute(pattern:, path: ".", file_pattern: "**/*", case_insensitive: false, context_lines: 0, max_files: 50, max_matches_per_file: 50, max_total_matches: 200, max_file_size: MAX_FILE_SIZE, max_files_to_search: 10000, working_dir: nil) ⇒ Object
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 |
# File 'lib/clacky/tools/grep.rb', line 66 def execute( pattern:, path: ".", file_pattern: "**/*", case_insensitive: false, context_lines: 0, max_files: 50, max_matches_per_file: 50, max_total_matches: 200, max_file_size: MAX_FILE_SIZE, max_files_to_search: 10000, working_dir: nil ) # Validate pattern if pattern.nil? || pattern.strip.empty? return { error: "Pattern cannot be empty" } end # Validate and expand path relative to working_dir when provided begin = (path, working_dir: working_dir) rescue StandardError => e return { error: "Invalid path: #{e.}" } end unless File.exist?() return { error: "Path does not exist: #{path}" } end if File.directory?() && Clacky::Utils::FileIgnoreHelper.dangerous_root?() return { error: "Refusing to recursively grep from broad path '#{path}'. " \ "Narrow the path to a specific subdirectory, " \ "or use '.' to search the working directory." } end # Limit context_lines context_lines = [[context_lines, 0].max, 10].min begin # Compile regex = case_insensitive ? Regexp::IGNORECASE : 0 regex = Regexp.new(pattern, ) results = [] total_matches = 0 files_searched = 0 skipped = { binary: 0, too_large: 0, ignored: 0 } truncation_reason = nil files = if File.file?() [] else # Auto-expand bare extension patterns (e.g. "*.ts") to recursive # (e.g. "**/*.ts"), matching ripgrep's default behaviour. # Patterns already containing "/" are left as-is — the user is # intentionally scoping to a specific directory. effective_pattern = file_pattern.include?("/") ? file_pattern : "**/#{file_pattern}" fnmatch_flags = File::FNM_PATHNAME | File::FNM_DOTMATCH collected = [] walk_status = {} Clacky::Utils::FileIgnoreHelper.walk_files(, skipped: skipped, status: walk_status) do |f| relative = f[(.length + 1)..] collected << f if File.fnmatch(effective_pattern, relative, fnmatch_flags) end if walk_status[:truncated] truncation_reason ||= "walk #{walk_status[:truncation_reason]}" end collected end files.each do |file| if files_searched >= max_files_to_search truncation_reason ||= "max_files_to_search limit reached" break end # Skip binary files if Clacky::Utils::FileProcessor.binary_file_path?(file) skipped[:binary] += 1 next end # Skip files that are too large if File.size(file) > max_file_size skipped[:too_large] += 1 next end files_searched += 1 # Check if we've found enough matching files if results.length >= max_files truncation_reason ||= "max_files limit reached" break end # Check if we've found enough total matches if total_matches >= max_total_matches truncation_reason ||= "max_total_matches limit reached" break end # Search the file matches = search_file(file, regex, context_lines, max_matches_per_file) next if matches.empty? # Add remaining matches respecting max_total_matches remaining_matches = max_total_matches - total_matches matches = matches.take(remaining_matches) if remaining_matches < matches.length results << { file: File.(file), matches: matches } total_matches += matches.length end { results: results, total_matches: total_matches, files_searched: files_searched, files_with_matches: results.length, skipped_files: skipped, truncated: !truncation_reason.nil?, truncation_reason: truncation_reason, error: nil } rescue RegexpError => e { error: "Invalid regex pattern: #{e.}" } rescue StandardError => e { error: "Failed to search files: #{e.}" } end end |
#format_call(args) ⇒ Object
206 207 208 209 210 211 212 213 214 215 |
# File 'lib/clacky/tools/grep.rb', line 206 def format_call(args) pattern = args[:pattern] || args['pattern'] || '' path = args[:path] || args['path'] || '.' # Truncate pattern if too long display_pattern = pattern.length > 30 ? "#{pattern[0..27]}..." : pattern display_path = path == '.' ? 'current dir' : (path.length > 20 ? "...#{path[-17..]}" : path) "grep(\"#{display_pattern}\" in #{display_path})" end |
#format_result(result) ⇒ Object
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
# File 'lib/clacky/tools/grep.rb', line 217 def format_result(result) if result[:error] "[Error] #{result[:error]}" else matches = result[:total_matches] || 0 files = result[:files_with_matches] || 0 msg = "[OK] Found #{matches} matches in #{files} files" # Add truncation info if present if result[:truncated] && result[:truncation_reason] msg += " (truncated: #{result[:truncation_reason]})" end msg end end |
#format_result_for_llm(result) ⇒ Object
Format result for LLM consumption - return a compact version to save tokens
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
# File 'lib/clacky/tools/grep.rb', line 235 def format_result_for_llm(result) # If there's an error, return it as-is return result if result[:error] # Build a compact summary with file list and sample matches compact = { summary: { total_matches: result[:total_matches], files_with_matches: result[:files_with_matches], files_searched: result[:files_searched], truncated: result[:truncated], truncation_reason: result[:truncation_reason] } } # Include list of files with match counts if result[:results] && !result[:results].empty? compact[:files] = result[:results].map do |file_result| { file: file_result[:file], match_count: file_result[:matches].length } end # Include sample matches (first 2 matches from first 3 files) for context sample_results = result[:results].take(3) compact[:sample_matches] = sample_results.map do |file_result| { file: file_result[:file], matches: file_result[:matches].take(2).map do |match| { line_number: match[:line_number], line: match[:line] # Omit context to save space - it's rarely needed by LLM } end } end end compact end |
#get_line_context(file, match_index, context_lines) ⇒ Object
Get context lines around a match
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
# File 'lib/clacky/tools/grep.rb', line 314 def get_line_context(file, match_index, context_lines) lines = File.readlines(file, chomp: true).map! { |l| safe_utf8(l) } start_line = [0, match_index - context_lines].max end_line = [lines.length - 1, match_index + context_lines].min context = [] (start_line..end_line).each do |i| line_content = lines[i] # Truncate long lines in context too display_content = line_content.length > MAX_LINE_LENGTH ? "#{line_content[0...MAX_LINE_LENGTH]}..." : line_content context << { line_number: i + 1, content: display_content, is_match: i == match_index } end context rescue StandardError nil end |
#search_file(file, regex, context_lines, max_matches) ⇒ Object
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
# File 'lib/clacky/tools/grep.rb', line 279 def search_file(file, regex, context_lines, max_matches) matches = [] # Use File.foreach for memory-efficient line-by-line reading. # Scrub invalid UTF-8 bytes so results survive JSON encoding. File.foreach(file, chomp: true).with_index do |raw_line, index| line = safe_utf8(raw_line) # Stop if we have enough matches for this file break if matches.length >= max_matches next unless line.match?(regex) # Truncate long lines display_line = line.length > MAX_LINE_LENGTH ? "#{line[0...MAX_LINE_LENGTH]}..." : line # Get context if requested if context_lines > 0 context = get_line_context(file, index, context_lines) else context = nil end matches << { line_number: index + 1, line: display_line, context: context } end matches rescue StandardError [] end |