Skip to main content

ggen_core/codegen_lib/
rule.rs

1//! Core rule abstraction for composable code generation
2
3use crate::codegen_lib::{GeneratedFile, GenerationMode, Queryable, Renderable, Result};
4use std::path::PathBuf;
5
6/// A composable code generation rule
7///
8/// Combines a query (Q) and a template (T) to generate files.
9/// This is the core abstraction: all code generation rules use this pattern.
10///
11/// # Type Parameters
12/// * `Q` - Query type implementing `Queryable`
13/// * `T` - Template type implementing `Renderable`
14#[derive(Debug)]
15pub struct Rule<Q: Queryable, T: Renderable> {
16    /// Rule name (e.g., "jpa-entities", "repositories")
17    name: String,
18    /// Query executor
19    query: Q,
20    /// Template renderer
21    template: T,
22    /// Output file path pattern (may contain {{ }} for variable substitution)
23    output_file: PathBuf,
24    /// Generation mode (Overwrite, Append, SkipIfExists)
25    mode: GenerationMode,
26}
27
28impl<Q: Queryable, T: Renderable> Rule<Q, T> {
29    /// Create a new rule
30    pub fn new(
31        name: impl Into<String>, query: Q, template: T, output_file: impl Into<PathBuf>,
32        mode: GenerationMode,
33    ) -> Self {
34        Self {
35            name: name.into(),
36            query,
37            template,
38            output_file: output_file.into(),
39            mode,
40        }
41    }
42
43    /// Execute the rule and generate files
44    ///
45    /// # Process
46    /// 1. Execute query to get bindings
47    /// 2. For each binding set:
48    ///    - Render template with bindings → content
49    ///    - Render output file path with bindings → actual path
50    ///    - Create GeneratedFile
51    /// 3. Return all generated files
52    pub fn execute(&self) -> Result<Vec<GeneratedFile>> {
53        // Execute query to get all binding sets
54        let binding_sets = self.query.execute()?;
55
56        // Render template for each binding set
57        let files = binding_sets
58            .iter()
59            .map(|bindings| {
60                // Render template content
61                let content = self.template.render(bindings)?;
62
63                // Render output file path with variable substitution
64                let path = self.output_file.to_string_lossy().to_string();
65                let rendered_path = bindings.iter().fold(path, |acc, (key, value)| {
66                    acc.replace(&format!("{{{{{}}}}}", key), value)
67                });
68
69                Ok(GeneratedFile::new(
70                    PathBuf::from(rendered_path),
71                    content,
72                    self.name.clone(),
73                ))
74            })
75            .collect::<Result<Vec<_>>>()?;
76
77        Ok(files)
78    }
79
80    /// Get rule metadata
81    pub fn name(&self) -> &str {
82        &self.name
83    }
84
85    pub fn mode(&self) -> GenerationMode {
86        self.mode
87    }
88
89    pub fn output_pattern(&self) -> &PathBuf {
90        &self.output_file
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use std::collections::HashMap;
98
99    // Chicago TDD: Real inline query implementation (not a test double)
100    struct InlineQuery {
101        name: String,
102        bindings: Vec<HashMap<String, String>>,
103    }
104
105    impl Queryable for InlineQuery {
106        fn execute(&self) -> Result<Vec<HashMap<String, String>>> {
107            // Real query execution that returns actual bindings
108            Ok(self.bindings.clone())
109        }
110
111        fn name(&self) -> &str {
112            &self.name
113        }
114    }
115
116    // Chicago TDD: Real template implementation using actual Tera-like rendering
117    struct InlineTemplate {
118        name: String,
119        template_str: String,
120    }
121
122    impl Renderable for InlineTemplate {
123        fn render(&self, bindings: &HashMap<String, String>) -> Result<String> {
124            // Real template rendering - substitute bindings into template
125            let mut result = self.template_str.clone();
126            for (key, value) in bindings {
127                let placeholder = format!("{{{{{}}}}}", key);
128                result = result.replace(&placeholder, value);
129            }
130            Ok(result)
131        }
132
133        fn name(&self) -> &str {
134            &self.name
135        }
136    }
137
138    #[test]
139    fn test_rule_creation_with_real_query_and_template() {
140        // Chicago TDD: Use real query and template implementations
141        let mut bindings = HashMap::new();
142        bindings.insert("className".to_string(), "TestClass".to_string());
143
144        let query = InlineQuery {
145            name: "test-query".to_string(),
146            bindings: vec![bindings],
147        };
148
149        let template = InlineTemplate {
150            name: "test-template".to_string(),
151            template_str: "public class {{className}} {\n}\n".to_string(),
152        };
153
154        let rule = Rule::new(
155            "test-rule",
156            query,
157            template,
158            "generated/Test.java",
159            GenerationMode::Overwrite,
160        );
161
162        assert_eq!(rule.name(), "test-rule");
163        assert_eq!(rule.mode(), GenerationMode::Overwrite);
164    }
165
166    #[test]
167    fn test_query_execution_returns_bindings() {
168        // Chicago TDD: Verify real query execution produces correct bindings
169        let mut bindings = HashMap::new();
170        bindings.insert("className".to_string(), "TestClass".to_string());
171        bindings.insert("packageName".to_string(), "com.example".to_string());
172
173        let query = InlineQuery {
174            name: "test-query".to_string(),
175            bindings: vec![bindings],
176        };
177
178        let results = query.execute().expect("Query should execute");
179        assert_eq!(results.len(), 1, "Should return one binding set");
180        assert_eq!(
181            results[0].get("className").unwrap(),
182            "TestClass",
183            "Binding should contain className"
184        );
185        assert_eq!(
186            results[0].get("packageName").unwrap(),
187            "com.example",
188            "Binding should contain packageName"
189        );
190    }
191
192    #[test]
193    fn test_template_rendering_with_real_bindings() {
194        // Chicago TDD: Verify real template rendering produces correct output
195        let mut bindings = HashMap::new();
196        bindings.insert("className".to_string(), "TestClass".to_string());
197
198        let template = InlineTemplate {
199            name: "test-template".to_string(),
200            template_str: "public class {{className}} {\n}\n".to_string(),
201        };
202
203        let rendered = template.render(&bindings).expect("Template should render");
204        assert!(
205            rendered.contains("TestClass"),
206            "Rendered output should contain className"
207        );
208        assert!(
209            rendered.contains("public class"),
210            "Rendered output should contain template structure"
211        );
212    }
213
214    #[test]
215    fn test_generated_file_determinism() {
216        let content1 = "public class Test {}";
217        let file1 = GeneratedFile::new(
218            PathBuf::from("Test.java"),
219            content1.to_string(),
220            "rule1".to_string(),
221        );
222
223        let file2 = GeneratedFile::new(
224            PathBuf::from("Test.java"),
225            content1.to_string(),
226            "rule1".to_string(),
227        );
228
229        // Chicago TDD: Verify observable property - same content produces same hash
230        assert_eq!(
231            file1.content_hash, file2.content_hash,
232            "Same content must produce identical hash"
233        );
234    }
235}