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, 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
239func searchWithRipgrep(ctx context.Context, pattern, path, include string) ([]grepMatch, error) {
240	cmd := getRgSearchCmd(ctx, pattern, path, include)
241	if cmd == nil {
242		return nil, fmt.Errorf("ripgrep not found in $PATH")
243	}
244
245	// Only add ignore files if they exist
246	for _, ignoreFile := range []string{".gitignore", ".crushignore"} {
247		ignorePath := filepath.Join(path, ignoreFile)
248		if _, err := os.Stat(ignorePath); err == nil {
249			cmd.Args = append(cmd.Args, "--ignore-file", ignorePath)
250		}
251	}
252
253	output, err := cmd.Output()
254	if err != nil {
255		if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {
256			return []grepMatch{}, nil
257		}
258		return nil, err
259	}
260
261	lines := strings.Split(strings.TrimSpace(string(output)), "\n")
262	matches := make([]grepMatch, 0, len(lines))
263
264	for _, line := range lines {
265		if line == "" {
266			continue
267		}
268
269		// Parse ripgrep output using null separation
270		filePath, lineNumStr, lineText, ok := parseRipgrepLine(line)
271		if !ok {
272			continue
273		}
274
275		lineNum, err := strconv.Atoi(lineNumStr)
276		if err != nil {
277			continue
278		}
279
280		fileInfo, err := os.Stat(filePath)
281		if err != nil {
282			continue // Skip files we can't access
283		}
284
285		matches = append(matches, grepMatch{
286			path:     filePath,
287			modTime:  fileInfo.ModTime(),
288			lineNum:  lineNum,
289			lineText: lineText,
290		})
291	}
292
293	return matches, nil
294}
295
296// parseRipgrepLine parses ripgrep output with null separation to handle Windows paths
297func parseRipgrepLine(line string) (filePath, lineNum, lineText string, ok bool) {
298	// Split on null byte first to separate filename from rest
299	parts := strings.SplitN(line, "\x00", 2)
300	if len(parts) != 2 {
301		return "", "", "", false
302	}
303
304	filePath = parts[0]
305	remainder := parts[1]
306
307	// Now split the remainder on first colon: "linenum:content"
308	colonIndex := strings.Index(remainder, ":")
309	if colonIndex == -1 {
310		return "", "", "", false
311	}
312
313	lineNumStr := remainder[:colonIndex]
314	lineText = remainder[colonIndex+1:]
315
316	if _, err := strconv.Atoi(lineNumStr); err != nil {
317		return "", "", "", false
318	}
319
320	return filePath, lineNumStr, lineText, true
321}
322
323func searchFilesWithRegex(pattern, rootPath, include string) ([]grepMatch, error) {
324	matches := []grepMatch{}
325
326	// Use cached regex compilation
327	regex, err := searchRegexCache.get(pattern)
328	if err != nil {
329		return nil, fmt.Errorf("invalid regex pattern: %w", err)
330	}
331
332	var includePattern *regexp.Regexp
333	if include != "" {
334		regexPattern := globToRegex(include)
335		includePattern, err = globRegexCache.get(regexPattern)
336		if err != nil {
337			return nil, fmt.Errorf("invalid include pattern: %w", err)
338		}
339	}
340
341	// Create walker with gitignore and crushignore support
342	walker := fsext.NewFastGlobWalker(rootPath)
343
344	err = filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
345		if err != nil {
346			return nil // Skip errors
347		}
348
349		if info.IsDir() {
350			// Check if directory should be skipped
351			if walker.ShouldSkip(path) {
352				return filepath.SkipDir
353			}
354			return nil // Continue into directory
355		}
356
357		// Use walker's shouldSkip method for files
358		if walker.ShouldSkip(path) {
359			return nil
360		}
361
362		// Skip hidden files (starting with a dot) to match ripgrep's default behavior
363		base := filepath.Base(path)
364		if base != "." && strings.HasPrefix(base, ".") {
365			return nil
366		}
367
368		if includePattern != nil && !includePattern.MatchString(path) {
369			return nil
370		}
371
372		match, lineNum, lineText, err := fileContainsPattern(path, regex)
373		if err != nil {
374			return nil // Skip files we can't read
375		}
376
377		if match {
378			matches = append(matches, grepMatch{
379				path:     path,
380				modTime:  info.ModTime(),
381				lineNum:  lineNum,
382				lineText: lineText,
383			})
384
385			if len(matches) >= 200 {
386				return filepath.SkipAll
387			}
388		}
389
390		return nil
391	})
392	if err != nil {
393		return nil, err
394	}
395
396	return matches, nil
397}
398
399func fileContainsPattern(filePath string, pattern *regexp.Regexp) (bool, int, string, error) {
400	// Quick binary file detection
401	if isBinaryFile(filePath) {
402		return false, 0, "", nil
403	}
404
405	file, err := os.Open(filePath)
406	if err != nil {
407		return false, 0, "", err
408	}
409	defer file.Close()
410
411	scanner := bufio.NewScanner(file)
412	lineNum := 0
413	for scanner.Scan() {
414		lineNum++
415		line := scanner.Text()
416		if pattern.MatchString(line) {
417			return true, lineNum, line, nil
418		}
419	}
420
421	return false, 0, "", scanner.Err()
422}
423
424var binaryExts = map[string]struct{}{
425	".exe": {}, ".dll": {}, ".so": {}, ".dylib": {},
426	".bin": {}, ".obj": {}, ".o": {}, ".a": {},
427	".zip": {}, ".tar": {}, ".gz": {}, ".bz2": {},
428	".jpg": {}, ".jpeg": {}, ".png": {}, ".gif": {},
429	".pdf": {}, ".doc": {}, ".docx": {}, ".xls": {},
430	".mp3": {}, ".mp4": {}, ".avi": {}, ".mov": {},
431}
432
433// isBinaryFile performs a quick check to determine if a file is binary
434func isBinaryFile(filePath string) bool {
435	// Check file extension first (fastest)
436	ext := strings.ToLower(filepath.Ext(filePath))
437	if _, isBinary := binaryExts[ext]; isBinary {
438		return true
439	}
440
441	// Quick content check for files without clear extensions
442	file, err := os.Open(filePath)
443	if err != nil {
444		return false // If we can't open it, let the caller handle the error
445	}
446	defer file.Close()
447
448	// Read first 512 bytes to check for null bytes
449	buffer := make([]byte, 512)
450	n, err := file.Read(buffer)
451	if err != nil && err != io.EOF {
452		return false
453	}
454
455	// Check for null bytes (common in binary files)
456	for i := range n {
457		if buffer[i] == 0 {
458			return true
459		}
460	}
461
462	return false
463}
464
465func globToRegex(glob string) string {
466	regexPattern := strings.ReplaceAll(glob, ".", "\\.")
467	regexPattern = strings.ReplaceAll(regexPattern, "*", ".*")
468	regexPattern = strings.ReplaceAll(regexPattern, "?", ".")
469
470	// Use pre-compiled regex instead of compiling each time
471	regexPattern = globBraceRegex.ReplaceAllStringFunc(regexPattern, func(match string) string {
472		inner := match[1 : len(match)-1]
473		return "(" + strings.ReplaceAll(inner, ",", "|") + ")"
474	})
475
476	return regexPattern
477}