Skip to main content

codive_tools/
glob.rs

1//! Glob tool for finding files matching patterns
2//!
3//! This tool finds files matching glob patterns like "*.rs" or "src/**/*.ts".
4
5use codive_core::tool::{Tool, ToolOutput};
6use async_trait::async_trait;
7use glob::glob as glob_match;
8use serde::Deserialize;
9use std::path::Path;
10use tracing::debug;
11
12/// Maximum number of results to return
13const DEFAULT_MAX_RESULTS: usize = 1000;
14
15/// Tool for finding files matching glob patterns
16pub struct GlobTool {
17    /// Maximum results to return
18    max_results: usize,
19}
20
21impl GlobTool {
22    /// Create a new GlobTool with default settings
23    pub fn new() -> Self {
24        Self {
25            max_results: DEFAULT_MAX_RESULTS,
26        }
27    }
28
29    /// Set the maximum number of results
30    pub fn with_max_results(mut self, max: usize) -> Self {
31        self.max_results = max;
32        self
33    }
34}
35
36impl Default for GlobTool {
37    fn default() -> Self {
38        Self::new()
39    }
40}
41
42/// Parameters for the glob tool
43#[derive(Debug, Deserialize)]
44struct GlobParams {
45    /// The glob pattern to match
46    pattern: String,
47    /// Optional base directory (default: current directory)
48    #[serde(default)]
49    path: Option<String>,
50}
51
52#[async_trait]
53impl Tool for GlobTool {
54    fn name(&self) -> &str {
55        "glob"
56    }
57
58    fn description(&self) -> &str {
59        "Find files matching a glob pattern. Supports patterns like '*.rs', 'src/**/*.ts', \
60         'test_*.py'. Use ** for recursive matching."
61    }
62
63    fn parameters_schema(&self) -> serde_json::Value {
64        serde_json::json!({
65            "type": "object",
66            "properties": {
67                "pattern": {
68                    "type": "string",
69                    "description": "The glob pattern to match (e.g., '*.rs', 'src/**/*.ts')"
70                },
71                "path": {
72                    "type": "string",
73                    "description": "Base directory to search in. Default: current directory"
74                }
75            },
76            "required": ["pattern"]
77        })
78    }
79
80    async fn execute(&self, params: serde_json::Value) -> ToolOutput {
81        // Parse parameters
82        let params: GlobParams = match serde_json::from_value(params) {
83            Ok(p) => p,
84            Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
85        };
86
87        // Build the full pattern
88        let full_pattern = if let Some(ref base_path) = params.path {
89            let base = Path::new(base_path);
90            if !base.exists() {
91                return ToolOutput::error(format!("Path does not exist: {}", base_path));
92            }
93            base.join(&params.pattern).to_string_lossy().into_owned()
94        } else {
95            params.pattern.clone()
96        };
97
98        debug!(pattern = %full_pattern, "Executing glob");
99
100        // Execute glob
101        let entries = match glob_match(&full_pattern) {
102            Ok(paths) => paths,
103            Err(e) => return ToolOutput::error(format!("Invalid glob pattern: {}", e)),
104        };
105
106        // Collect results
107        let mut results = Vec::new();
108        let mut truncated = false;
109
110        for entry in entries {
111            match entry {
112                Ok(path) => {
113                    if results.len() >= self.max_results {
114                        truncated = true;
115                        break;
116                    }
117                    results.push(path.display().to_string());
118                }
119                Err(e) => {
120                    // Log but continue on errors (e.g., permission denied)
121                    debug!(error = %e, "Glob entry error");
122                }
123            }
124        }
125
126        // Sort results for consistent output
127        results.sort();
128
129        // Format output
130        if results.is_empty() {
131            return ToolOutput::success("No files found matching pattern");
132        }
133
134        let mut output = format!("Found {} files:\n", results.len());
135        for path in &results {
136            output.push_str(path);
137            output.push('\n');
138        }
139
140        if truncated {
141            output.push_str(&format!(
142                "\n(Results truncated at {} files)",
143                self.max_results
144            ));
145        }
146
147        ToolOutput::success(output)
148    }
149}
150
151// ============================================================================
152// Tests
153// ============================================================================
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use std::fs;
159    use tempfile::tempdir;
160
161    #[test]
162    fn test_glob_tool_name() {
163        let tool = GlobTool::new();
164        assert_eq!(tool.name(), "glob");
165    }
166
167    #[test]
168    fn test_glob_schema() {
169        let tool = GlobTool::new();
170        let schema = tool.parameters_schema();
171        assert_eq!(schema["type"], "object");
172        assert!(schema["properties"]["pattern"].is_object());
173        assert_eq!(schema["required"][0], "pattern");
174    }
175
176    #[tokio::test]
177    async fn test_glob_find_files() {
178        let dir = tempdir().unwrap();
179        fs::write(dir.path().join("file1.txt"), "").unwrap();
180        fs::write(dir.path().join("file2.txt"), "").unwrap();
181        fs::write(dir.path().join("file3.rs"), "").unwrap();
182
183        let tool = GlobTool::new();
184        let output = tool
185            .execute(serde_json::json!({
186                "pattern": "*.txt",
187                "path": dir.path().to_str().unwrap()
188            }))
189            .await;
190
191        assert!(output.is_success());
192        assert!(output.content.contains("Found 2 files"));
193        assert!(output.content.contains("file1.txt"));
194        assert!(output.content.contains("file2.txt"));
195        assert!(!output.content.contains("file3.rs"));
196    }
197
198    #[tokio::test]
199    async fn test_glob_recursive() {
200        let dir = tempdir().unwrap();
201        fs::create_dir_all(dir.path().join("subdir")).unwrap();
202        fs::write(dir.path().join("file.txt"), "").unwrap();
203        fs::write(dir.path().join("subdir").join("nested.txt"), "").unwrap();
204
205        let tool = GlobTool::new();
206        let output = tool
207            .execute(serde_json::json!({
208                "pattern": "**/*.txt",
209                "path": dir.path().to_str().unwrap()
210            }))
211            .await;
212
213        assert!(output.is_success());
214        assert!(output.content.contains("nested.txt"));
215    }
216
217    #[tokio::test]
218    async fn test_glob_no_matches() {
219        let dir = tempdir().unwrap();
220        fs::write(dir.path().join("file.txt"), "").unwrap();
221
222        let tool = GlobTool::new();
223        let output = tool
224            .execute(serde_json::json!({
225                "pattern": "*.rs",
226                "path": dir.path().to_str().unwrap()
227            }))
228            .await;
229
230        assert!(output.is_success());
231        assert!(output.content.contains("No files found"));
232    }
233
234    #[tokio::test]
235    async fn test_glob_invalid_pattern() {
236        let tool = GlobTool::new();
237        let output = tool
238            .execute(serde_json::json!({
239                "pattern": "[invalid"
240            }))
241            .await;
242
243        assert!(output.is_error);
244        assert!(output.content.contains("Invalid glob pattern"));
245    }
246
247    #[tokio::test]
248    async fn test_glob_nonexistent_path() {
249        let tool = GlobTool::new();
250        let output = tool
251            .execute(serde_json::json!({
252                "pattern": "*.txt",
253                "path": "/nonexistent/path/12345"
254            }))
255            .await;
256
257        assert!(output.is_error);
258        assert!(output.content.contains("does not exist"));
259    }
260
261    #[tokio::test]
262    async fn test_glob_max_results() {
263        let dir = tempdir().unwrap();
264        for i in 0..10 {
265            fs::write(dir.path().join(format!("file{}.txt", i)), "").unwrap();
266        }
267
268        let tool = GlobTool::new().with_max_results(5);
269        let output = tool
270            .execute(serde_json::json!({
271                "pattern": "*.txt",
272                "path": dir.path().to_str().unwrap()
273            }))
274            .await;
275
276        assert!(output.is_success());
277        assert!(output.content.contains("Found 5 files"));
278        assert!(output.content.contains("truncated"));
279    }
280
281    #[tokio::test]
282    async fn test_glob_invalid_params() {
283        let tool = GlobTool::new();
284        let output = tool.execute(serde_json::json!({})).await;
285
286        assert!(output.is_error);
287        assert!(output.content.contains("Invalid parameters"));
288    }
289}