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
50WINDOWS NOTES:
51- Path separators are handled automatically (both / and \ work)
52- Uses ripgrep (rg) command if available, otherwise falls back to built-in Go implementation
53
54TIPS:
55- Patterns should use forward slashes (/) for cross-platform compatibility
56- For the most useful results, combine with the Grep tool: first find files with Glob, then search their contents with Grep
57- When doing iterative exploration that may require multiple rounds of searching, consider using the Agent tool instead
58- Always check if results are truncated and refine your search pattern if needed`
59)
60
61type GlobParams struct {
62 Pattern string `json:"pattern"`
63 Path string `json:"path"`
64}
65
66type GlobResponseMetadata struct {
67 NumberOfFiles int `json:"number_of_files"`
68 Truncated bool `json:"truncated"`
69}
70
71type globTool struct{}
72
73func NewGlobTool() BaseTool {
74 return &globTool{}
75}
76
77func (g *globTool) Name() string {
78 return GlobToolName
79}
80
81func (g *globTool) Info() ToolInfo {
82 return ToolInfo{
83 Name: GlobToolName,
84 Description: globDescription,
85 Parameters: map[string]any{
86 "pattern": map[string]any{
87 "type": "string",
88 "description": "The glob pattern to match files against",
89 },
90 "path": map[string]any{
91 "type": "string",
92 "description": "The directory to search in. Defaults to the current working directory.",
93 },
94 },
95 Required: []string{"pattern"},
96 }
97}
98
99func (g *globTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
100 var params GlobParams
101 if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
102 return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
103 }
104
105 if params.Pattern == "" {
106 return NewTextErrorResponse("pattern is required"), nil
107 }
108
109 searchPath := params.Path
110 if searchPath == "" {
111 searchPath = config.Get().WorkingDir()
112 }
113
114 files, truncated, err := globFiles(params.Pattern, searchPath, 100)
115 if err != nil {
116 return ToolResponse{}, fmt.Errorf("error finding files: %w", err)
117 }
118
119 var output string
120 if len(files) == 0 {
121 output = "No files found"
122 } else {
123 output = strings.Join(files, "\n")
124 if truncated {
125 output += "\n\n(Results are truncated. Consider using a more specific path or pattern.)"
126 }
127 }
128
129 return WithResponseMetadata(
130 NewTextResponse(output),
131 GlobResponseMetadata{
132 NumberOfFiles: len(files),
133 Truncated: truncated,
134 },
135 ), nil
136}
137
138func globFiles(pattern, searchPath string, limit int) ([]string, bool, error) {
139 cmdRg := fsext.GetRgCmd(pattern)
140 if cmdRg != nil {
141 cmdRg.Dir = searchPath
142 matches, err := runRipgrep(cmdRg, searchPath, limit)
143 if err == nil {
144 return matches, len(matches) >= limit && limit > 0, nil
145 }
146 logging.Warn(fmt.Sprintf("Ripgrep execution failed: %v. Falling back to doublestar.", err))
147 }
148
149 return fsext.GlobWithDoubleStar(pattern, searchPath, limit)
150}
151
152func runRipgrep(cmd *exec.Cmd, searchRoot string, limit int) ([]string, error) {
153 out, err := cmd.CombinedOutput()
154 if err != nil {
155 if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 1 {
156 return nil, nil
157 }
158 return nil, fmt.Errorf("ripgrep: %w\n%s", err, out)
159 }
160
161 var matches []string
162 for p := range bytes.SplitSeq(out, []byte{0}) {
163 if len(p) == 0 {
164 continue
165 }
166 absPath := string(p)
167 if !filepath.IsAbs(absPath) {
168 absPath = filepath.Join(searchRoot, absPath)
169 }
170 if fsext.SkipHidden(absPath) {
171 continue
172 }
173 matches = append(matches, absPath)
174 }
175
176 sort.SliceStable(matches, func(i, j int) bool {
177 return len(matches[i]) < len(matches[j])
178 })
179
180 if limit > 0 && len(matches) > limit {
181 matches = matches[:limit]
182 }
183 return matches, nil
184}