glob.go

  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) Name() string {
 81	return GlobToolName
 82}
 83
 84func (g *globTool) Info() ToolInfo {
 85	return ToolInfo{
 86		Name:        GlobToolName,
 87		Description: globDescription,
 88		Parameters: map[string]any{
 89			"pattern": map[string]any{
 90				"type":        "string",
 91				"description": "The glob pattern to match files against",
 92			},
 93			"path": map[string]any{
 94				"type":        "string",
 95				"description": "The directory to search in. Defaults to the current working directory.",
 96			},
 97		},
 98		Required: []string{"pattern"},
 99	}
100}
101
102func (g *globTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
103	var params GlobParams
104	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
105		return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
106	}
107
108	if params.Pattern == "" {
109		return NewTextErrorResponse("pattern is required"), nil
110	}
111
112	searchPath := params.Path
113	if searchPath == "" {
114		searchPath = g.workingDir
115	}
116
117	files, truncated, err := globFiles(ctx, params.Pattern, searchPath, 100)
118	if err != nil {
119		return ToolResponse{}, fmt.Errorf("error finding files: %w", err)
120	}
121
122	var output string
123	if len(files) == 0 {
124		output = "No files found"
125	} else {
126		output = strings.Join(files, "\n")
127		if truncated {
128			output += "\n\n(Results are truncated. Consider using a more specific path or pattern.)"
129		}
130	}
131
132	return WithResponseMetadata(
133		NewTextResponse(output),
134		GlobResponseMetadata{
135			NumberOfFiles: len(files),
136			Truncated:     truncated,
137		},
138	), nil
139}
140
141func globFiles(ctx context.Context, pattern, searchPath string, limit int) ([]string, bool, error) {
142	cmdRg := fsext.GetRgCmd(ctx, pattern)
143	if cmdRg != nil {
144		cmdRg.Dir = searchPath
145		matches, err := runRipgrep(cmdRg, searchPath, limit)
146		if err == nil {
147			return matches, len(matches) >= limit && limit > 0, nil
148		}
149		slog.Warn("Ripgrep execution failed, falling back to doublestar", "error", err)
150	}
151
152	return fsext.GlobWithDoubleStar(pattern, searchPath, limit)
153}
154
155func runRipgrep(cmd *exec.Cmd, searchRoot string, limit int) ([]string, error) {
156	out, err := cmd.CombinedOutput()
157	if err != nil {
158		if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 1 {
159			return nil, nil
160		}
161		return nil, fmt.Errorf("ripgrep: %w\n%s", err, out)
162	}
163
164	var matches []string
165	for p := range bytes.SplitSeq(out, []byte{0}) {
166		if len(p) == 0 {
167			continue
168		}
169		absPath := string(p)
170		if !filepath.IsAbs(absPath) {
171			absPath = filepath.Join(searchRoot, absPath)
172		}
173		if fsext.SkipHidden(absPath) {
174			continue
175		}
176		matches = append(matches, absPath)
177	}
178
179	sort.SliceStable(matches, func(i, j int) bool {
180		return len(matches[i]) < len(matches[j])
181	})
182
183	if limit > 0 && len(matches) > limit {
184		matches = matches[:limit]
185	}
186	return matches, nil
187}