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