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