codive-tools 0.1.0

Tool implementations for Codive
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! Grep tool for searching file contents
//!
//! This tool searches for patterns in files using regular expressions.

use codive_core::tool::{Tool, ToolOutput};
use async_trait::async_trait;
use regex::Regex;
use serde::Deserialize;
use std::path::Path;
use tracing::debug;
use walkdir::WalkDir;

/// Maximum number of matches to return
const DEFAULT_MAX_MATCHES: usize = 100;

/// Maximum number of context lines
const DEFAULT_CONTEXT_LINES: usize = 2;

/// Tool for searching file contents with regex
pub struct GrepTool {
    /// Maximum matches to return
    max_matches: usize,
    /// Number of context lines before/after
    context_lines: usize,
}

impl GrepTool {
    /// Create a new GrepTool with default settings
    pub fn new() -> Self {
        Self {
            max_matches: DEFAULT_MAX_MATCHES,
            context_lines: DEFAULT_CONTEXT_LINES,
        }
    }

    /// Set the maximum number of matches
    pub fn with_max_matches(mut self, max: usize) -> Self {
        self.max_matches = max;
        self
    }

    /// Set the number of context lines
    pub fn with_context_lines(mut self, lines: usize) -> Self {
        self.context_lines = lines;
        self
    }
}

impl Default for GrepTool {
    fn default() -> Self {
        Self::new()
    }
}

/// Parameters for the grep tool
#[derive(Debug, Deserialize)]
struct GrepParams {
    /// The regex pattern to search for
    pattern: String,
    /// File or directory to search in
    path: String,
    /// Optional file extension filter (e.g., "rs", "py")
    #[serde(default)]
    extension: Option<String>,
    /// Whether the search should be case-insensitive
    #[serde(default)]
    case_insensitive: bool,
}

/// A match result
struct Match {
    file: String,
    line_num: usize,
    line: String,
}

#[async_trait]
impl Tool for GrepTool {
    fn name(&self) -> &str {
        "grep"
    }

    fn description(&self) -> &str {
        "Search for a regex pattern in files. Returns matching lines with file paths \
         and line numbers. Can search a single file or recursively search a directory."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "The regex pattern to search for"
                },
                "path": {
                    "type": "string",
                    "description": "File or directory to search in"
                },
                "extension": {
                    "type": "string",
                    "description": "Optional file extension filter (e.g., 'rs', 'py')"
                },
                "case_insensitive": {
                    "type": "boolean",
                    "description": "Case-insensitive search. Default: false"
                }
            },
            "required": ["pattern", "path"]
        })
    }

    async fn execute(&self, params: serde_json::Value) -> ToolOutput {
        // Parse parameters
        let params: GrepParams = match serde_json::from_value(params) {
            Ok(p) => p,
            Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
        };

        // Build regex pattern
        let pattern_str = if params.case_insensitive {
            format!("(?i){}", params.pattern)
        } else {
            params.pattern.clone()
        };

        let regex = match Regex::new(&pattern_str) {
            Ok(r) => r,
            Err(e) => return ToolOutput::error(format!("Invalid regex pattern: {}", e)),
        };

        let search_path = Path::new(&params.path);
        debug!(path = %search_path.display(), pattern = %params.pattern, "Executing grep");

        if !search_path.exists() {
            return ToolOutput::error(format!("Path does not exist: {}", params.path));
        }

        // Collect matches
        let mut matches = Vec::new();
        let mut files_searched = 0;
        let mut truncated = false;

        // Search files
        if search_path.is_file() {
            // Single file search
            files_searched = 1;
            if let Some(file_matches) = search_file(search_path, &regex) {
                for m in file_matches {
                    matches.push(m);
                    if matches.len() >= self.max_matches {
                        truncated = true;
                        break;
                    }
                }
            }
        } else {
            // Directory search
            for entry in WalkDir::new(search_path)
                .follow_links(false)
                .into_iter()
                .filter_map(|e| e.ok())
            {
                if !entry.file_type().is_file() {
                    continue;
                }

                let path = entry.path();

                // Filter by extension if specified
                if let Some(ref ext) = params.extension {
                    if path.extension().map(|e| e.to_str().unwrap_or("")) != Some(ext.as_str()) {
                        continue;
                    }
                }

                // Skip binary and hidden files
                if is_likely_binary(path) || is_hidden(path) {
                    continue;
                }

                files_searched += 1;
                if let Some(file_matches) = search_file(path, &regex) {
                    for m in file_matches {
                        matches.push(m);
                        if matches.len() >= self.max_matches {
                            truncated = true;
                            break;
                        }
                    }
                    if truncated {
                        break;
                    }
                }
            }
        }

        // Format output
        if matches.is_empty() {
            return ToolOutput::success(format!(
                "No matches found for pattern '{}' in {} files",
                params.pattern, files_searched
            ));
        }

        let mut output = format!(
            "Found {} matches in {} files:\n\n",
            matches.len(),
            files_searched
        );

        let mut current_file = String::new();
        for m in &matches {
            if m.file != current_file {
                if !current_file.is_empty() {
                    output.push('\n');
                }
                output.push_str(&format!("{}:\n", m.file));
                current_file = m.file.clone();
            }
            output.push_str(&format!("  {}:{}\n", m.line_num, m.line));
        }

        if truncated {
            output.push_str(&format!(
                "\n(Results truncated at {} matches)",
                self.max_matches
            ));
        }

        ToolOutput::success(output)
    }
}

