glob.go

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