adk_devtools/tools/
grep.rs1use std::sync::Arc;
4
5use adk_core::{Result, Tool, ToolContext};
6use async_trait::async_trait;
7use regex::Regex;
8use serde_json::{Value, json};
9use walkdir::WalkDir;
10
11use crate::error::DevToolError;
12use crate::tools::read::require_str;
13use crate::workspace::Workspace;
14
15const MAX_MATCHES: usize = 500;
16const MAX_FILE_BYTES: u64 = 5 * 1_048_576;
17const SKIP_DIRS: &[&str] = &[".git", "target", "node_modules", ".venv", "dist", "build"];
18
19pub struct GrepTool {
23 workspace: Workspace,
24}
25
26impl GrepTool {
27 pub fn new(workspace: Workspace) -> Self {
29 Self { workspace }
30 }
31}
32
33#[async_trait]
34impl Tool for GrepTool {
35 fn name(&self) -> &str {
36 "grep"
37 }
38
39 fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
41 adk_core::egress::ToolEgress::None
42 }
43
44 fn description(&self) -> &str {
45 "Search file contents for a regular expression. Returns matching lines as \
46 'path:line: text'. Optionally restrict to a sub-path and/or a glob over file names."
47 }
48
49 fn is_read_only(&self) -> bool {
50 true
51 }
52
53 fn is_concurrency_safe(&self) -> bool {
54 true
55 }
56
57 fn parameters_schema(&self) -> Option<Value> {
58 Some(json!({
59 "type": "object",
60 "properties": {
61 "pattern": { "type": "string", "description": "Regular expression to search for." },
62 "path": { "type": "string", "description": "Optional sub-directory to search within." },
63 "glob": { "type": "string", "description": "Optional glob over file names, e.g. '*.rs'." },
64 "case_insensitive": { "type": "boolean", "description": "Case-insensitive match (default false)." }
65 },
66 "required": ["pattern"]
67 }))
68 }
69
70 async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
71 let pattern = require_str(&args, "pattern")?;
72 let case_insensitive =
73 args.get("case_insensitive").and_then(Value::as_bool).unwrap_or(false);
74 let name_glob = args
75 .get("glob")
76 .and_then(Value::as_str)
77 .map(glob::Pattern::new)
78 .transpose()
79 .map_err(|e| DevToolError::Other(format!("invalid glob: {e}")))?;
80
81 let re = regex::RegexBuilder::new(&pattern)
82 .case_insensitive(case_insensitive)
83 .build()
84 .map_err(|e| DevToolError::Other(format!("invalid regex: {e}")))?;
85
86 let base = match args.get("path").and_then(Value::as_str) {
87 Some(sub) => self.workspace.resolve(sub)?,
88 None => self.workspace.root().to_path_buf(),
89 };
90
91 let (matches, truncated) = search(&base, &re, name_glob.as_ref(), &self.workspace);
92
93 Ok(json!({
94 "pattern": pattern,
95 "matches": matches,
96 "count": matches.len(),
97 "truncated": truncated,
98 }))
99 }
100}
101
102fn search(
103 base: &std::path::Path,
104 re: &Regex,
105 name_glob: Option<&glob::Pattern>,
106 ws: &Workspace,
107) -> (Vec<String>, bool) {
108 let mut out = Vec::new();
109 let walker = WalkDir::new(base).into_iter().filter_entry(|e| {
110 !e.file_name().to_str().map(|n| SKIP_DIRS.contains(&n)).unwrap_or(false)
111 && !ws.is_excluded(e.path())
112 });
113
114 for entry in walker.filter_map(std::result::Result::ok) {
115 if !entry.file_type().is_file() {
116 continue;
117 }
118 let path = entry.path();
119 if let Some(g) = name_glob {
120 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
121 if !g.matches(name) {
122 continue;
123 }
124 }
125 if entry.metadata().map(|m| m.len() > MAX_FILE_BYTES).unwrap_or(true) {
126 continue;
127 }
128 let Ok(contents) = std::fs::read_to_string(path) else {
129 continue; };
131 let display = ws.display(path);
132 for (idx, line) in contents.lines().enumerate() {
133 if re.is_match(line) {
134 out.push(format!("{}:{}: {}", display, idx + 1, line.trim_end()));
135 if out.len() >= MAX_MATCHES {
136 return (out, true);
137 }
138 }
139 }
140 }
141 (out, false)
142}