/// Search a single file for matches
fn search_file(path: &Path, regex: &Regex) -> Option<Vec<Match>> {
    let content = std::fs::read_to_string(path).ok()?;

    let mut matches = Vec::new();
    let file_str = path.display().to_string();

    for (line_num, line) in content.lines().enumerate() {
        if regex.is_match(line) {
            matches.push(Match {
                file: file_str.clone(),
                line_num: line_num + 1,
                line: line.to_string(),
            });
        }
    }

    if matches.is_empty() {
        None
    } else {
        Some(matches)
    }
}

/// Check if a path is likely a binary file
fn is_likely_binary(path: &Path) -> bool {
    let binary_extensions = [
        "exe", "dll", "so", "dylib", "bin", "o", "a", "obj", "class", "jar", "war", "ear", "pyc",
        "pyo", "whl", "egg", "png", "jpg", "jpeg", "gif", "ico", "bmp", "tiff", "webp", "svg",
        "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "zip", "tar", "gz", "bz2", "xz", "7z",
        "rar", "mp3", "mp4", "avi", "mov", "mkv", "wav", "flac", "ttf", "otf", "woff", "woff2",
        "eot", "lock",
    ];

    if let Some(ext) = path.extension() {
        if let Some(ext_str) = ext.to_str() {
            return binary_extensions.contains(&ext_str.to_lowercase().as_str());
        }
    }
    false
}

