1package tools
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "os/exec"
9 "path/filepath"
10 "sort"
11 "strings"
12
13 "github.com/charmbracelet/crush/internal/config"
14 "github.com/charmbracelet/crush/internal/fsext"
15 "github.com/charmbracelet/crush/internal/logging"
16)
17
18const (
19 GlobToolName = "glob"
20 globDescription = `Fast file pattern matching tool that finds files by name and pattern, returning matching paths sorted by modification time (newest first).
21
22WHEN TO USE THIS TOOL:
23- Use when you need to find files by name patterns or extensions
24- Great for finding specific file types across a directory structure
25- Useful for discovering files that match certain naming conventions
26
27HOW TO USE:
28- Provide a glob pattern to match against file paths
29- Optionally specify a starting directory (defaults to current working directory)
30- Results are sorted with most recently modified files first
31
32GLOB PATTERN SYNTAX:
33- '*' matches any sequence of non-separator characters
34- '**' matches any sequence of characters, including separators
35- '?' matches any single non-separator character
36- '[...]' matches any character in the brackets
37- '[!...]' matches any character not in the brackets
38
39COMMON PATTERN EXAMPLES:
40- '*.js' - Find all JavaScript files in the current directory
41- '**/*.js' - Find all JavaScript files in any subdirectory
42- 'src/**/*.{ts,tsx}' - Find all TypeScript files in the src directory
43- '*.{html,css,js}' - Find all HTML, CSS, and JS files
44
45LIMITATIONS:
46- Results are limited to 100 files (newest first)
47- Does not search file contents (use Grep tool for that)
48- Hidden files (starting with '.') are skipped
49
50TIPS:
51- For the most useful results, combine with the Grep tool: first find files with Glob, then search their contents with Grep
52- When doing iterative exploration that may require multiple rounds of searching, consider using the Agent tool instead
53- Always check if results are truncated and refine your search pattern if needed`
54)
55
56type GlobParams struct {
57 Pattern string `json:"pattern"`
58 Path string `json:"path"`
59}
60
61type GlobResponseMetadata struct {
62 NumberOfFiles int `json:"number_of_files"`
63 Truncated bool `json:"truncated"`
64}
65
66type globTool struct{}
67
68func NewGlobTool() BaseTool {
69 return &globTool{}
70}
71
72func (g *globTool) Info() ToolInfo {
73 return ToolInfo{
74 Name: GlobToolName,
75 Description: globDescription,
76 Parameters: map[string]any{
77 "pattern": map[string]any{
78 "type": "string",
79 "description": "The glob pattern to match files against",
80 },
81 "path": map[string]any{
82 "type": "string",
83 "description": "The directory to search in. Defaults to the current working directory.",
84 },
85 },
86 Required: []string{"pattern"},
87 }
88}
89
90func (g *globTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
91 var params GlobParams
92 if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
93 return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
94 }
95
96 if params.Pattern == "" {
97 return NewTextErrorResponse("pattern is required"), nil
98 }
99
100 searchPath := params.Path
101 if searchPath == "" {
102 searchPath = config.WorkingDirectory()
103 }
104
105 files, truncated, err := globFiles(params.Pattern, searchPath, 100)
106 if err != nil {
107 return ToolResponse{}, fmt.Errorf("error finding files: %w", err)
108 }
109
110 var output string
111 if len(files) == 0 {
112 output = "No files found"
113 } else {
114 output = strings.Join(files, "\n")
115 if truncated {
116 output += "\n\n(Results are truncated. Consider using a more specific path or pattern.)"
117 }
118 }
119
120 return WithResponseMetadata(
121 NewTextResponse(output),
122 GlobResponseMetadata{
123 NumberOfFiles: len(files),
124 Truncated: truncated,
125 },
126 ), nil
127}
128
129func globFiles(pattern, searchPath string, limit int) ([]string, bool, error) {
130 cmdRg := fsext.GetRgCmd(pattern)
131 if cmdRg != nil {
132 cmdRg.Dir = searchPath
133 matches, err := runRipgrep(cmdRg, searchPath, limit)
134 if err == nil {
135 return matches, len(matches) >= limit && limit > 0, nil
136 }
137 logging.Warn(fmt.Sprintf("Ripgrep execution failed: %v. Falling back to doublestar.", err))
138 }
139
140 return fsext.GlobWithDoubleStar(pattern, searchPath, limit)
141}
142
143func runRipgrep(cmd *exec.Cmd, searchRoot string, limit int) ([]string, error) {
144 out, err := cmd.CombinedOutput()
145 if err != nil {
146 if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 1 {
147 return nil, nil
148 }
149 return nil, fmt.Errorf("ripgrep: %w\n%s", err, out)
150 }
151
152 var matches []string
153 for _, p := range bytes.Split(out, []byte{0}) {
154 if len(p) == 0 {
155 continue
156 }
157 absPath := string(p)
158 if !filepath.IsAbs(absPath) {
159 absPath = filepath.Join(searchRoot, absPath)
160 }
161 if fsext.SkipHidden(absPath) {
162 continue
163 }
164 matches = append(matches, absPath)
165 }
166
167 sort.SliceStable(matches, func(i, j int) bool {
168 return len(matches[i]) < len(matches[j])
169 })
170
171 if limit > 0 && len(matches) > limit {
172 matches = matches[:limit]
173 }
174 return matches, nil
175}