glob.go

  1package tools
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7	"io/fs"
  8	"os"
  9	"path/filepath"
 10	"sort"
 11	"strings"
 12	"time"
 13
 14	"github.com/bmatcuk/doublestar/v4"
 15	"github.com/kujtimiihoxha/termai/internal/config"
 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
 50TIPS:
 51- For the most useful results, combine with the Grep tool: first find files with Glob, then search their contents with Grep
 52- When doing iterative exploration that may require multiple rounds of searching, consider using the Agent tool instead
 53- Always check if results are truncated and refine your search pattern if needed`
 54)
 55
 56type fileInfo struct {
 57	path    string
 58	modTime time.Time
 59}
 60
 61type GlobParams struct {
 62	Pattern string `json:"pattern"`
 63	Path    string `json:"path"`
 64}
 65
 66type globTool struct{}
 67
 68func NewGlobTool() BaseTool {
 69	return &globTool{}
 70}
 71
 72func (g *globTool) Info() ToolInfo {
 73	return ToolInfo{
 74		Name:        GlobToolName,
 75		Description: globDescription,
 76		Parameters: map[string]any{
 77			"pattern": map[string]any{
 78				"type":        "string",
 79				"description": "The glob pattern to match files against",
 80			},
 81			"path": map[string]any{
 82				"type":        "string",
 83				"description": "The directory to search in. Defaults to the current working directory.",
 84			},
 85		},
 86		Required: []string{"pattern"},
 87	}
 88}
 89
 90func (g *globTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
 91	var params GlobParams
 92	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
 93		return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
 94	}
 95
 96	if params.Pattern == "" {
 97		return NewTextErrorResponse("pattern is required"), nil
 98	}
 99
100	searchPath := params.Path
101	if searchPath == "" {
102		searchPath = config.WorkingDirectory()
103	}
104
105	files, truncated, err := globFiles(params.Pattern, searchPath, 100)
106	if err != nil {
107		return NewTextErrorResponse(fmt.Sprintf("error performing glob search: %s", err)), nil
108	}
109
110	var output string
111	if len(files) == 0 {
112		output = "No files found"
113	} else {
114		output = strings.Join(files, "\n")
115		if truncated {
116			output += "\n\n(Results are truncated. Consider using a more specific path or pattern.)"
117		}
118	}
119
120	return NewTextResponse(output), nil
121}
122
123func globFiles(pattern, searchPath string, limit int) ([]string, bool, error) {
124	if !strings.HasPrefix(pattern, "/") && !strings.HasPrefix(pattern, searchPath) {
125		if !strings.HasSuffix(searchPath, "/") {
126			searchPath += "/"
127		}
128		pattern = searchPath + pattern
129	}
130
131	fsys := os.DirFS("/")
132
133	relPattern := strings.TrimPrefix(pattern, "/")
134
135	var matches []fileInfo
136
137	err := doublestar.GlobWalk(fsys, relPattern, func(path string, d fs.DirEntry) error {
138		if d.IsDir() {
139			return nil
140		}
141		if skipHidden(path) {
142			return nil
143		}
144
145		info, err := d.Info()
146		if err != nil {
147			return nil // Skip files we can't access
148		}
149
150		absPath := "/" + path // Restore absolute path
151		matches = append(matches, fileInfo{
152			path:    absPath,
153			modTime: info.ModTime(),
154		})
155
156		if len(matches) >= limit*2 { // Collect more than needed for sorting
157			return fs.SkipAll
158		}
159
160		return nil
161	})
162	if err != nil {
163		return nil, false, fmt.Errorf("glob walk error: %w", err)
164	}
165
166	sort.Slice(matches, func(i, j int) bool {
167		return matches[i].modTime.After(matches[j].modTime)
168	})
169
170	truncated := len(matches) > limit
171	if truncated {
172		matches = matches[:limit]
173	}
174
175	results := make([]string, len(matches))
176	for i, m := range matches {
177		results[i] = m.path
178	}
179
180	return results, truncated, nil
181}
182
183func skipHidden(path string) bool {
184	base := filepath.Base(path)
185	return base != "." && strings.HasPrefix(base, ".")
186}