grep.go

  1package tools
  2
  3import (
  4	"bufio"
  5	"context"
  6	_ "embed"
  7	"encoding/json"
  8	"fmt"
  9	"io"
 10	"os"
 11	"os/exec"
 12	"path/filepath"
 13	"regexp"
 14	"sort"
 15	"strconv"
 16	"strings"
 17	"sync"
 18	"time"
 19
 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	workingDir string
 94}
 95
 96const (
 97	GrepToolName        = "grep"
 98	maxGrepContentWidth = 500
 99)
100
101//go:embed grep.md
102var grepDescription []byte
103
104func NewGrepTool(workingDir string) BaseTool {
105	return &grepTool{
106		workingDir: workingDir,
107	}
108}
109
110func (g *grepTool) Name() string {
111	return GrepToolName
112}
113
114func (g *grepTool) Info() ToolInfo {
115	return ToolInfo{
116		Name:        GrepToolName,
117		Description: string(grepDescription),
118		Parameters: map[string]any{
119			"pattern": map[string]any{
120				"type":        "string",
121				"description": "The regex pattern to search for in file contents",
122			},
123			"path": map[string]any{
124				"type":        "string",
125				"description": "The directory to search in. Defaults to the current working directory.",
126			},
127			"include": map[string]any{
128				"type":        "string",
129				"description": "File pattern to include in the search (e.g. \"*.js\", \"*.{ts,tsx}\")",
130			},
131			"literal_text": map[string]any{
132				"type":        "boolean",
133				"description": "If true, the pattern will be treated as literal text with special regex characters escaped. Default is false.",
134			},
135		},
136		Required: []string{"pattern"},
137	}
138}
139
140// escapeRegexPattern escapes special regex characters so they're treated as literal characters
141func escapeRegexPattern(pattern string) string {
142	specialChars := []string{"\\", ".", "+", "*", "?", "(", ")", "[", "]", "{", "}", "^", "$", "|"}
143	escaped := pattern
144
145	for _, char := range specialChars {
146		escaped = strings.ReplaceAll(escaped, char, "\\"+char)
147	}
148
149	return escaped
150}
151
152func (g *grepTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
153	var params GrepParams
154	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
155		return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
156	}
157
158	if params.Pattern == "" {
159		return NewTextErrorResponse("pattern is required"), nil
160	}
161
162	// If literal_text is true, escape the pattern
163	searchPattern := params.Pattern
164	if params.LiteralText {
165		searchPattern = escapeRegexPattern(params.Pattern)
166	}
167
168	searchPath := params.Path
169	if searchPath == "" {
170		searchPath = g.workingDir
171	}
172
173	matches, truncated, err := searchFiles(ctx, searchPattern, searchPath, params.Include, 100)
174	if err != nil {
175		return ToolResponse{}, fmt.Errorf("error searching files: %w", err)
176	}
177
178	var output strings.Builder
179	if len(matches) == 0 {
180		output.WriteString("No files found")
181	} else {
182		fmt.Fprintf(&output, "Found %d matches\n", len(matches))
183
184		currentFile := ""
185		for _, match := range matches {
186			if currentFile != match.path {
187				if currentFile != "" {
188					output.WriteString("\n")
189				}
190				currentFile = match.path
191				fmt.Fprintf(&output, "%s:\n", match.path)
192			}
193			if match.lineNum > 0 {
194				lineText := match.lineText
195				if len(lineText) > maxGrepContentWidth {
196					lineText = lineText[:maxGrepContentWidth] + "..."
197				}
198				fmt.Fprintf(&output, "  Line %d: %s\n", match.lineNum, lineText)
199			} else {
200				fmt.Fprintf(&output, "  %s\n", match.path)
201			}
202		}
203
204		if truncated {
205			output.WriteString("\n(Results are truncated. Consider using a more specific path or pattern.)")
206		}
207	}
208
209	return WithResponseMetadata(
210		NewTextResponse(output.String()),
211		GrepResponseMetadata{
212			NumberOfMatches: len(matches),
213			Truncated:       truncated,
214		},
215	), nil
216}
217
218func searchFiles(ctx context.Context, pattern, rootPath, include string, limit int) ([]grepMatch, bool, error) {
219	matches, err := searchWithRipgrep(ctx, getRgSearchCmd, pattern, rootPath, include)
220	if err != nil {
221		matches, err = searchFilesWithRegex(pattern, rootPath, include)
222		if err != nil {
223			return nil, false, err
224		}
225	}
226
227	sort.Slice(matches, func(i, j int) bool {
228		return matches[i].modTime.After(matches[j].modTime)
229	})
230
231	truncated := len(matches) > limit
232	if truncated {
233		matches = matches[:limit]
234	}
235
236	return matches, truncated, nil
237}
238
239// NOTE(tauraamui): ideally I would want to not pass in the search specific args here but will leave for now
240func searchWithRipgrep(ctx context.Context, rgSearchCmd resolveRgSearchCmd, pattern, path, include string) ([]grepMatch, error) {
241	cmd := rgSearchCmd(ctx, pattern, path, include)
242	if cmd == nil {
243		return nil, fmt.Errorf("ripgrep not found in $PATH")
244	}
245
246	// Only add ignore files if they exist
247	for _, ignoreFile := range []string{".gitignore", ".crushignore"} {
248		ignorePath := filepath.Join(path, ignoreFile)
249		if _, err := os.Stat(ignorePath); err == nil {
250			cmd.AddArgs("--ignore-file", ignorePath)
251		}
252	}
253
254	output, err := cmd.Output()
255	if err != nil {
256		if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {
257			return []grepMatch{}, nil
258		}
259		return nil, err
260	}
261
262	lines := strings.Split(strings.TrimSpace(string(output)), "\n")
263	matches := make([]grepMatch, 0, len(lines))
264
265	for _, line := range lines {
266		if line == "" {
267			continue
268		}
269
270		// Parse ripgrep output using null separation
271		filePath, lineNumStr, lineText, ok := parseRipgrepLine(line)
272		if !ok {
273			continue
274		}
275
276		lineNum, err := strconv.Atoi(lineNumStr)
277		if err != nil {
278			continue
279		}
280
281		fileInfo, err := os.Stat(filePath)
282		if err != nil {
283			continue // Skip files we can't access
284		}
285
286		matches = append(matches, grepMatch{
287			path:     filePath,
288			modTime:  fileInfo.ModTime(),
289			lineNum:  lineNum,
290			lineText: lineText,
291		})
292	}
293
294	return matches, nil
295}
296
297// parseRipgrepLine parses ripgrep output with null separation to handle Windows paths
298func parseRipgrepLine(line string) (filePath, lineNum, lineText string, ok bool) {
299	// Split on null byte first to separate filename from rest
300	parts := strings.SplitN(line, "\x00", 2)
301	if len(parts) != 2 {
302		return "", "", "", false
303	}
304
305	filePath = parts[0]
306	remainder := parts[1]
307
308	// Now split the remainder on first colon: "linenum:content"
309	colonIndex := strings.Index(remainder, ":")
310	if colonIndex == -1 {
311		return "", "", "", false
312	}
313
314	lineNumStr := remainder[:colonIndex]
315	lineText = remainder[colonIndex+1:]
316
317	if _, err := strconv.Atoi(lineNumStr); err != nil {
318		return "", "", "", false
319	}
320
321	return filePath, lineNumStr, lineText, true
322}
323
324func searchFilesWithRegex(pattern, rootPath, include string) ([]grepMatch, error) {
325	matches := []grepMatch{}
326
327	// Use cached regex compilation
328	regex, err := searchRegexCache.get(pattern)
329	if err != nil {
330		return nil, fmt.Errorf("invalid regex pattern: %w", err)
331	}
332
333	var includePattern *regexp.Regexp
334	if include != "" {
335		regexPattern := globToRegex(include)
336		includePattern, err = globRegexCache.get(regexPattern)
337		if err != nil {
338			return nil, fmt.Errorf("invalid include pattern: %w", err)
339		}
340	}
341
342	// Create walker with gitignore and crushignore support
343	walker := fsext.NewFastGlobWalker(rootPath)
344
345	err = filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
346		if err != nil {
347			return nil // Skip errors
348		}
349
350		if info.IsDir() {
351			// Check if directory should be skipped
352			if walker.ShouldSkip(path) {
353				return filepath.SkipDir
354			}
355			return nil // Continue into directory
356		}
357
358		// Use walker's shouldSkip method for files
359		if walker.ShouldSkip(path) {
360			return nil
361		}
362
363		// Skip hidden files (starting with a dot) to match ripgrep's default behavior
364		base := filepath.Base(path)
365		if base != "." && strings.HasPrefix(base, ".") {
366			return nil
367		}
368
369		if includePattern != nil && !includePattern.MatchString(path) {
370			return nil
371		}
372
373		match, lineNum, lineText, err := fileContainsPattern(path, regex)
374		if err != nil {
375			return nil // Skip files we can't read
376		}
377
378		if match {
379			matches = append(matches, grepMatch{
380				path:     path,
381				modTime:  info.ModTime(),
382				lineNum:  lineNum,
383				lineText: lineText,
384			})
385
386			if len(matches) >= 200 {
387				return filepath.SkipAll
388			}
389		}
390
391		return nil
392	})
393	if err != nil {
394		return nil, err
395	}
396
397	return matches, nil
398}
399
400func fileContainsPattern(filePath string, pattern *regexp.Regexp) (bool, int, string, error) {
401	// Quick binary file detection
402	if isBinaryFile(filePath) {
403		return false, 0, "", nil
404	}
405
406	file, err := os.Open(filePath)
407	if err != nil {
408		return false, 0, "", err
409	}
410	defer file.Close()
411
412	scanner := bufio.NewScanner(file)
413	lineNum := 0
414	for scanner.Scan() {
415		lineNum++
416		line := scanner.Text()
417		if pattern.MatchString(line) {
418			return true, lineNum, line, nil
419		}
420	}
421
422	return false, 0, "", scanner.Err()
423}
424
425var binaryExts = map[string]struct{}{
426	".exe": {}, ".dll": {}, ".so": {}, ".dylib": {},
427	".bin": {}, ".obj": {}, ".o": {}, ".a": {},
428	".zip": {}, ".tar": {}, ".gz": {}, ".bz2": {},
429	".jpg": {}, ".jpeg": {}, ".png": {}, ".gif": {},
430	".pdf": {}, ".doc": {}, ".docx": {}, ".xls": {},
431	".mp3": {}, ".mp4": {}, ".avi": {}, ".mov": {},
432}
433
434// isBinaryFile performs a quick check to determine if a file is binary
435func isBinaryFile(filePath string) bool {
436	// Check file extension first (fastest)
437	ext := strings.ToLower(filepath.Ext(filePath))
438	if _, isBinary := binaryExts[ext]; isBinary {
439		return true
440	}
441
442	// Quick content check for files without clear extensions
443	file, err := os.Open(filePath)
444	if err != nil {
445		return false // If we can't open it, let the caller handle the error
446	}
447	defer file.Close()
448
449	// Read first 512 bytes to check for null bytes
450	buffer := make([]byte, 512)
451	n, err := file.Read(buffer)
452	if err != nil && err != io.EOF {
453		return false
454	}
455
456	// Check for null bytes (common in binary files)
457	for i := range n {
458		if buffer[i] == 0 {
459			return true
460		}
461	}
462
463	return false
464}
465
466func globToRegex(glob string) string {
467	regexPattern := strings.ReplaceAll(glob, ".", "\\.")
468	regexPattern = strings.ReplaceAll(regexPattern, "*", ".*")
469	regexPattern = strings.ReplaceAll(regexPattern, "?", ".")
470
471	// Use pre-compiled regex instead of compiling each time
472	regexPattern = globBraceRegex.ReplaceAllStringFunc(regexPattern, func(match string) string {
473		inner := match[1 : len(match)-1]
474		return "(" + strings.ReplaceAll(inner, ",", "|") + ")"
475	})
476
477	return regexPattern
478}