From 06c9e87041fe2916b65b6cc0078ab57cb061bf32 Mon Sep 17 00:00:00 2001 From: KitsuneCafe <10284516+kitsunecafe@users.noreply.github.com> Date: Mon, 5 Feb 2024 15:37:56 -0500 Subject: [PATCH] iterate captures --- src/lib.rs | 42 +++++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index f5c2931..a5f1b60 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,8 +5,9 @@ use regex::Regex; use roxy_core::roxy::Parse; const DEFAULT_CONTEXT: Lazy = Lazy::new(|| tera::Context::default()); -const EXPANSION_RE: Lazy = - Lazy::new(|| Regex::new("\\{% (extends|include) \"?(.+?)\"? %\\}").expect("couldn't load regex")); +const EXPANSION_RE: Lazy = Lazy::new(|| { + Regex::new("\\{% (extends|include) \"?(.+?)\"? %\\}").expect("couldn't load regex") +}); #[derive(Debug)] pub struct TeraParserOptions { @@ -43,16 +44,17 @@ impl<'a> TeraParser<'a> { fn load_template(&mut self, path: &str, src: &[u8]) -> Result<(), tera::Error> { let str = String::from_utf8_lossy(src).to_string(); - while let Some(captures) = EXPANSION_RE.captures(&str.as_str()) { - if let Some(layout_path) = captures.get(2) { - let layout_path = layout_path.as_str(); - let path = PathBuf::from(path).parent().map(|p| p.join(layout_path)).unwrap(); + for (_, [_, layout_path]) in EXPANSION_RE + .captures_iter(&str.as_str()) + .map(|c| c.extract()) + { + let path = PathBuf::from(path) + .parent() + .map(|p| p.join(layout_path)) + .unwrap(); - self.tera.add_template_file( - &path.canonicalize().unwrap(), - Some(layout_path) - )?; - } + self.tera + .add_template_file(&path.canonicalize().unwrap(), Some(layout_path))?; } Ok(()) @@ -60,7 +62,12 @@ impl<'a> TeraParser<'a> { } impl<'a> Parse for TeraParser<'a> { - fn parse(&mut self, path: &str, src: &[u8], dst: &mut Vec) -> Result<(), roxy_core::error::Error> { + fn parse( + &mut self, + path: &str, + src: &[u8], + dst: &mut Vec, + ) -> Result<(), roxy_core::error::Error> { // TODO: This error is a hack let err = |e: tera::Error| { println!("{e:?}"); @@ -90,5 +97,14 @@ mod tests { use roxy_core::roxy::Parse; use crate::{TeraParser, TeraParserOptions}; -} + #[test] + fn capture_test() { + let mut tera = tera::Tera::default(); + let mut parser = TeraParser::new(&mut tera, TeraParserOptions::default()); + let data = b"

{% include \"test.html\" %}

"; + let mut dst = Vec::new(); + parser.parse("test.html", data, &mut dst); + println!("{dst:?}"); + } +}