weaver_lib/
partial.rs

1use std::path::PathBuf;
2
3use regex::RegexBuilder;
4use serde::{Deserialize, Serialize};
5
6use crate::normalize_line_endings;
7
8#[derive(Debug, Serialize, Deserialize, Default, Clone)]
9pub struct Partial {
10    pub name: String,
11    pub at_path: String,
12    pub contents: String,
13}
14
15impl Partial {
16    pub fn new_from_path(path: PathBuf) -> Self {
17        let contents_result = std::fs::read_to_string(&path);
18
19        if contents_result.is_err() {
20            dbg!("error reading file: {}", contents_result.err());
21            panic!("failed to read '{}'", path.display());
22        }
23
24        let re = RegexBuilder::new(r"<([a-zA-Z][a-zA-Z0-9]*)([^>]*)>")
25            .case_insensitive(true)
26            .build()
27            .expect("Failed to compile regex for HTML tags");
28
29        let original_content = normalize_line_endings(contents_result.as_ref().unwrap().as_bytes());
30        let contents = re.replace_all(&original_content, "$0\n").to_string();
31
32        Self {
33            at_path: path.display().to_string(),
34            name: path.file_name().unwrap().to_string_lossy().to_string(),
35            contents,
36        }
37    }
38}
39
40#[cfg(test)]
41mod test {
42    use super::*;
43    use pretty_assertions::assert_eq;
44
45    #[test]
46    fn test_partial_whitespace() {
47        let base_path_wd = std::env::current_dir().unwrap().display().to_string();
48        let base_path = format!("{}/test_fixtures/liquid/partials", base_path_wd);
49        let partial = Partial::new_from_path(format!("{}/test.liquid", base_path).into());
50
51        assert_eq!("<div>\n\n\ttest\n</div>\n", partial.contents,);
52    }
53}