grep.go

  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 &regexCache{
 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
127TIPS:
128- For faster, more targeted searches, first use Glob to find relevant files, then use Grep
129- When doing iterative exploration that may require multiple rounds of searching, consider using the Agent tool instead
130- Always check if results are truncated and refine your search pattern if needed
131- Use literal_text=true when searching for exact text containing special characters like dots, parentheses, etc.`
132)
133
134func NewGrepTool() BaseTool {
135	return &grepTool{}
136}
137
138func (g *grepTool) Info() ToolInfo {
139	return ToolInfo{
140		Name:        GrepToolName,
141		Description: grepDescription,
142		Parameters: map[string]any{
143			"pattern": map[string]any{
144				"type":        "string",
145				"description": "The regex pattern to search for in file contents",
146			},
147			"path": map[string]any{
148				"type":        "string",
149				"description": "The directory to search in. Defaults to the current working directory.",
150			},
151			"include": map[string]any{
152				"type":        "string",
153				"description": "File pattern to include in the search (e.g. \"*.js\", \"*.{ts,tsx}\")",
154			},
155			"literal_text": map[string]any{
156				"type":        "boolean",
157				"description": "If true, the pattern will be treated as literal text with special regex characters escaped. Default is false.",
158			},
159		},
160		Required: []string{"pattern"},
161	}
162}
163
164// escapeRegexPattern escapes special regex characters so they're treated as literal characters
165func escapeRegexPattern(pattern string) string {
166	specialChars := []string{"\\", ".", "+", "*", "?", "(", ")", "[", "]", "{", "}", "^", "$", "|"}
167	escaped := pattern
168
169	for _, char := range specialChars {
170		escaped = strings.ReplaceAll(escaped, char, "\\"+char)
171	}
172
173	return escaped
174}
175
176func (g *grepTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
177	var params GrepParams
178	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
179		return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
180	}
181
182	if params.Pattern == "" {
183		return NewTextErrorResponse("pattern is required"), nil
184	}
185
186	// If literal_text is true, escape the pattern
187	searchPattern := params.Pattern
188	if params.LiteralText {
189		searchPattern = escapeRegexPattern(params.Pattern)
190	}
191
192	searchPath := params.Path
193	if searchPath == "" {
194		searchPath = config.WorkingDirectory()
195	}
196
197	matches, truncated, err := searchFiles(searchPattern, searchPath, params.Include, 100)
198	if err != nil {
199		return ToolResponse{}, fmt.Errorf("error searching files: %w", err)
200	}
201
202	var output strings.Builder
203	if len(matches) == 0 {
204		output.WriteString("No files found")
205	} else {
206		fmt.Fprintf(&output, "Found %d matches\n", len(matches))
207
208		currentFile := ""
209		for _, match := range matches {
210			if currentFile != match.path {
211				if currentFile != "" {
212					output.WriteString("\n")
213				}
214				currentFile = match.path
215				fmt.Fprintf(&output, "%s:\n", match.path)
216			}
217			if match.lineNum > 0 {
218				fmt.Fprintf(&output, "  Line %d: %s\n", match.lineNum, match.lineText)
219			} else {
220				fmt.Fprintf(&output, "  %s\n", match.path)
221			}
222		}
223
224		if truncated {
225			output.WriteString("\n(Results are truncated. Consider using a more specific path or pattern.)")
226		}
227	}
228
229	return WithResponseMetadata(
230		NewTextResponse(output.String()),
231		GrepResponseMetadata{
232			NumberOfMatches: len(matches),
233			Truncated:       truncated,
234		},
235	), nil
236}
237
238func searchFiles(pattern, rootPath, include string, limit int) ([]grepMatch, bool, error) {
239	matches, err := searchWithRipgrep(pattern, rootPath, include)
240	if err != nil {
241		matches, err = searchFilesWithRegex(pattern, rootPath, include)
242		if err != nil {
243			return nil, false, err
244		}
245	}
246
247	sort.Slice(matches, func(i, j int) bool {
248		return matches[i].modTime.After(matches[j].modTime)
249	})
250
251	truncated := len(matches) > limit
252	if truncated {
253		matches = matches[:limit]
254	}
255
256	return matches, truncated, nil
257}
258
259func searchWithRipgrep(pattern, path, include string) ([]grepMatch, error) {
260	cmd := fsext.GetRgSearchCmd(pattern, path, include)
261	if cmd == nil {
262		return nil, fmt.Errorf("ripgrep not found in $PATH")
263	}
264
265	output, err := cmd.Output()
266	if err != nil {
267		if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {
268			return []grepMatch{}, nil
269		}
270		return nil, err
271	}
272
273	lines := strings.Split(strings.TrimSpace(string(output)), "\n")
274	matches := make([]grepMatch, 0, len(lines))
275
276	for _, line := range lines {
277		if line == "" {
278			continue
279		}
280
281		// Parse ripgrep output format: file:line:content
282		parts := strings.SplitN(line, ":", 3)
283		if len(parts) < 3 {
284			continue
285		}
286
287		filePath := parts[0]
288		lineNum, err := strconv.Atoi(parts[1])
289		if err != nil {
290			continue
291		}
292		lineText := parts[2]
293
294		fileInfo, err := os.Stat(filePath)
295		if err != nil {
296			continue // Skip files we can't access
297		}
298
299		matches = append(matches, grepMatch{
300			path:     filePath,
301			modTime:  fileInfo.ModTime(),
302			lineNum:  lineNum,
303			lineText: lineText,
304		})
305	}
306
307	return matches, nil
308}
309
310func searchFilesWithRegex(pattern, rootPath, include string) ([]grepMatch, error) {
311	matches := []grepMatch{}
312
313	// Use cached regex compilation
314	regex, err := searchRegexCache.get(pattern)
315	if err != nil {
316		return nil, fmt.Errorf("invalid regex pattern: %w", err)
317	}
318
319	var includePattern *regexp.Regexp
320	if include != "" {
321		regexPattern := globToRegex(include)
322		includePattern, err = globRegexCache.get(regexPattern)
323		if err != nil {
324			return nil, fmt.Errorf("invalid include pattern: %w", err)
325		}
326	}
327
328	err = filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
329		if err != nil {
330			return nil // Skip errors
331		}
332
333		if info.IsDir() {
334			return nil // Skip directories
335		}
336
337		if fsext.SkipHidden(path) {
338			return nil
339		}
340
341		if includePattern != nil && !includePattern.MatchString(path) {
342			return nil
343		}
344
345		match, lineNum, lineText, err := fileContainsPattern(path, regex)
346		if err != nil {
347			return nil // Skip files we can't read
348		}
349
350		if match {
351			matches = append(matches, grepMatch{
352				path:     path,
353				modTime:  info.ModTime(),
354				lineNum:  lineNum,
355				lineText: lineText,
356			})
357
358			if len(matches) >= 200 {
359				return filepath.SkipAll
360			}
361		}
362
363		return nil
364	})
365	if err != nil {
366		return nil, err
367	}
368
369	return matches, nil
370}
371
372func fileContainsPattern(filePath string, pattern *regexp.Regexp) (bool, int, string, error) {
373	// Quick binary file detection
374	if isBinaryFile(filePath) {
375		return false, 0, "", nil
376	}
377
378	file, err := os.Open(filePath)
379	if err != nil {
380		return false, 0, "", err
381	}
382	defer file.Close()
383
384	scanner := bufio.NewScanner(file)
385	lineNum := 0
386	for scanner.Scan() {
387		lineNum++
388		line := scanner.Text()
389		if pattern.MatchString(line) {
390			return true, lineNum, line, nil
391		}
392	}
393
394	return false, 0, "", scanner.Err()
395}
396
397var binaryExts = map[string]struct{}{
398	".exe": {}, ".dll": {}, ".so": {}, ".dylib": {},
399	".bin": {}, ".obj": {}, ".o": {}, ".a": {},
400	".zip": {}, ".tar": {}, ".gz": {}, ".bz2": {},
401	".jpg": {}, ".jpeg": {}, ".png": {}, ".gif": {},
402	".pdf": {}, ".doc": {}, ".docx": {}, ".xls": {},
403	".mp3": {}, ".mp4": {}, ".avi": {}, ".mov": {},
404}
405
406// isBinaryFile performs a quick check to determine if a file is binary
407func isBinaryFile(filePath string) bool {
408	// Check file extension first (fastest)
409	ext := strings.ToLower(filepath.Ext(filePath))
410	if _, isBinary := binaryExts[ext]; isBinary {
411		return true
412	}
413
414	// Quick content check for files without clear extensions
415	file, err := os.Open(filePath)
416	if err != nil {
417		return false // If we can't open it, let the caller handle the error
418	}
419	defer file.Close()
420
421	// Read first 512 bytes to check for null bytes
422	buffer := make([]byte, 512)
423	n, err := file.Read(buffer)
424	if err != nil && err != io.EOF {
425		return false
426	}
427
428	// Check for null bytes (common in binary files)
429	for i := range n {
430		if buffer[i] == 0 {
431			return true
432		}
433	}
434
435	return false
436}
437
438func globToRegex(glob string) string {
439	regexPattern := strings.ReplaceAll(glob, ".", "\\.")
440	regexPattern = strings.ReplaceAll(regexPattern, "*", ".*")
441	regexPattern = strings.ReplaceAll(regexPattern, "?", ".")
442
443	// Use pre-compiled regex instead of compiling each time
444	regexPattern = globBraceRegex.ReplaceAllStringFunc(regexPattern, func(match string) string {
445		inner := match[1 : len(match)-1]
446		return "(" + strings.ReplaceAll(inner, ",", "|") + ")"
447	})
448
449	return regexPattern
450}