/// Check if a file/directory name is hidden (starts with .)
/// Only checks the file name itself, not parent directories (to support temp dirs)
fn is_hidden(path: &Path) -> bool {
    path.file_name()
        .and_then(|n| n.to_str())
        .map(|s| s.starts_with('.'))
        .unwrap_or(false)
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn test_grep_tool_name() {
        let tool = GrepTool::new();
        assert_eq!(tool.name(), "grep");
    }

    #[test]
    fn test_grep_schema() {
        let tool = GrepTool::new();
        let schema = tool.parameters_schema();
        assert_eq!(schema["type"], "object");
        assert!(schema["properties"]["pattern"].is_object());
        assert!(schema["properties"]["path"].is_object());
        assert_eq!(schema["required"][0], "pattern");
        assert_eq!(schema["required"][1], "path");
    }

    #[tokio::test]
    async fn test_grep_single_file() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        fs::write(&file_path, "line 1\nfind me here\nline 3\nfind me again\n").unwrap();

        let tool = GrepTool::new();
        let output = tool
            .execute(serde_json::json!({
                "pattern": "find me",
                "path": file_path.to_str().unwrap()
            }))
            .await;

        assert!(output.is_success());
        assert!(output.content.contains("Found 2 matches"));
        assert!(output.content.contains("find me here"));
        assert!(output.content.contains("find me again"));
    }

    #[tokio::test]
    async fn test_grep_directory() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("file1.txt"), "hello world\n").unwrap();
        fs::write(dir.path().join("file2.txt"), "goodbye world\n").unwrap();
        fs::write(dir.path().join("file3.txt"), "hello again\n").unwrap();

        let tool = GrepTool::new();
        let output = tool
            .execute(serde_json::json!({
                "pattern": "hello",
                "path": dir.path().to_str().unwrap()
            }))
            .await;

        assert!(output.is_success());
        // Check that we found both matches (file1 and file3 contain "hello")
        assert!(
            output.content.contains("hello world") && output.content.contains("hello again"),
            "Expected to find both 'hello' matches. Output: {}",
            output.content
        );
    }

    #[tokio::test]
    async fn test_grep_with_extension_filter() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("file.rs"), "fn main() {}\n").unwrap();
        fs::write(dir.path().join("file.py"), "def main():\n").unwrap();

        let tool = GrepTool::new();
        let output = tool
            .execute(serde_json::json!({
                "pattern": "main",
                "path": dir.path().to_str().unwrap(),
                "extension": "rs"
            }))
            .await;

        assert!(output.is_success(), "Output: {}", output.content);
        assert!(
            output.content.contains("fn main()"),
            "Expected to find 'fn main()'. Output: {}",
            output.content
        );
        assert!(output.content.contains("file.rs"));
        assert!(!output.content.contains("file.py"));
    }

    #[tokio::test]
    async fn test_grep_case_insensitive() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        fs::write(&file_path, "Hello World\nhello world\nHELLO WORLD\n").unwrap();

        let tool = GrepTool::new();
        let output = tool
            .execute(serde_json::json!({
                "pattern": "hello",
                "path": file_path.to_str().unwrap(),
                "case_insensitive": true
            }))
            .await;

        assert!(output.is_success());
        assert!(output.content.contains("Found 3 matches"));
    }

    #[tokio::test]
    async fn test_grep_no_matches() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("file.txt"), "hello world\n").unwrap();

        let tool = GrepTool::new();
        let output = tool
            .execute(serde_json::json!({
                "pattern": "notfound",
                "path": dir.path().to_str().unwrap()
            }))
            .await;

        assert!(output.is_success());
        assert!(output.content.contains("No matches found"));
    }

    #[tokio::test]
    async fn test_grep_invalid_regex() {
        let tool = GrepTool::new();
        let output = tool
            .execute(serde_json::json!({
                "pattern": "[invalid",
                "path": "/tmp"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("Invalid regex"));
    }

    #[tokio::test]
    async fn test_grep_nonexistent_path() {
        let tool = GrepTool::new();
        let output = tool
            .execute(serde_json::json!({
                "pattern": "test",
                "path": "/nonexistent/path/12345"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("does not exist"));
    }

    #[tokio::test]
    async fn test_grep_max_matches() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        let content = "match\n".repeat(20);
        fs::write(&file_path, content).unwrap();

        let tool = GrepTool::new().with_max_matches(5);
        let output = tool
            .execute(serde_json::json!({
                "pattern": "match",
                "path": file_path.to_str().unwrap()
            }))
            .await;

        assert!(output.is_success(), "Output: {}", output.content);
        // Count how many times "match" appears in output (should be limited to 5)
        let match_count = output.content.matches(":match").count();
        assert_eq!(
            match_count, 5,
            "Expected 5 matches but got {}. Output: {}",
            match_count, output.content
        );
        assert!(
            output.content.contains("truncated"),
            "Expected 'truncated' in output: {}",
            output.content
        );
    }

    #[test]
    fn test_is_likely_binary() {
        assert!(is_likely_binary(Path::new("file.exe")));
        assert!(is_likely_binary(Path::new("image.png")));
        assert!(is_likely_binary(Path::new("archive.zip")));
        assert!(!is_likely_binary(Path::new("code.rs")));
        assert!(!is_likely_binary(Path::new("readme.md")));
    }

    #[test]
    fn test_is_hidden() {
        assert!(is_hidden(Path::new(".gitignore")));
        assert!(is_hidden(Path::new("path/to/.hidden")));
        assert!(!is_hidden(Path::new("normal/path/file.txt")));
        // Files in hidden directories are NOT hidden (we only check the file name)
        assert!(!is_hidden(Path::new(".git/config")));
    }
}