grep.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package tools
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "regexp"
  11. "sort"
  12. "strings"
  13. "time"
  14. "github.com/kujtimiihoxha/termai/internal/config"
  15. )
  16. type GrepParams struct {
  17. Pattern string `json:"pattern"`
  18. Path string `json:"path"`
  19. Include string `json:"include"`
  20. }
  21. type grepMatch struct {
  22. path string
  23. modTime time.Time
  24. }
  25. type grepTool struct{}
  26. const (
  27. GrepToolName = "grep"
  28. grepDescription = `Fast content search tool that finds files containing specific text or patterns, returning matching file paths sorted by modification time (newest first).
  29. WHEN TO USE THIS TOOL:
  30. - Use when you need to find files containing specific text or patterns
  31. - Great for searching code bases for function names, variable declarations, or error messages
  32. - Useful for finding all files that use a particular API or pattern
  33. HOW TO USE:
  34. - Provide a regex pattern to search for within file contents
  35. - Optionally specify a starting directory (defaults to current working directory)
  36. - Optionally provide an include pattern to filter which files to search
  37. - Results are sorted with most recently modified files first
  38. REGEX PATTERN SYNTAX:
  39. - Supports standard regular expression syntax
  40. - 'function' searches for the literal text "function"
  41. - 'log\..*Error' finds text starting with "log." and ending with "Error"
  42. - 'import\s+.*\s+from' finds import statements in JavaScript/TypeScript
  43. COMMON INCLUDE PATTERN EXAMPLES:
  44. - '*.js' - Only search JavaScript files
  45. - '*.{ts,tsx}' - Only search TypeScript files
  46. - '*.go' - Only search Go files
  47. LIMITATIONS:
  48. - Results are limited to 100 files (newest first)
  49. - Performance depends on the number of files being searched
  50. - Very large binary files may be skipped
  51. - Hidden files (starting with '.') are skipped
  52. TIPS:
  53. - For faster, more targeted searches, first use Glob to find relevant files, then use Grep
  54. - When doing iterative exploration that may require multiple rounds of searching, consider using the Agent tool instead
  55. - Always check if results are truncated and refine your search pattern if needed`
  56. )
  57. func NewGrepTool() BaseTool {
  58. return &grepTool{}
  59. }
  60. func (g *grepTool) Info() ToolInfo {
  61. return ToolInfo{
  62. Name: GrepToolName,
  63. Description: grepDescription,
  64. Parameters: map[string]any{
  65. "pattern": map[string]any{
  66. "type": "string",
  67. "description": "The regex pattern to search for in file contents",
  68. },
  69. "path": map[string]any{
  70. "type": "string",
  71. "description": "The directory to search in. Defaults to the current working directory.",
  72. },
  73. "include": map[string]any{
  74. "type": "string",
  75. "description": "File pattern to include in the search (e.g. \"*.js\", \"*.{ts,tsx}\")",
  76. },
  77. },
  78. Required: []string{"pattern"},
  79. }
  80. }
  81. func (g *grepTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  82. var params GrepParams
  83. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  84. return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
  85. }
  86. if params.Pattern == "" {
  87. return NewTextErrorResponse("pattern is required"), nil
  88. }
  89. searchPath := params.Path
  90. if searchPath == "" {
  91. searchPath = config.WorkingDirectory()
  92. }
  93. matches, truncated, err := searchFiles(params.Pattern, searchPath, params.Include, 100)
  94. if err != nil {
  95. return NewTextErrorResponse(fmt.Sprintf("error searching files: %s", err)), nil
  96. }
  97. var output string
  98. if len(matches) == 0 {
  99. output = "No files found"
  100. } else {
  101. output = fmt.Sprintf("Found %d file%s\n%s",
  102. len(matches),
  103. pluralize(len(matches)),
  104. strings.Join(matches, "\n"))
  105. if truncated {
  106. output += "\n\n(Results are truncated. Consider using a more specific path or pattern.)"
  107. }
  108. }
  109. return NewTextResponse(output), nil
  110. }
  111. func pluralize(count int) string {
  112. if count == 1 {
  113. return ""
  114. }
  115. return "s"
  116. }
  117. func searchFiles(pattern, rootPath, include string, limit int) ([]string, bool, error) {
  118. matches, err := searchWithRipgrep(pattern, rootPath, include)
  119. if err != nil {
  120. matches, err = searchFilesWithRegex(pattern, rootPath, include)
  121. if err != nil {
  122. return nil, false, err
  123. }
  124. }
  125. sort.Slice(matches, func(i, j int) bool {
  126. return matches[i].modTime.After(matches[j].modTime)
  127. })
  128. truncated := len(matches) > limit
  129. if truncated {
  130. matches = matches[:limit]
  131. }
  132. results := make([]string, len(matches))
  133. for i, m := range matches {
  134. results[i] = m.path
  135. }
  136. return results, truncated, nil
  137. }
  138. func searchWithRipgrep(pattern, path, include string) ([]grepMatch, error) {
  139. _, err := exec.LookPath("rg")
  140. if err != nil {
  141. return nil, fmt.Errorf("ripgrep not found: %w", err)
  142. }
  143. args := []string{"-l", pattern}
  144. if include != "" {
  145. args = append(args, "--glob", include)
  146. }
  147. args = append(args, path)
  148. cmd := exec.Command("rg", args...)
  149. output, err := cmd.Output()
  150. if err != nil {
  151. if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {
  152. return []grepMatch{}, nil
  153. }
  154. return nil, err
  155. }
  156. lines := strings.Split(strings.TrimSpace(string(output)), "\n")
  157. matches := make([]grepMatch, 0, len(lines))
  158. for _, line := range lines {
  159. if line == "" {
  160. continue
  161. }
  162. fileInfo, err := os.Stat(line)
  163. if err != nil {
  164. continue // Skip files we can't access
  165. }
  166. matches = append(matches, grepMatch{
  167. path: line,
  168. modTime: fileInfo.ModTime(),
  169. })
  170. }
  171. return matches, nil
  172. }
  173. func searchFilesWithRegex(pattern, rootPath, include string) ([]grepMatch, error) {
  174. matches := []grepMatch{}
  175. regex, err := regexp.Compile(pattern)
  176. if err != nil {
  177. return nil, fmt.Errorf("invalid regex pattern: %w", err)
  178. }
  179. var includePattern *regexp.Regexp
  180. if include != "" {
  181. regexPattern := globToRegex(include)
  182. includePattern, err = regexp.Compile(regexPattern)
  183. if err != nil {
  184. return nil, fmt.Errorf("invalid include pattern: %w", err)
  185. }
  186. }
  187. err = filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
  188. if err != nil {
  189. return nil // Skip errors
  190. }
  191. if info.IsDir() {
  192. return nil // Skip directories
  193. }
  194. if skipHidden(path) {
  195. return nil
  196. }
  197. if includePattern != nil && !includePattern.MatchString(path) {
  198. return nil
  199. }
  200. match, err := fileContainsPattern(path, regex)
  201. if err != nil {
  202. return nil // Skip files we can't read
  203. }
  204. if match {
  205. matches = append(matches, grepMatch{
  206. path: path,
  207. modTime: info.ModTime(),
  208. })
  209. if len(matches) >= 200 {
  210. return filepath.SkipAll
  211. }
  212. }
  213. return nil
  214. })
  215. if err != nil {
  216. return nil, err
  217. }
  218. return matches, nil
  219. }
  220. func fileContainsPattern(filePath string, pattern *regexp.Regexp) (bool, error) {
  221. file, err := os.Open(filePath)
  222. if err != nil {
  223. return false, err
  224. }
  225. defer file.Close()
  226. scanner := bufio.NewScanner(file)
  227. for scanner.Scan() {
  228. if pattern.MatchString(scanner.Text()) {
  229. return true, nil
  230. }
  231. }
  232. return false, scanner.Err()
  233. }
  234. func globToRegex(glob string) string {
  235. regexPattern := strings.ReplaceAll(glob, ".", "\\.")
  236. regexPattern = strings.ReplaceAll(regexPattern, "*", ".*")
  237. regexPattern = strings.ReplaceAll(regexPattern, "?", ".")
  238. re := regexp.MustCompile(`\{([^}]+)\}`)
  239. regexPattern = re.ReplaceAllStringFunc(regexPattern, func(match string) string {
  240. inner := match[1 : len(match)-1]
  241. return "(" + strings.ReplaceAll(inner, ",", "|") + ")"
  242. })
  243. return regexPattern
  244. }