glob.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package tools
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io/fs"
  7. "os"
  8. "path/filepath"
  9. "sort"
  10. "strings"
  11. "time"
  12. "github.com/bmatcuk/doublestar/v4"
  13. "github.com/kujtimiihoxha/termai/internal/config"
  14. )
  15. const (
  16. GlobToolName = "glob"
  17. globDescription = `Fast file pattern matching tool that finds files by name and pattern, returning matching paths sorted by modification time (newest first).
  18. WHEN TO USE THIS TOOL:
  19. - Use when you need to find files by name patterns or extensions
  20. - Great for finding specific file types across a directory structure
  21. - Useful for discovering files that match certain naming conventions
  22. HOW TO USE:
  23. - Provide a glob pattern to match against file paths
  24. - Optionally specify a starting directory (defaults to current working directory)
  25. - Results are sorted with most recently modified files first
  26. GLOB PATTERN SYNTAX:
  27. - '*' matches any sequence of non-separator characters
  28. - '**' matches any sequence of characters, including separators
  29. - '?' matches any single non-separator character
  30. - '[...]' matches any character in the brackets
  31. - '[!...]' matches any character not in the brackets
  32. COMMON PATTERN EXAMPLES:
  33. - '*.js' - Find all JavaScript files in the current directory
  34. - '**/*.js' - Find all JavaScript files in any subdirectory
  35. - 'src/**/*.{ts,tsx}' - Find all TypeScript files in the src directory
  36. - '*.{html,css,js}' - Find all HTML, CSS, and JS files
  37. LIMITATIONS:
  38. - Results are limited to 100 files (newest first)
  39. - Does not search file contents (use Grep tool for that)
  40. - Hidden files (starting with '.') are skipped
  41. TIPS:
  42. - For the most useful results, combine with the Grep tool: first find files with Glob, then search their contents with Grep
  43. - When doing iterative exploration that may require multiple rounds of searching, consider using the Agent tool instead
  44. - Always check if results are truncated and refine your search pattern if needed`
  45. )
  46. type fileInfo struct {
  47. path string
  48. modTime time.Time
  49. }
  50. type GlobParams struct {
  51. Pattern string `json:"pattern"`
  52. Path string `json:"path"`
  53. }
  54. type globTool struct{}
  55. func NewGlobTool() BaseTool {
  56. return &globTool{}
  57. }
  58. func (g *globTool) Info() ToolInfo {
  59. return ToolInfo{
  60. Name: GlobToolName,
  61. Description: globDescription,
  62. Parameters: map[string]any{
  63. "pattern": map[string]any{
  64. "type": "string",
  65. "description": "The glob pattern to match files against",
  66. },
  67. "path": map[string]any{
  68. "type": "string",
  69. "description": "The directory to search in. Defaults to the current working directory.",
  70. },
  71. },
  72. Required: []string{"pattern"},
  73. }
  74. }
  75. func (g *globTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  76. var params GlobParams
  77. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  78. return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
  79. }
  80. if params.Pattern == "" {
  81. return NewTextErrorResponse("pattern is required"), nil
  82. }
  83. searchPath := params.Path
  84. if searchPath == "" {
  85. searchPath = config.WorkingDirectory()
  86. }
  87. files, truncated, err := globFiles(params.Pattern, searchPath, 100)
  88. if err != nil {
  89. return NewTextErrorResponse(fmt.Sprintf("error performing glob search: %s", err)), nil
  90. }
  91. var output string
  92. if len(files) == 0 {
  93. output = "No files found"
  94. } else {
  95. output = strings.Join(files, "\n")
  96. if truncated {
  97. output += "\n\n(Results are truncated. Consider using a more specific path or pattern.)"
  98. }
  99. }
  100. return NewTextResponse(output), nil
  101. }
  102. func globFiles(pattern, searchPath string, limit int) ([]string, bool, error) {
  103. if !strings.HasPrefix(pattern, "/") && !strings.HasPrefix(pattern, searchPath) {
  104. if !strings.HasSuffix(searchPath, "/") {
  105. searchPath += "/"
  106. }
  107. pattern = searchPath + pattern
  108. }
  109. fsys := os.DirFS("/")
  110. relPattern := strings.TrimPrefix(pattern, "/")
  111. var matches []fileInfo
  112. err := doublestar.GlobWalk(fsys, relPattern, func(path string, d fs.DirEntry) error {
  113. if d.IsDir() {
  114. return nil
  115. }
  116. if skipHidden(path) {
  117. return nil
  118. }
  119. info, err := d.Info()
  120. if err != nil {
  121. return nil // Skip files we can't access
  122. }
  123. absPath := "/" + path // Restore absolute path
  124. matches = append(matches, fileInfo{
  125. path: absPath,
  126. modTime: info.ModTime(),
  127. })
  128. if len(matches) >= limit*2 { // Collect more than needed for sorting
  129. return fs.SkipAll
  130. }
  131. return nil
  132. })
  133. if err != nil {
  134. return nil, false, fmt.Errorf("glob walk error: %w", err)
  135. }
  136. sort.Slice(matches, func(i, j int) bool {
  137. return matches[i].modTime.After(matches[j].modTime)
  138. })
  139. truncated := len(matches) > limit
  140. if truncated {
  141. matches = matches[:limit]
  142. }
  143. results := make([]string, len(matches))
  144. for i, m := range matches {
  145. results[i] = m.path
  146. }
  147. return results, truncated, nil
  148. }
  149. func skipHidden(path string) bool {
  150. base := filepath.Base(path)
  151. return base != "." && strings.HasPrefix(base, ".")
  152. }