Skip to main content

ggen_core/
preprocessor.rs

1//! Template preprocessor pipeline for deterministic text transformations
2//!
3//! This module provides a preprocessing pipeline that applies deterministic text
4//! transformations to templates before rendering. The preprocessor handles freeze
5//! blocks, includes, and macros in a controlled order to ensure reproducible output.
6//!
7//! ## Pipeline Order
8//!
9//! The preprocessing pipeline executes in the following order:
10//! 1. **Preprocessor**: Freeze, includes, macros
11//! 2. **Render Frontmatter**: Tera rendering on YAML frontmatter
12//! 3. **Graph Operations**: RDF loading and SPARQL query execution
13//! 4. **Body Render**: Final Tera rendering of template body
14//!
15//! ## Preprocessing Stages
16//!
17//! - **Freeze**: Replace `{% freeze %}` blocks with cached slot contents
18//!   - Preserves manual edits in generated files
19//!   - Supports checksum-based validation
20//! - **Includes**: Process `{% include %}` directives
21//!   - Resolve template includes recursively
22//!   - Support for relative and absolute paths
23//! - **Macros**: Expand template macros
24//!   - Macro definition and invocation
25//!   - Parameter passing and scoping
26//!
27//! ## Error Model
28//!
29//! - Each stage returns contextual errors with:
30//!   - Stage name for identification
31//!   - Byte span for error location
32//!   - Code snippet for context
33//! - No partial silent edits - all transformations are explicit
34//!
35//! ## Examples
36//!
37//! ### Using the Preprocessor
38//!
39//! ```rust,no_run
40//! use crate::preprocessor::{Preprocessor, PrepCtx};
41//! use std::path::Path;
42//!
43//! # fn main() -> crate::utils::error::Result<()> {
44//! let preprocessor = Preprocessor::with_default_stages();
45//! let ctx = PrepCtx {
46//!     template_path: Path::new("template.tmpl"),
47//!     out_dir: Path::new("output"),
48//!     vars_json: &serde_json::json!({}),
49//! };
50//!
51//! let input = r#"
52//! {% freeze slot="header" %}
53//! // Generated header
54//! {% endfreeze %}
55//! "#.to_string();
56//!
57//! let output = preprocessor.run(input, &ctx)?;
58//! # Ok(())
59//! # }
60//! ```
61
62use crate::utils::error::{Error, Result};
63use serde_json;
64use std::fs;
65use std::path::{Path, PathBuf};
66
67/// Preprocessor context for stage execution
68///
69/// Provides template path, output directory, and optional JSON variables
70/// to preprocessing stages during pipeline execution.
71pub struct PrepCtx<'a> {
72    /// Path to the template file being processed.
73    pub template_path: &'a Path,
74    /// Output directory for generated files.
75    pub out_dir: &'a Path,
76    /// Optional JSON variables for template rendering.
77    pub vars_json: &'a serde_json::Value, // optional, read-only
78}
79
80/// Trait for preprocessing stages
81///
82/// Defines the interface for pipeline stages that transform template content.
83pub trait Stage: Send + Sync {
84    /// Returns the name of this preprocessing stage.
85    fn name(&self) -> &'static str;
86    /// Runs the stage on the input string with the given context.
87    fn run(&self, input: &str, ctx: &PrepCtx) -> Result<String>;
88}
89
90/// Freeze policy for handling cached content
91///
92/// Determines when to use cached content vs regenerating from templates.
93///
94/// # Examples
95///
96/// ```rust
97/// use crate::preprocessor::FreezePolicy;
98///
99/// # fn main() {
100/// let policy = FreezePolicy::Always;
101/// match policy {
102///     FreezePolicy::Always => assert!(true),
103///     FreezePolicy::Checksum => assert!(true),
104///     FreezePolicy::Never => assert!(true),
105/// }
106/// # }
107/// ```
108#[derive(Debug, Clone)]
109pub enum FreezePolicy {
110    /// Always use cached content if available
111    Always,
112    /// Use cached content only if checksum matches
113    Checksum,
114    /// Never use cached content (always regenerate)
115    Never,
116}
117
118/// Freeze stage for processing {% freeze %} blocks
119///
120/// Processes `{% freeze %}` blocks in templates, managing cached content
121/// according to the specified freeze policy.
122pub struct FreezeStage {
123    /// Directory where cached slot content is stored.
124    pub slots_dir: PathBuf,
125    /// Policy determining when to use cached content.
126    pub policy: FreezePolicy,
127}
128
129impl Stage for FreezeStage {
130    fn name(&self) -> &'static str {
131        "freeze"
132    }
133
134    fn run(&self, input: &str, ctx: &PrepCtx) -> Result<String> {
135        process_freeze_blocks(input, ctx, self)
136    }
137}
138
139/// Include stage for processing {% include %} directives
140///
141/// Processes `{% include %}` directives in templates, resolving and inserting
142/// external template content.
143pub struct IncludeStage {
144    /// Directories to search for included template files.
145    pub template_dirs: Vec<PathBuf>,
146}
147
148impl Stage for IncludeStage {
149    fn name(&self) -> &'static str {
150        "include"
151    }
152
153    fn run(&self, input: &str, ctx: &PrepCtx) -> Result<String> {
154        process_includes(input, ctx, self)
155    }
156}
157
158/// Main preprocessor orchestrating multiple stages
159///
160/// Coordinates a pipeline of preprocessing stages that transform template
161/// content deterministically before rendering.
162pub struct Preprocessor {
163    /// Ordered list of preprocessing stages.
164    stages: Vec<Box<dyn Stage>>,
165}
166
167impl Default for Preprocessor {
168    fn default() -> Self {
169        Self::new()
170    }
171}
172
173impl Preprocessor {
174    /// Create a new preprocessor with no stages
175    pub fn new() -> Self {
176        Self { stages: Vec::new() }
177    }
178
179    /// Add a stage to the pipeline
180    pub fn with<S: Stage + 'static>(mut self, stage: S) -> Self {
181        self.stages.push(Box::new(stage));
182        self
183    }
184
185    /// Run all stages in order on the input
186    pub fn run(&self, mut input: String, ctx: &PrepCtx) -> Result<String> {
187        for stage in &self.stages {
188            input = stage.run(&input, ctx).map_err(|e| {
189                Error::with_source(&format!("Stage '{}' failed", stage.name()), Box::new(e))
190            })?;
191        }
192        Ok(input)
193    }
194
195    /// Create a preprocessor with common stages
196    pub fn with_default_stages() -> Self {
197        Self::new().with(IncludeStage {
198            template_dirs: vec![PathBuf::from("templates")],
199        })
200    }
201
202    /// Create a preprocessor with freeze support
203    pub fn with_freeze(slots_dir: PathBuf, policy: FreezePolicy) -> Self {
204        Self::new()
205            .with(IncludeStage {
206                template_dirs: vec![PathBuf::from("templates")],
207            })
208            .with(FreezeStage { slots_dir, policy })
209    }
210}
211
212/// Process {% freeze %} blocks in template content
213fn process_freeze_blocks(input: &str, ctx: &PrepCtx, stage: &FreezeStage) -> Result<String> {
214    let mut result = String::new();
215    let mut pos = 0;
216
217    // Find all freeze blocks
218    while let Some(start) = input[pos..].find("{% startfreeze") {
219        let absolute_start = pos + start;
220
221        // Find the end of the start tag
222        let end_start = if let Some(end) = input[absolute_start..].find("%}") {
223            absolute_start + end + 2
224        } else {
225            return Err(Error::new(&format!(
226                "Unclosed startfreeze tag at position {}",
227                absolute_start
228            )));
229        };
230
231        // Find the matching endfreeze tag
232        let endfreeze_start = if let Some(end) = input[end_start..].find("{% endfreeze %}") {
233            end_start + end
234        } else {
235            return Err(Error::new(&format!(
236                "Missing endfreeze tag for startfreeze at position {}",
237                absolute_start
238            )));
239        };
240
241        let endfreeze_end = endfreeze_start + "{% endfreeze %}".len();
242
243        // Extract block content and attributes
244        let block_content = &input[end_start..endfreeze_start];
245        let start_tag = &input[absolute_start..end_start];
246
247        // Parse attributes from start tag
248        let (id, checksum) = parse_freeze_attributes(start_tag)?;
249
250        // Generate default id/checksum if missing
251        let final_id = id.unwrap_or_else(|| generate_default_id(ctx.template_path, absolute_start));
252        let final_checksum = checksum.unwrap_or_else(|| generate_checksum(block_content));
253
254        // Process based on policy
255        let processed_content = match stage.policy {
256            FreezePolicy::Always => {
257                load_or_generate_slot(&stage.slots_dir, &final_id, &final_checksum, block_content)?
258            }
259            FreezePolicy::Checksum => {
260                load_or_generate_slot(&stage.slots_dir, &final_id, &final_checksum, block_content)?
261            }
262            FreezePolicy::Never => {
263                generate_and_save_slot(&stage.slots_dir, &final_id, &final_checksum, block_content)?
264            }
265        };
266
267        // Add content before this block
268        result.push_str(&input[pos..absolute_start]);
269        // Add processed content
270        result.push_str(&processed_content);
271
272        // Move position past this block
273        pos = endfreeze_end;
274    }
275
276    // Add remaining content
277    result.push_str(&input[pos..]);
278    Ok(result)
279}
280
281/// Process {% include %} directives in template content
282fn process_includes(input: &str, ctx: &PrepCtx, stage: &IncludeStage) -> Result<String> {
283    let mut result = String::new();
284    let mut pos = 0;
285
286    // Find all include directives
287    while let Some(start) = input[pos..].find("{% include") {
288        let absolute_start = pos + start;
289
290        // Find the end of the include tag
291        let end_start = if let Some(end) = input[absolute_start..].find("%}") {
292            absolute_start + end + 2
293        } else {
294            return Err(Error::new(&format!(
295                "Unclosed include tag at position {}",
296                absolute_start
297            )));
298        };
299
300        // Extract include path from tag
301        let include_tag = &input[absolute_start..end_start];
302        let include_path = parse_include_path(include_tag)?;
303
304        // Resolve include path
305        let resolved_path = resolve_include_path(&include_path, ctx, &stage.template_dirs)?;
306
307        // Read included content
308        let included_content = fs::read_to_string(&resolved_path).map_err(|e| {
309            Error::new(&format!(
310                "Failed to read include file '{}': {}",
311                resolved_path.display(),
312                e
313            ))
314        })?;
315
316        // Add content before this include
317        result.push_str(&input[pos..absolute_start]);
318        // Add included content
319        result.push_str(&included_content);
320
321        // Move position past this include
322        pos = end_start;
323    }
324
325    // Add remaining content
326    result.push_str(&input[pos..]);
327    Ok(result)
328}
329
330/// Parse attributes from {% startfreeze %} tag
331fn parse_freeze_attributes(tag: &str) -> Result<(Option<String>, Option<String>)> {
332    let mut id = None;
333    let mut checksum = None;
334
335    // Simple attribute parsing - look for id="..." and checksum="..."
336    if let Some(id_start) = tag.find("id=\"") {
337        let id_start = id_start + 4;
338        if let Some(id_end) = tag[id_start..].find('"') {
339            id = Some(tag[id_start..id_start + id_end].to_string());
340        }
341    }
342
343    if let Some(cs_start) = tag.find("checksum=\"") {
344        let cs_start = cs_start + 10;
345        if let Some(cs_end) = tag[cs_start..].find('"') {
346            checksum = Some(tag[cs_start..cs_start + cs_end].to_string());
347        }
348    }
349
350    Ok((id, checksum))
351}
352
353/// Parse include path from {% include %} tag
354fn parse_include_path(tag: &str) -> Result<String> {
355    // Extract path from {% include "path" %} or {% include 'path' %}
356    let path_start = if let Some(start) = tag.find('"') {
357        start + 1
358    } else if let Some(start) = tag.find('\'') {
359        start + 1
360    } else {
361        return Err(Error::new(&format!("Invalid include tag format: {}", tag)));
362    };
363
364    let path_end = if let Some(end) = tag[path_start..].find('"') {
365        path_start + end
366    } else if let Some(end) = tag[path_start..].find('\'') {
367        path_start + end
368    } else {
369        return Err(Error::new(&format!(
370            "Unclosed include path in tag: {}",
371            tag
372        )));
373    };
374
375    Ok(tag[path_start..path_end].to_string())
376}
377
378/// Resolve include path relative to template directories
379fn resolve_include_path(
380    include_path: &str, ctx: &PrepCtx, template_dirs: &[PathBuf],
381) -> Result<PathBuf> {
382    // Try relative to template file first
383    if let Some(template_dir) = ctx.template_path.parent() {
384        let relative_path = template_dir.join(include_path);
385        if relative_path.exists() {
386            return Ok(relative_path);
387        }
388    }
389
390    // Try template directories
391    for template_dir in template_dirs {
392        let full_path = template_dir.join(include_path);
393        if full_path.exists() {
394            return Ok(full_path);
395        }
396    }
397
398    Err(Error::new(&format!(
399        "Include file not found: {}",
400        include_path
401    )))
402}
403
404/// Generate default ID for freeze block
405fn generate_default_id(template_path: &Path, position: usize) -> String {
406    use std::collections::hash_map::DefaultHasher;
407    use std::hash::{Hash, Hasher};
408
409    let mut hasher = DefaultHasher::new();
410    template_path.hash(&mut hasher);
411    position.hash(&mut hasher);
412    format!("slot_{:x}", hasher.finish())
413}
414
415/// Generate checksum for content
416fn generate_checksum(content: &str) -> String {
417    use std::collections::hash_map::DefaultHasher;
418    use std::hash::{Hash, Hasher};
419
420    let mut hasher = DefaultHasher::new();
421    content.hash(&mut hasher);
422    format!("{:x}", hasher.finish())
423}
424
425/// Load cached slot or generate new content
426fn load_or_generate_slot(
427    slots_dir: &Path, id: &str, checksum: &str, content: &str,
428) -> Result<String> {
429    let slot_path = slots_dir.join(format!("{}.slot", id));
430    let checksum_path = slots_dir.join(format!("{}.checksum", id));
431
432    // Check if cached slot exists and checksum matches
433    if slot_path.exists() && checksum_path.exists() {
434        if let Ok(cached_checksum) = fs::read_to_string(&checksum_path) {
435            if cached_checksum.trim() == checksum {
436                return fs::read_to_string(&slot_path)
437                    .map_err(|e| Error::with_source("Failed to read cached slot", Box::new(e)));
438            }
439        }
440    }
441
442    // Generate and save new slot
443    generate_and_save_slot(slots_dir, id, checksum, content)
444}
445
446/// Generate and save slot content
447fn generate_and_save_slot(
448    slots_dir: &Path, id: &str, checksum: &str, content: &str,
449) -> Result<String> {
450    // Ensure slots directory exists
451    fs::create_dir_all(slots_dir)
452        .map_err(|e| Error::with_source("Failed to create slots directory", Box::new(e)))?;
453
454    let slot_path = slots_dir.join(format!("{}.slot", id));
455    let checksum_path = slots_dir.join(format!("{}.checksum", id));
456
457    // Save content and checksum
458    fs::write(&slot_path, content)
459        .map_err(|e| Error::with_source("Failed to write slot file", Box::new(e)))?;
460    fs::write(&checksum_path, checksum)
461        .map_err(|e| Error::with_source("Failed to write checksum file", Box::new(e)))?;
462
463    Ok(content.to_string())
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469    use tempfile::TempDir;
470
471    fn create_test_ctx() -> PrepCtx<'static> {
472        PrepCtx {
473            template_path: Path::new("test.tmpl"),
474            out_dir: Path::new("output"),
475            vars_json: &serde_json::Value::Null,
476        }
477    }
478
479    #[test]
480    fn test_freeze_stage_basic() -> Result<()> {
481        let temp_dir = TempDir::new()?;
482        let stage = FreezeStage {
483            slots_dir: temp_dir.path().to_path_buf(),
484            policy: FreezePolicy::Always,
485        };
486
487        let input = r#"Hello
488{% startfreeze id="test" %}
489World
490{% endfreeze %}
491!"#;
492
493        let ctx = create_test_ctx();
494        let result = stage.run(input, &ctx)?;
495
496        assert!(result.contains("World"));
497        assert!(!result.contains("startfreeze"));
498        assert!(!result.contains("endfreeze"));
499
500        Ok(())
501    }
502
503    #[test]
504    fn test_include_stage_basic() -> Result<()> {
505        let temp_dir = TempDir::new()?;
506        let include_file = temp_dir.path().join("included.tmpl");
507        fs::write(&include_file, "Included content")?;
508
509        let stage = IncludeStage {
510            template_dirs: vec![temp_dir.path().to_path_buf()],
511        };
512
513        let input = r#"Hello
514{% include "included.tmpl" %}
515!"#;
516
517        let ctx = create_test_ctx();
518        let result = stage.run(input, &ctx)?;
519
520        assert!(result.contains("Included content"));
521        assert!(!result.contains("include"));
522
523        Ok(())
524    }
525
526    #[test]
527    fn test_preprocessor_pipeline() -> Result<()> {
528        let temp_dir = TempDir::new()?;
529        let include_file = temp_dir.path().join("included.tmpl");
530        fs::write(&include_file, "Included")?;
531
532        let preprocessor = Preprocessor::new()
533            .with(IncludeStage {
534                template_dirs: vec![temp_dir.path().to_path_buf()],
535            })
536            .with(FreezeStage {
537                slots_dir: temp_dir.path().join("slots"),
538                policy: FreezePolicy::Always,
539            });
540
541        let input = r#"Hello
542{% include "included.tmpl" %}
543{% startfreeze id="test" %}
544Frozen
545{% endfreeze %}
546!"#;
547
548        let ctx = create_test_ctx();
549        let result = preprocessor.run(input.to_string(), &ctx)?;
550
551        assert!(result.contains("Included"));
552        assert!(result.contains("Frozen"));
553        assert!(!result.contains("include"));
554        assert!(!result.contains("startfreeze"));
555
556        Ok(())
557    }
558}