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/fileutil"
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
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), ¶ms); 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 _, err := exec.LookPath("rg")
261 if err != nil {
262 return nil, fmt.Errorf("ripgrep not found: %w", err)
263 }
264
265 // Use -n to show line numbers and include the matched line
266 args := []string{"-n", pattern}
267 if include != "" {
268 args = append(args, "--glob", include)
269 }
270 args = append(args, path)
271
272 cmd := exec.Command("rg", args...)
273 output, err := cmd.Output()
274 if err != nil {
275 if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {
276 return []grepMatch{}, nil
277 }
278 return nil, err
279 }
280
281 lines := strings.Split(strings.TrimSpace(string(output)), "\n")
282 matches := make([]grepMatch, 0, len(lines))
283
284 for _, line := range lines {
285 if line == "" {
286 continue
287 }
288
289 // Parse ripgrep output format: file:line:content
290 parts := strings.SplitN(line, ":", 3)
291 if len(parts) < 3 {
292 continue
293 }
294
295 filePath := parts[0]
296 lineNum, err := strconv.Atoi(parts[1])
297 if err != nil {
298 continue
299 }
300 lineText := parts[2]
301
302 fileInfo, err := os.Stat(filePath)
303 if err != nil {
304 continue // Skip files we can't access
305 }
306
307 matches = append(matches, grepMatch{
308 path: filePath,
309 modTime: fileInfo.ModTime(),
310 lineNum: lineNum,
311 lineText: lineText,
312 })
313 }
314
315 return matches, nil
316}
317
318func searchFilesWithRegex(pattern, rootPath, include string) ([]grepMatch, error) {
319 matches := []grepMatch{}
320
321 // Use cached regex compilation
322 regex, err := searchRegexCache.get(pattern)
323 if err != nil {
324 return nil, fmt.Errorf("invalid regex pattern: %w", err)
325 }
326
327 var includePattern *regexp.Regexp
328 if include != "" {
329 regexPattern := globToRegex(include)
330 includePattern, err = globRegexCache.get(regexPattern)
331 if err != nil {
332 return nil, fmt.Errorf("invalid include pattern: %w", err)
333 }
334 }
335
336 err = filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
337 if err != nil {
338 return nil // Skip errors
339 }
340
341 if info.IsDir() {
342 return nil // Skip directories
343 }
344
345 if fileutil.SkipHidden(path) {
346 return nil
347 }
348
349 if includePattern != nil && !includePattern.MatchString(path) {
350 return nil
351 }
352
353 match, lineNum, lineText, err := fileContainsPattern(path, regex)
354 if err != nil {
355 return nil // Skip files we can't read
356 }
357
358 if match {
359 matches = append(matches, grepMatch{
360 path: path,
361 modTime: info.ModTime(),
362 lineNum: lineNum,
363 lineText: lineText,
364 })
365
366 if len(matches) >= 200 {
367 return filepath.SkipAll
368 }
369 }
370
371 return nil
372 })
373 if err != nil {
374 return nil, err
375 }
376
377 return matches, nil
378}
379
380func fileContainsPattern(filePath string, pattern *regexp.Regexp) (bool, int, string, error) {
381 // Quick binary file detection
382 if isBinaryFile(filePath) {
383 return false, 0, "", nil
384 }
385
386 file, err := os.Open(filePath)
387 if err != nil {
388 return false, 0, "", err
389 }
390 defer file.Close()
391
392 scanner := bufio.NewScanner(file)
393 lineNum := 0
394 for scanner.Scan() {
395 lineNum++
396 line := scanner.Text()
397 if pattern.MatchString(line) {
398 return true, lineNum, line, nil
399 }
400 }
401
402 return false, 0, "", scanner.Err()
403}
404
405var binaryExts = map[string]struct{}{
406 ".exe": {}, ".dll": {}, ".so": {}, ".dylib": {},
407 ".bin": {}, ".obj": {}, ".o": {}, ".a": {},
408 ".zip": {}, ".tar": {}, ".gz": {}, ".bz2": {},
409 ".jpg": {}, ".jpeg": {}, ".png": {}, ".gif": {},
410 ".pdf": {}, ".doc": {}, ".docx": {}, ".xls": {},
411 ".mp3": {}, ".mp4": {}, ".avi": {}, ".mov": {},
412}
413
414// isBinaryFile performs a quick check to determine if a file is binary
415func isBinaryFile(filePath string) bool {
416 // Check file extension first (fastest)
417 ext := strings.ToLower(filepath.Ext(filePath))
418 if _, isBinary := binaryExts[ext]; isBinary {
419 return true
420 }
421
422 // Quick content check for files without clear extensions
423 file, err := os.Open(filePath)
424 if err != nil {
425 return false // If we can't open it, let the caller handle the error
426 }
427 defer file.Close()
428
429 // Read first 512 bytes to check for null bytes
430 buffer := make([]byte, 512)
431 n, err := file.Read(buffer)
432 if err != nil && err != io.EOF {
433 return false
434 }
435
436 // Check for null bytes (common in binary files)
437 for i := 0; i < n; i++ {
438 if buffer[i] == 0 {
439 return true
440 }
441 }
442
443 return false
444}
445
446func globToRegex(glob string) string {
447 regexPattern := strings.ReplaceAll(glob, ".", "\\.")
448 regexPattern = strings.ReplaceAll(regexPattern, "*", ".*")
449 regexPattern = strings.ReplaceAll(regexPattern, "?", ".")
450
451 // Use pre-compiled regex instead of compiling each time
452 regexPattern = globBraceRegex.ReplaceAllStringFunc(regexPattern, func(match string) string {
453 inner := match[1 : len(match)-1]
454 return "(" + strings.ReplaceAll(inner, ",", "|") + ")"
455 })
456
457 return regexPattern
458}