15 "github.com/charmbracelet/crush/internal/fsext"
18const GlobToolName = "glob"
21var globDescription []byte
23type GlobParams struct {
24 Pattern string `json:"pattern" description:"The glob pattern to match files against"`
25 Path string `json:"path,omitempty" description:"The directory to search in. Defaults to the current working directory."`
28type GlobResponseMetadata struct {
29 NumberOfFiles int `json:"number_of_files"`
30 Truncated bool `json:"truncated"`
33func NewGlobTool(workingDir string) fantasy.AgentTool {
34 return fantasy.NewAgentTool(
36 string(globDescription),
37 func(ctx context.Context, params GlobParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
38 if params.Pattern == "" {
39 return fantasy.NewTextErrorResponse("pattern is required"), nil
42 searchPath := params.Path
44 searchPath = workingDir
47 files, truncated, err := globFiles(ctx, params.Pattern, searchPath, 100)
49 return fantasy.ToolResponse{}, fmt.Errorf("error finding files: %w", err)
54 output = "No files found"
56 normalizeFilePaths(files)
57 output = strings.Join(files, "\n")
59 output += "\n\n(Results are truncated. Consider using a more specific path or pattern.)"
63 return fantasy.WithResponseMetadata(
64 fantasy.NewTextResponse(output),
66 NumberOfFiles: len(files),
73func globFiles(ctx context.Context, pattern, searchPath string, limit int) ([]string, bool, error) {
74 cmdRg := getRgCmd(ctx, pattern)
76 cmdRg.Dir = searchPath
77 matches, err := runRipgrep(cmdRg, searchPath, limit)
79 return matches, len(matches) >= limit && limit > 0, nil
81 slog.Warn("Ripgrep execution failed, falling back to doublestar", "error", err)
84 return fsext.GlobWithDoubleStar(pattern, searchPath, limit)
87func runRipgrep(cmd *exec.Cmd, searchRoot string, limit int) ([]string, error) {
88 out, err := cmd.CombinedOutput()
90 if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 1 {
93 return nil, fmt.Errorf("ripgrep: %w\n%s", err, out)
97 for p := range bytes.SplitSeq(out, []byte{0}) {
102 if !filepath.IsAbs(absPath) {
103 absPath = filepath.Join(searchRoot, absPath)
105 if fsext.SkipHidden(absPath) {
108 matches = append(matches, absPath)
111 sort.SliceStable(matches, func(i, j int) bool {
112 return len(matches[i]) < len(matches[j])
115 if limit > 0 && len(matches) > limit {
116 matches = matches[:limit]
121func normalizeFilePaths(paths []string) {
122 for i, p := range paths {
123 paths[i] = filepath.ToSlash(p)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list