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
 18type globTool struct{}
 19
 20const (
 21	GlobToolName = "glob"
 22)
 23
 24type fileInfo struct {
 25	path    string
 26	modTime time.Time
 27}
 28
 29type GlobParams struct {
 30	Pattern string `json:"pattern"`
 31	Path    string `json:"path"`
 32}
 33
 34func (g *globTool) Info() ToolInfo {
 35	return ToolInfo{
 36		Name:        GlobToolName,
 37		Description: globDescription(),
 38		Parameters: map[string]any{
 39			"pattern": map[string]any{
 40				"type":        "string",
 41				"description": "The glob pattern to match files against",
 42			},
 43			"path": map[string]any{
 44				"type":        "string",
 45				"description": "The directory to search in. Defaults to the current working directory.",
 46			},
 47		},
 48		Required: []string{"pattern"},
 49	}
 50}
 51
 52// Run implements Tool.
 53func (g *globTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
 54	var params GlobParams
 55	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
 56		return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
 57	}
 58
 59	if params.Pattern == "" {
 60		return NewTextErrorResponse("pattern is required"), nil
 61	}
 62
 63	// If path is empty, use current working directory
 64	searchPath := params.Path
 65	if searchPath == "" {
 66		searchPath = config.WorkingDirectory()
 67	}
 68
 69	files, truncated, err := globFiles(params.Pattern, searchPath, 100)
 70	if err != nil {
 71		return NewTextErrorResponse(fmt.Sprintf("error performing glob search: %s", err)), nil
 72	}
 73
 74	// Format the output for the assistant
 75	var output string
 76	if len(files) == 0 {
 77		output = "No files found"
 78	} else {
 79		output = strings.Join(files, "\n")
 80		if truncated {
 81			output += "\n\n(Results are truncated. Consider using a more specific path or pattern.)"
 82		}
 83	}
 84
 85	return NewTextResponse(output), nil
 86}
 87
 88func globFiles(pattern, searchPath string, limit int) ([]string, bool, error) {
 89	// Make sure pattern starts with the search path if not absolute
 90	if !strings.HasPrefix(pattern, "/") && !strings.HasPrefix(pattern, searchPath) {
 91		// If searchPath doesn't end with a slash, add one before appending the pattern
 92		if !strings.HasSuffix(searchPath, "/") {
 93			searchPath += "/"
 94		}
 95		pattern = searchPath + pattern
 96	}
 97
 98	// Open the filesystem for walking
 99	fsys := os.DirFS("/")
100
101	// Convert the absolute pattern to a relative one for the DirFS
102	// DirFS uses the root directory ("/") so we should strip leading "/"
103	relPattern := strings.TrimPrefix(pattern, "/")
104
105	// Collect matching files
106	var matches []fileInfo
107
108	// Use doublestar to walk the filesystem and find matches
109	err := doublestar.GlobWalk(fsys, relPattern, func(path string, d fs.DirEntry) error {
110		// Skip directories from results
111		if d.IsDir() {
112			return nil
113		}
114		if skipHidden(path) {
115			return nil
116		}
117
118		// Get file info for modification time
119		info, err := d.Info()
120		if err != nil {
121			return nil // Skip files we can't access
122		}
123
124		// Add to matches
125		absPath := "/" + path // Restore absolute path
126		matches = append(matches, fileInfo{
127			path:    absPath,
128			modTime: info.ModTime(),
129		})
130
131		// Check limit
132		if len(matches) >= limit*2 { // Collect more than needed for sorting
133			return fs.SkipAll
134		}
135
136		return nil
137	})
138	if err != nil {
139		return nil, false, fmt.Errorf("glob walk error: %w", err)
140	}
141
142	// Sort files by modification time (newest first)
143	sort.Slice(matches, func(i, j int) bool {
144		return matches[i].modTime.After(matches[j].modTime)
145	})
146
147	// Check if we need to truncate the results
148	truncated := len(matches) > limit
149	if truncated {
150		matches = matches[:limit]
151	}
152
153	// Extract just the paths
154	results := make([]string, len(matches))
155	for i, m := range matches {
156		results[i] = m.path
157	}
158
159	return results, truncated, nil
160}
161
162func skipHidden(path string) bool {
163	base := filepath.Base(path)
164	return base != "." && strings.HasPrefix(base, ".")
165}
166
167func globDescription() string {
168	return `Fast file pattern matching tool that finds files by name and pattern, returning matching paths sorted by modification time (newest first).
169
170WHEN TO USE THIS TOOL:
171- Use when you need to find files by name patterns or extensions
172- Great for finding specific file types across a directory structure
173- Useful for discovering files that match certain naming conventions
174
175HOW TO USE:
176- Provide a glob pattern to match against file paths
177- Optionally specify a starting directory (defaults to current working directory)
178- Results are sorted with most recently modified files first
179
180GLOB PATTERN SYNTAX:
181- '*' matches any sequence of non-separator characters
182- '**' matches any sequence of characters, including separators
183- '?' matches any single non-separator character
184- '[...]' matches any character in the brackets
185- '[!...]' matches any character not in the brackets
186
187COMMON PATTERN EXAMPLES:
188- '*.js' - Find all JavaScript files in the current directory
189- '**/*.js' - Find all JavaScript files in any subdirectory
190- 'src/**/*.{ts,tsx}' - Find all TypeScript files in the src directory
191- '*.{html,css,js}' - Find all HTML, CSS, and JS files
192
193LIMITATIONS:
194- Results are limited to 100 files (newest first)
195- Does not search file contents (use Grep tool for that)
196- Hidden files (starting with '.') are skipped
197
198TIPS:
199- For the most useful results, combine with the Grep tool: first find files with Glob, then search their contents with Grep
200- When doing iterative exploration that may require multiple rounds of searching, consider using the Agent tool instead
201- Always check if results are truncated and refine your search pattern if needed`
202}
203
204func NewGlobTool() BaseTool {
205	return &globTool{}
206}