codive-tools 0.1.0

Tool implementations for Codive
Documentation
//! Glob tool for finding files matching patterns
//!
//! This tool finds files matching glob patterns like "*.rs" or "src/**/*.ts".

use codive_core::tool::{Tool, ToolOutput};
use async_trait::async_trait;
use glob::glob as glob_match;
use serde::Deserialize;
use std::path::Path;
use tracing::debug;

/// Maximum number of results to return
const DEFAULT_MAX_RESULTS: usize = 1000;

/// Tool for finding files matching glob patterns
pub struct GlobTool {
    /// Maximum results to return
    max_results: usize,
}

impl GlobTool {
    /// Create a new GlobTool with default settings
    pub fn new() -> Self {
        Self {
            max_results: DEFAULT_MAX_RESULTS,
        }
    }

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

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

/// Parameters for the glob tool
#[derive(Debug, Deserialize)]
struct GlobParams {
    /// The glob pattern to match
    pattern: String,
    /// Optional base directory (default: current directory)
    #[serde(default)]
    path: Option<String>,
}

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

    fn description(&self) -> &str {
        "Find files matching a glob pattern. Supports patterns like '*.rs', 'src/**/*.ts', \
         'test_*.py'. Use ** for recursive matching."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "The glob pattern to match (e.g., '*.rs', 'src/**/*.ts')"
                },
                "path": {
                    "type": "string",
                    "description": "Base directory to search in. Default: current directory"
                }
            },
            "required": ["pattern"]
        })
    }

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

        // Build the full pattern
        let full_pattern = if let Some(ref base_path) = params.path {
            let base = Path::new(base_path);
            if !base.exists() {
                return ToolOutput::error(format!("Path does not exist: {}", base_path));
            }
            base.join(&params.pattern).to_string_lossy().into_owned()
        } else {
            params.pattern.clone()
        };

        debug!(pattern = %full_pattern, "Executing glob");

        // Execute glob
        let entries = match glob_match(&full_pattern) {
            Ok(paths) => paths,
            Err(e) => return ToolOutput::error(format!("Invalid glob pattern: {}", e)),
        };

        // Collect results
        let mut results = Vec::new();
        let mut truncated = false;

        for entry in entries {
            match entry {
                Ok(path) => {
                    if results.len() >= self.max_results {
                        truncated = true;
                        break;
                    }
                    results.push(path.display().to_string());
                }
                Err(e) => {
                    // Log but continue on errors (e.g., permission denied)
                    debug!(error = %e, "Glob entry error");
                }
            }
        }

        // Sort results for consistent output
        results.sort();

        // Format output
        if results.is_empty() {
            return ToolOutput::success("No files found matching pattern");
        }

        let mut output = format!("Found {} files:\n", results.len());
        for path in &results {
            output.push_str(path);
            output.push('\n');
        }

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

        ToolOutput::success(output)
    }
}

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

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

    #[test]
    fn test_glob_tool_name() {
        let tool = GlobTool::new();
        assert_eq!(tool.name(), "glob");
    }

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

    #[tokio::test]
    async fn test_glob_find_files() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("file1.txt"), "").unwrap();
        fs::write(dir.path().join("file2.txt"), "").unwrap();
        fs::write(dir.path().join("file3.rs"), "").unwrap();

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

        assert!(output.is_success());
        assert!(output.content.contains("Found 2 files"));
        assert!(output.content.contains("file1.txt"));
        assert!(output.content.contains("file2.txt"));
        assert!(!output.content.contains("file3.rs"));
    }

    #[tokio::test]
    async fn test_glob_recursive() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("subdir")).unwrap();
        fs::write(dir.path().join("file.txt"), "").unwrap();
        fs::write(dir.path().join("subdir").join("nested.txt"), "").unwrap();

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

        assert!(output.is_success());
        assert!(output.content.contains("nested.txt"));
    }

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

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

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

    #[tokio::test]
    async fn test_glob_invalid_pattern() {
        let tool = GlobTool::new();
        let output = tool
            .execute(serde_json::json!({
                "pattern": "[invalid"
            }))
            .await;

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

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

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

    #[tokio::test]
    async fn test_glob_max_results() {
        let dir = tempdir().unwrap();
        for i in 0..10 {
            fs::write(dir.path().join(format!("file{}.txt", i)), "").unwrap();
        }

        let tool = GlobTool::new().with_max_results(5);
        let output = tool
            .execute(serde_json::json!({
                "pattern": "*.txt",
                "path": dir.path().to_str().unwrap()
            }))
            .await;

        assert!(output.is_success());
        assert!(output.content.contains("Found 5 files"));
        assert!(output.content.contains("truncated"));
    }

    #[tokio::test]
    async fn test_glob_invalid_params() {
        let tool = GlobTool::new();
        let output = tool.execute(serde_json::json!({})).await;

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