glob.go

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