1use crate::utils::error::{Error, Result};
63use serde_json;
64use std::fs;
65use std::path::{Path, PathBuf};
66
67pub struct PrepCtx<'a> {
72 pub template_path: &'a Path,
74 pub out_dir: &'a Path,
76 pub vars_json: &'a serde_json::Value, }
79
80pub trait Stage: Send + Sync {
84 fn name(&self) -> &'static str;
86 fn run(&self, input: &str, ctx: &PrepCtx) -> Result<String>;
88}
89
90#[derive(Debug, Clone)]
109pub enum FreezePolicy {
110 Always,
112 Checksum,
114 Never,
116}
117
118pub struct FreezeStage {
123 pub slots_dir: PathBuf,
125 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
139pub struct IncludeStage {
144 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
158pub struct Preprocessor {
163 stages: Vec<Box<dyn Stage>>,
165}
166
167impl Default for Preprocessor {
168 fn default() -> Self {
169 Self::new()
170 }
171}
172
173impl Preprocessor {
174 pub fn new() -> Self {
176 Self { stages: Vec::new() }
177 }
178
179 pub fn with<S: Stage + 'static>(mut self, stage: S) -> Self {
181 self.stages.push(Box::new(stage));
182 self
183 }
184
185 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 pub fn with_default_stages() -> Self {
197 Self::new().with(IncludeStage {
198 template_dirs: vec![PathBuf::from("templates")],
199 })
200 }
201
202 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
212fn process_freeze_blocks(input: &str, ctx: &PrepCtx, stage: &FreezeStage) -> Result<String> {
214 let mut result = String::new();
215 let mut pos = 0;
216
217 while let Some(start) = input[pos..].find("{% startfreeze") {
219 let absolute_start = pos + start;
220
221 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 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 let block_content = &input[end_start..endfreeze_start];
245 let start_tag = &input[absolute_start..end_start];
246
247 let (id, checksum) = parse_freeze_attributes(start_tag)?;
249
250 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 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 result.push_str(&input[pos..absolute_start]);
269 result.push_str(&processed_content);
271
272 pos = endfreeze_end;
274 }
275
276 result.push_str(&input[pos..]);
278 Ok(result)
279}
280
281fn process_includes(input: &str, ctx: &PrepCtx, stage: &IncludeStage) -> Result<String> {
283 let mut result = String::new();
284 let mut pos = 0;
285
286 while let Some(start) = input[pos..].find("{% include") {
288 let absolute_start = pos + start;
289
290 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 let include_tag = &input[absolute_start..end_start];
302 let include_path = parse_include_path(include_tag)?;
303
304 let resolved_path = resolve_include_path(&include_path, ctx, &stage.template_dirs)?;
306
307 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 result.push_str(&input[pos..absolute_start]);
318 result.push_str(&included_content);
320
321 pos = end_start;
323 }
324
325 result.push_str(&input[pos..]);
327 Ok(result)
328}
329
330fn parse_freeze_attributes(tag: &str) -> Result<(Option<String>, Option<String>)> {
332 let mut id = None;
333 let mut checksum = None;
334
335 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
353fn parse_include_path(tag: &str) -> Result<String> {
355 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
378fn resolve_include_path(
380 include_path: &str, ctx: &PrepCtx, template_dirs: &[PathBuf],
381) -> Result<PathBuf> {
382 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 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
404fn 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
415fn 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
425fn 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 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_slot(slots_dir, id, checksum, content)
444}
445
446fn generate_and_save_slot(
448 slots_dir: &Path, id: &str, checksum: &str, content: &str,
449) -> Result<String> {
450 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 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}