Skip to main content

adk_devtools/tools/
glob.rs

1//! `glob` — list workspace files matching a glob pattern.
2
3use std::path::{Component, Path, PathBuf};
4use std::sync::Arc;
5
6use adk_core::{Result, Tool, ToolContext};
7use async_trait::async_trait;
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_RESULTS: usize = 1000;
16
17/// Lists files matching a glob pattern (e.g. `src/**/*.rs`), relative to the
18/// workspace root or an optional sub-directory. Files matching the workspace's
19/// exclusion patterns ([`Workspace::exclude_globs`]) are not listed.
20pub struct GlobTool {
21    workspace: Workspace,
22}
23
24impl GlobTool {
25    /// Create a `glob` tool bound to `workspace`.
26    pub fn new(workspace: Workspace) -> Self {
27        Self { workspace }
28    }
29}
30
31#[async_trait]
32impl Tool for GlobTool {
33    fn name(&self) -> &str {
34        "glob"
35    }
36
37    /// Lists workspace paths on disk.
38    fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
39        adk_core::egress::ToolEgress::None
40    }
41
42    fn description(&self) -> &str {
43        "List files matching a glob pattern (e.g. 'src/**/*.rs'). Returns paths \
44         relative to the workspace root. The pattern is relative to the workspace \
45         and may not contain '..' or an absolute path."
46    }
47
48    fn is_read_only(&self) -> bool {
49        true
50    }
51
52    fn is_concurrency_safe(&self) -> bool {
53        true
54    }
55
56    fn parameters_schema(&self) -> Option<Value> {
57        Some(json!({
58            "type": "object",
59            "properties": {
60                "pattern": { "type": "string", "description": "Glob pattern, e.g. '**/*.toml'." },
61                "path": { "type": "string", "description": "Optional sub-directory to search within." }
62            },
63            "required": ["pattern"]
64        }))
65    }
66
67    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
68        let pattern = require_str(&args, "pattern")?;
69        // `glob` follows `..` and absolute prefixes literally, so either would list
70        // directories outside the workspace.
71        let escapes = Path::new(&pattern).components().any(|component| match component {
72            Component::Prefix(_) | Component::RootDir | Component::ParentDir => true,
73            Component::CurDir | Component::Normal(_) => false,
74        });
75        if escapes {
76            return Err(DevToolError::PathEscape(pattern).into());
77        }
78        let base = match args.get("path").and_then(Value::as_str) {
79            Some(sub) => self.workspace.resolve(sub)?,
80            None => self.workspace.root().to_path_buf(),
81        };
82
83        let matcher = glob::Pattern::new(&pattern)
84            .map_err(|e| DevToolError::Other(format!("invalid glob pattern: {e}")))?;
85        // `*` and `?` stay within one component, as `glob::glob` treats them, so `src/*.rs`
86        // cannot reach `src/a/b.rs`; `**` still spans directories.
87        let options = glob::MatchOptions { require_literal_separator: true, ..Default::default() };
88
89        // Walk from the base and match the path relative to it. Expanding the base through
90        // `glob::glob` broke on Windows, where a canonical root carries the `\\?\` verbatim
91        // prefix and `?` is a wildcard. The pattern's literal leading components narrow the
92        // walk, so `src/**/*.rs` never visits `target/`.
93        let literal: PathBuf = Path::new(&pattern)
94            .components()
95            .take_while(|component| match component {
96                Component::Normal(part) => !part.to_string_lossy().contains(['*', '?', '[']),
97                Component::Prefix(_)
98                | Component::RootDir
99                | Component::CurDir
100                | Component::ParentDir => false,
101            })
102            .collect();
103        let start = base.join(literal);
104
105        let mut matches = Vec::new();
106        let mut truncated = false;
107        if start.exists() {
108            // Symlinked directories are listed but not descended: one that points outside
109            // the workspace would otherwise be walked before containment is checked.
110            for entry in WalkDir::new(&start).sort_by_file_name().into_iter().flatten() {
111                let path = entry.path();
112                let Ok(relative) = path.strip_prefix(&base) else { continue };
113                if relative.as_os_str().is_empty()
114                    || !matcher.matches_path_with(relative, options)
115                    || self.workspace.is_excluded(path)
116                {
117                    continue;
118                }
119                // A symlink can point anywhere.
120                let contained = std::fs::canonicalize(path)
121                    .is_ok_and(|canonical| canonical.starts_with(self.workspace.root()));
122                if !contained {
123                    continue;
124                }
125                if matches.len() >= MAX_RESULTS {
126                    truncated = true;
127                    break;
128                }
129                matches.push(self.workspace.display(path));
130            }
131        }
132
133        Ok(json!({
134            "pattern": pattern,
135            "matches": matches,
136            "count": matches.len(),
137            "truncated": truncated,
138        }))
139    }
140}