1package tools
2
3import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "regexp"
13 "sort"
14 "strconv"
15 "strings"
16 "sync"
17 "time"
18
19 "github.com/charmbracelet/crush/internal/config"
20 "github.com/charmbracelet/crush/internal/fsext"
21)
22
23// regexCache provides thread-safe caching of compiled regex patterns
24type regexCache struct {
25 cache map[string]*regexp.Regexp
26 mu sync.RWMutex
27}
28
29// newRegexCache creates a new regex cache
30func newRegexCache() *regexCache {
31 return ®exCache{
32 cache: make(map[string]*regexp.Regexp),
33 }
34}
35
36// get retrieves a compiled regex from cache or compiles and caches it
37func (rc *regexCache) get(pattern string) (*regexp.Regexp, error) {
38 // Try to get from cache first (read lock)
39 rc.mu.RLock()
40 if regex, exists := rc.cache[pattern]; exists {
41 rc.mu.RUnlock()
42 return regex, nil
43 }
44 rc.mu.RUnlock()
45
46 // Compile the regex (write lock)
47 rc.mu.Lock()
48 defer rc.mu.Unlock()
49
50 // Double-check in case another goroutine compiled it while we waited
51 if regex, exists := rc.cache[pattern]; exists {
52 return regex, nil
53 }
54
55 // Compile and cache the regex
56 regex, err := regexp.Compile(pattern)
57 if err != nil {
58 return nil, err
59 }
60
61 rc.cache[pattern] = regex
62 return regex, nil
63}
64
65// Global regex cache instances
66var (
67 searchRegexCache = newRegexCache()
68 globRegexCache = newRegexCache()
69 // Pre-compiled regex for glob conversion (used frequently)
70 globBraceRegex = regexp.MustCompile(`\{([^}]+)\}`)
71)
72
73type GrepParams struct {
74 Pattern string `json:"pattern"`
75 Path string `json:"path"`
76 Include string `json:"include"`
77 LiteralText bool `json:"literal_text"`
78}
79
80type grepMatch struct {
81 path string
82 modTime time.Time
83 lineNum int
84 lineText string
85}
86
87type GrepResponseMetadata struct {
88 NumberOfMatches int `json:"number_of_matches"`
89 Truncated bool `json:"truncated"`
90}
91
92type grepTool struct{}
93
94const (
95 GrepToolName = "grep"
96 grepDescription = `Fast content search tool that finds files containing specific text or patterns, returning matching file paths sorted by modification time (newest first).
97
98WHEN TO USE THIS TOOL:
99- Use when you need to find files containing specific text or patterns
100- Great for searching code bases for function names, variable declarations, or error messages
101- Useful for finding all files that use a particular API or pattern
102
103HOW TO USE:
104- Provide a regex pattern to search for within file contents
105- Set literal_text=true if you want to search for the exact text with special characters (recommended for non-regex users)
106- Optionally specify a starting directory (defaults to current working directory)
107- Optionally provide an include pattern to filter which files to search
108- Results are sorted with most recently modified files first
109
110REGEX PATTERN SYNTAX (when literal_text=false):
111- Supports standard regular expression syntax
112- 'function' searches for the literal text "function"
113- 'log\..*Error' finds text starting with "log." and ending with "Error"
114- 'import\s+.*\s+from' finds import statements in JavaScript/TypeScript
115
116COMMON INCLUDE PATTERN EXAMPLES:
117- '*.js' - Only search JavaScript files
118- '*.{ts,tsx}' - Only search TypeScript files
119- '*.go' - Only search Go files
120
121LIMITATIONS:
122- Results are limited to 100 files (newest first)
123- Performance depends on the number of files being searched
124- Very large binary files may be skipped
125- Hidden files (starting with '.') are skipped
126
127CROSS-PLATFORM NOTES:
128- Uses ripgrep (rg) command if available for better performance
129- Falls back to built-in Go implementation if ripgrep is not available
130- File paths are normalized automatically for cross-platform compatibility
131
132TIPS:
133- For faster, more targeted searches, first use Glob to find relevant files, then use Grep
134- When doing iterative exploration that may require multiple rounds of searching, consider using the Agent tool instead
135- Always check if results are truncated and refine your search pattern if needed
136- Use literal_text=true when searching for exact text containing special characters like dots, parentheses, etc.`
137)
138
139func NewGrepTool() BaseTool {
140 return &grepTool{}
141}
142
143func (g *grepTool) Info() ToolInfo {
144 return ToolInfo{
145 Name: GrepToolName,
146 Description: grepDescription,
147 Parameters: map[string]any{
148 "pattern": map[string]any{
149 "type": "string",
150 "description": "The regex pattern to search for in file contents",
151 },
152 "path": map[string]any{
153 "type": "string",
154 "description": "The directory to search in. Defaults to the current working directory.",
155 },
156 "include": map[string]any{
157 "type": "string",
158 "description": "File pattern to include in the search (e.g. \"*.js\", \"*.{ts,tsx}\")",
159 },
160 "literal_text": map[string]any{
161 "type": "boolean",
162 "description": "If true, the pattern will be treated as literal text with special regex characters escaped. Default is false.",
163 },
164 },
165 Required: []string{"pattern"},
166 }
167}
168
169// escapeRegexPattern escapes special regex characters so they're treated as literal characters
170func escapeRegexPattern(pattern string) string {
171 specialChars := []string{"\\", ".", "+", "*", "?", "(", ")", "[", "]", "{", "}", "^", "$", "|"}
172 escaped := pattern
173
174 for _, char := range specialChars {
175 escaped = strings.ReplaceAll(escaped, char, "\\"+char)
176 }
177
178 return escaped
179}
180
181func (g *grepTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
182 var params GrepParams
183 if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
184 return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
185 }
186
187 if params.Pattern == "" {
188 return NewTextErrorResponse("pattern is required"), nil
189 }
190
191 // If literal_text is true, escape the pattern
192 searchPattern := params.Pattern
193 if params.LiteralText {
194 searchPattern = escapeRegexPattern(params.Pattern)
195 }
196
197 searchPath := params.Path
198 if searchPath == "" {
199 searchPath = config.WorkingDirectory()
200 }
201
202 matches, truncated, err := searchFiles(searchPattern, searchPath, params.Include, 100)
203 if err != nil {
204 return ToolResponse{}, fmt.Errorf("error searching files: %w", err)
205 }
206
207 var output strings.Builder
208 if len(matches) == 0 {
209 output.WriteString("No files found")
210 } else {
211 fmt.Fprintf(&output, "Found %d matches\n", len(matches))
212
213 currentFile := ""
214 for _, match := range matches {
215 if currentFile != match.path {
216 if currentFile != "" {
217 output.WriteString("\n")
218 }
219 currentFile = match.path
220 fmt.Fprintf(&output, "%s:\n", match.path)
221 }
222 if match.lineNum > 0 {
223 fmt.Fprintf(&output, " Line %d: %s\n", match.lineNum, match.lineText)
224 } else {
225 fmt.Fprintf(&output, " %s\n", match.path)
226 }
227 }
228
229 if truncated {
230 output.WriteString("\n(Results are truncated. Consider using a more specific path or pattern.)")
231 }
232 }
233
234 return WithResponseMetadata(
235 NewTextResponse(output.String()),
236 GrepResponseMetadata{
237 NumberOfMatches: len(matches),
238 Truncated: truncated,
239 },
240 ), nil
241}
242
243func searchFiles(pattern, rootPath, include string, limit int) ([]grepMatch, bool, error) {
244 matches, err := searchWithRipgrep(pattern, rootPath, include)
245 if err != nil {
246 matches, err = searchFilesWithRegex(pattern, rootPath, include)
247 if err != nil {
248 return nil, false, err
249 }
250 }
251
252 sort.Slice(matches, func(i, j int) bool {
253 return matches[i].modTime.After(matches[j].modTime)
254 })
255
256 truncated := len(matches) > limit
257 if truncated {
258 matches = matches[:limit]
259 }
260
261 return matches, truncated, nil
262}
263
264func searchWithRipgrep(pattern, path, include string) ([]grepMatch, error) {
265 cmd := fsext.GetRgSearchCmd(pattern, path, include)
266 if cmd == nil {
267 return nil, fmt.Errorf("ripgrep not found in $PATH")
268 }
269
270 output, err := cmd.Output()
271 if err != nil {
272 if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {
273 return []grepMatch{}, nil
274 }
275 return nil, err
276 }
277
278 lines := strings.Split(strings.TrimSpace(string(output)), "\n")
279 matches := make([]grepMatch, 0, len(lines))
280
281 for _, line := range lines {
282 if line == "" {
283 continue
284 }
285
286 // Parse ripgrep output format: file:line:content
287 parts := strings.SplitN(line, ":", 3)
288 if len(parts) < 3 {
289 continue
290 }
291
292 filePath := parts[0]
293 lineNum, err := strconv.Atoi(parts[1])
294 if err != nil {
295 continue
296 }
297 lineText := parts[2]
298
299 fileInfo, err := os.Stat(filePath)
300 if err != nil {
301 continue // Skip files we can't access
302 }
303
304 matches = append(matches, grepMatch{
305 path: filePath,
306 modTime: fileInfo.ModTime(),
307 lineNum: lineNum,
308 lineText: lineText,
309 })
310 }
311
312 return matches, nil
313}
314
315func searchFilesWithRegex(pattern, rootPath, include string) ([]grepMatch, error) {
316 matches := []grepMatch{}
317
318 // Use cached regex compilation
319 regex, err := searchRegexCache.get(pattern)
320 if err != nil {
321 return nil, fmt.Errorf("invalid regex pattern: %w", err)
322 }
323
324 var includePattern *regexp.Regexp
325 if include != "" {
326 regexPattern := globToRegex(include)
327 includePattern, err = globRegexCache.get(regexPattern)
328 if err != nil {
329 return nil, fmt.Errorf("invalid include pattern: %w", err)
330 }
331 }
332
333 err = filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
334 if err != nil {
335 return nil // Skip errors
336 }
337
338 if info.IsDir() {
339 return nil // Skip directories
340 }
341
342 if fsext.SkipHidden(path) {
343 return nil
344 }
345
346 if includePattern != nil && !includePattern.MatchString(path) {
347 return nil
348 }
349
350 match, lineNum, lineText, err := fileContainsPattern(path, regex)
351 if err != nil {
352 return nil // Skip files we can't read
353 }
354
355 if match {
356 matches = append(matches, grepMatch{
357 path: path,
358 modTime: info.ModTime(),
359 lineNum: lineNum,
360 lineText: lineText,
361 })
362
363 if len(matches) >= 200 {
364 return filepath.SkipAll
365 }
366 }
367
368 return nil
369 })
370 if err != nil {
371 return nil, err
372 }
373
374 return matches, nil
375}
376
377func fileContainsPattern(filePath string, pattern *regexp.Regexp) (bool, int, string, error) {
378 // Quick binary file detection
379 if isBinaryFile(filePath) {
380 return false, 0, "", nil
381 }
382
383 file, err := os.Open(filePath)
384 if err != nil {
385 return false, 0, "", err
386 }
387 defer file.Close()
388
389 scanner := bufio.NewScanner(file)
390 lineNum := 0
391 for scanner.Scan() {
392 lineNum++
393 line := scanner.Text()
394 if pattern.MatchString(line) {
395 return true, lineNum, line, nil
396 }
397 }
398
399 return false, 0, "", scanner.Err()
400}
401
402var binaryExts = map[string]struct{}{
403 ".exe": {}, ".dll": {}, ".so": {}, ".dylib": {},
404 ".bin": {}, ".obj": {}, ".o": {}, ".a": {},
405 ".zip": {}, ".tar": {}, ".gz": {}, ".bz2": {},
406 ".jpg": {}, ".jpeg": {}, ".png": {}, ".gif": {},
407 ".pdf": {}, ".doc": {}, ".docx": {}, ".xls": {},
408 ".mp3": {}, ".mp4": {}, ".avi": {}, ".mov": {},
409}
410
411// isBinaryFile performs a quick check to determine if a file is binary
412func isBinaryFile(filePath string) bool {
413 // Check file extension first (fastest)
414 ext := strings.ToLower(filepath.Ext(filePath))
415 if _, isBinary := binaryExts[ext]; isBinary {
416 return true
417 }
418
419 // Quick content check for files without clear extensions
420 file, err := os.Open(filePath)
421 if err != nil {
422 return false // If we can't open it, let the caller handle the error
423 }
424 defer file.Close()
425
426 // Read first 512 bytes to check for null bytes
427 buffer := make([]byte, 512)
428 n, err := file.Read(buffer)
429 if err != nil && err != io.EOF {
430 return false
431 }
432
433 // Check for null bytes (common in binary files)
434 for i := range n {
435 if buffer[i] == 0 {
436 return true
437 }
438 }
439
440 return false
441}
442
443func globToRegex(glob string) string {
444 regexPattern := strings.ReplaceAll(glob, ".", "\\.")
445 regexPattern = strings.ReplaceAll(regexPattern, "*", ".*")
446 regexPattern = strings.ReplaceAll(regexPattern, "?", ".")
447
448 // Use pre-compiled regex instead of compiling each time
449 regexPattern = globBraceRegex.ReplaceAllStringFunc(regexPattern, func(match string) string {
450 inner := match[1 : len(match)-1]
451 return "(" + strings.ReplaceAll(inner, ",", "|") + ")"
452 })
453
454 return regexPattern
455}