grep.go 9.1 KB

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