ryo-mutations 0.1.0

[experimental] Code transformation primitives for Rust source code
Documentation
//! CreateModMutation
//!
//! Create a new module with content.

use ryo_symbol::SymbolId;

use crate::Mutation;

/// Create a new module with content
#[derive(Debug, Clone)]
pub struct CreateModMutation {
    /// Parent module SymbolId
    pub parent: SymbolId,
    /// Name of the new module
    pub name: String,
    /// Content of the new module (raw source code)
    pub content: String,
    /// Whether the module is public
    pub is_pub: bool,
}

impl CreateModMutation {
    pub fn new(parent: SymbolId, name: impl Into<String>) -> Self {
        Self {
            parent,
            name: name.into(),
            content: String::new(),
            is_pub: false,
        }
    }

    pub fn with_content(mut self, content: impl Into<String>) -> Self {
        self.content = content.into();
        self
    }

    pub fn public(mut self) -> Self {
        self.is_pub = true;
        self
    }
}

impl Mutation for CreateModMutation {
    fn mutation_type(&self) -> &'static str {
        "CreateMod"
    }

    fn describe(&self) -> String {
        let vis = if self.is_pub { "pub " } else { "" };
        format!("Create {}mod '{}' in {}", vis, self.name, self.parent)
    }

    fn box_clone(&self) -> Box<dyn Mutation> {
        Box::new(self.clone())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ryo_symbol::{SymbolKind, SymbolPath, SymbolRegistry};

    #[test]
    fn test_create_mod_mutation_describe() {
        // Create a registry and register a parent module
        let mut registry = SymbolRegistry::new();
        let parent_path = SymbolPath::parse("test_crate").unwrap();
        let parent_id = registry.register(parent_path, SymbolKind::Mod).unwrap();

        let mutation = CreateModMutation::new(parent_id, "models")
            .with_content("pub struct Config {}")
            .public();
        assert!(mutation.describe().contains("pub mod"));
        assert!(mutation.describe().contains("models"));
    }
}