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