Skip to main content

ggen_core/codegen_lib/
generated_file.rs

1//! Represents a generated file with content hash verification
2
3use std::collections::HashMap;
4use std::path::PathBuf;
5
6/// Represents a single generated file
7#[derive(Debug, Clone)]
8pub struct GeneratedFile {
9    /// Relative file path (may contain {{ }} for variable substitution)
10    pub path: PathBuf,
11    /// File content
12    pub content: String,
13    /// Source rule name
14    pub source_rule: String,
15    /// Content hash for determinism verification
16    pub content_hash: String,
17}
18
19impl GeneratedFile {
20    /// Create a new generated file with content hash
21    pub fn new(path: PathBuf, content: String, source_rule: String) -> Self {
22        use sha2::{Digest, Sha256};
23
24        let mut hasher = Sha256::new();
25        hasher.update(&content);
26        let content_hash = format!("{:x}", hasher.finalize());
27
28        Self {
29            path,
30            content,
31            source_rule,
32            content_hash,
33        }
34    }
35
36    /// Render the file path with bindings
37    pub fn render_path(
38        &self, bindings: &HashMap<String, String>,
39    ) -> crate::codegen_lib::Result<PathBuf> {
40        let path_str = self.path.to_string_lossy().to_string();
41
42        // Simple template variable substitution ({{ varName }} → value)
43        let rendered = bindings.iter().fold(path_str, |acc, (key, value)| {
44            acc.replace(&format!("{{{{{}}}}}", key), value)
45        });
46
47        Ok(PathBuf::from(rendered))
48    }
49}