codive-tools 0.1.0

Tool implementations for Codive
Documentation
//! WriteFile tool for writing content to files
//!
//! This tool writes content to files, creating parent directories if needed.

use codive_core::tool::{Tool, ToolOutput};
use async_trait::async_trait;
use serde::Deserialize;
use std::path::Path;
use tokio::fs;
use tracing::debug;

/// Maximum content size to write (10MB)
const MAX_CONTENT_SIZE: usize = 10 * 1024 * 1024;

/// Tool for writing file contents
pub struct WriteFileTool {
    /// Maximum content size to write
    max_content_size: usize,
    /// Whether to create parent directories
    create_parents: bool,
}

impl WriteFileTool {
    /// Create a new WriteFileTool with default settings
    pub fn new() -> Self {
        Self {
            max_content_size: MAX_CONTENT_SIZE,
            create_parents: true,
        }
    }

    /// Set the maximum content size
    pub fn with_max_content_size(mut self, size: usize) -> Self {
        self.max_content_size = size;
        self
    }

    /// Set whether to create parent directories
    pub fn with_create_parents(mut self, create: bool) -> Self {
        self.create_parents = create;
        self
    }
}

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

/// Parameters for the write_file tool
#[derive(Debug, Deserialize)]
struct WriteFileParams {
    /// Path to the file to write
    path: String,
    /// Content to write to the file
    content: String,
    /// Whether to append instead of overwrite (default: false)
    #[serde(default)]
    append: bool,
}

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

    fn description(&self) -> &str {
        "Write content to a file. Creates the file if it doesn't exist. \
         Parent directories are created automatically. \
         Use append=true to append instead of overwriting."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "The path to the file to write"
                },
                "content": {
                    "type": "string",
                    "description": "The content to write to the file"
                },
                "append": {
                    "type": "boolean",
                    "description": "If true, append to the file instead of overwriting. Default: false"
                }
            },
            "required": ["path", "content"]
        })
    }

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

        // Check content size
        if params.content.len() > self.max_content_size {
            return ToolOutput::error(format!(
                "Content too large: {} bytes (max: {} bytes)",
                params.content.len(),
                self.max_content_size
            ));
        }

        let path = Path::new(&params.path);
        debug!(path = %path.display(), append = params.append, "Writing file");

        // Create parent directories if needed
        if self.create_parents {
            if let Some(parent) = path.parent() {
                if !parent.exists() {
                    if let Err(e) = fs::create_dir_all(parent).await {
                        return ToolOutput::error(format!(
                            "Failed to create parent directories: {}",
                            e
                        ));
                    }
                }
            }
        }

        // Capture old content for diff (before any writes)
        let old_content = fs::read_to_string(path).await.ok();

        // Write or append to the file
        let (result, final_content) = if params.append {
            // Read existing content and append
            let existing = old_content.clone().unwrap_or_default();
            let new_content = format!("{}{}", existing, params.content);
            let res = fs::write(path, &new_content).await;
            (res, new_content)
        } else {
            let res = fs::write(path, &params.content).await;
            (res, params.content.clone())
        };

        match result {
            Ok(()) => {
                let bytes = params.content.len();
                let action = if params.append { "Appended" } else { "Wrote" };
                ToolOutput::success(format!("{} {} bytes to {}", action, bytes, path.display()))
                    .with_file_change(params.path, old_content, final_content)
            }
            Err(e) => ToolOutput::error(format!("Failed to write file: {}", e)),
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::{tempdir, NamedTempFile};

    #[test]
    fn test_write_file_tool_name() {
        let tool = WriteFileTool::new();
        assert_eq!(tool.name(), "write_file");
    }

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

    #[tokio::test]
    async fn test_write_new_file() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");

        let tool = WriteFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "content": "hello world"
            }))
            .await;

        assert!(output.is_success());
        assert!(output.content.contains("Wrote"));
        assert!(output.content.contains("11 bytes"));

        // Verify file content
        let content = std::fs::read_to_string(&file_path).unwrap();
        assert_eq!(content, "hello world");
    }

    #[tokio::test]
    async fn test_write_overwrite() {
        let file = NamedTempFile::new().unwrap();
        std::fs::write(file.path(), "old content").unwrap();

        let tool = WriteFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file.path().to_str().unwrap(),
                "content": "new content"
            }))
            .await;

        assert!(output.is_success());

        let content = std::fs::read_to_string(file.path()).unwrap();
        assert_eq!(content, "new content");
    }

    #[tokio::test]
    async fn test_write_append() {
        let file = NamedTempFile::new().unwrap();
        std::fs::write(file.path(), "hello").unwrap();

        let tool = WriteFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file.path().to_str().unwrap(),
                "content": " world",
                "append": true
            }))
            .await;

        assert!(output.is_success());
        assert!(output.content.contains("Appended"));

        let content = std::fs::read_to_string(file.path()).unwrap();
        assert_eq!(content, "hello world");
    }

    #[tokio::test]
    async fn test_write_create_parents() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("nested").join("dir").join("file.txt");

        let tool = WriteFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "content": "test"
            }))
            .await;

        assert!(output.is_success());
        assert!(file_path.exists());
    }

    #[tokio::test]
    async fn test_write_content_too_large() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");

        let tool = WriteFileTool::new().with_max_content_size(10);
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "content": "this content is too large"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("too large"));
    }

    #[tokio::test]
    async fn test_write_invalid_params() {
        let tool = WriteFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": "/tmp/test.txt"
            }))
            .await;

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

    #[tokio::test]
    async fn test_write_empty_content() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("empty.txt");

        let tool = WriteFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file_path.to_str().unwrap(),
                "content": ""
            }))
            .await;

        assert!(output.is_success());
        assert!(output.content.contains("0 bytes"));
    }
}