Skip to main content

yui/
render.rs

1//! Tera template rendering for `*.tera` files.
2//!
3//! Output goes to the **same directory** as the source `.tera` file (e.g.
4//! `home/.gitconfig.tera` → `home/.gitconfig`). When `manage_gitignore` is
5//! true, the rendered files are listed in a `# >>> yui rendered ... <<<`
6//! managed section of `.gitignore` so they aren't committed.
7//!
8//! Conditional render (both honored, AND'd together when both present):
9//!   - file-header: `{# yui:when EXPR #}` as the first Tera comment in the
10//!     `.tera` file. Tera comments are stripped from output, so the header
11//!     never bleeds into the rendered file.
12//!   - config rule: `[[render.rule]] match = "<glob>", when = "<expr>"` —
13//!     the glob is matched against the path relative to the source root.
14//!
15//! Drift policy: if the rendered file already exists with content that
16//! diverges from what the template would produce now, we DO NOT overwrite
17//! it. The user has likely edited the rendered file in place and needs to
18//! reflect that change back into the `.tera` first. The divergence is
19//! reported in `RenderReport::diverged`; `--check` treats it as fatal.
20
21use camino::{Utf8Path, Utf8PathBuf};
22use globset::{Glob, GlobSet, GlobSetBuilder};
23use ignore::WalkBuilder;
24use tera::Context as TeraContext;
25
26use crate::config::{Config, RenderRule};
27use crate::template::{self, Engine};
28use crate::vars::YuiVars;
29use crate::{Error, Result};
30
31const GITIGNORE_BEGIN: &str = "# >>> yui rendered (auto-managed, do not edit) >>>";
32const GITIGNORE_END: &str = "# <<< yui rendered (auto-managed) <<<";
33
34#[derive(Debug, Default)]
35pub struct RenderReport {
36    /// Templates rendered for the first time (or after deletion).
37    pub written: Vec<Utf8PathBuf>,
38    /// Rendered output identical to existing file — no write needed.
39    pub unchanged: Vec<Utf8PathBuf>,
40    /// Skipped because file-header or config rule `when` evaluated to false.
41    pub skipped_when_false: Vec<Utf8PathBuf>,
42    /// Existing rendered file diverges from current template output.
43    /// User must reflect the manual edit back into `.tera` before re-rendering.
44    pub diverged: Vec<Utf8PathBuf>,
45}
46
47impl RenderReport {
48    pub fn has_drift(&self) -> bool {
49        !self.diverged.is_empty()
50    }
51}
52
53pub fn render_all(
54    source: &Utf8Path,
55    config: &Config,
56    yui: &YuiVars,
57    dry_run: bool,
58) -> Result<RenderReport> {
59    let mut engine = Engine::new();
60    let ctx = template::template_context(yui, &config.vars);
61    let rules = compile_rules(&config.render.rule)?;
62    let mut report = RenderReport::default();
63
64    // Disable .gitignore / .ignore filtering: the rendered counterparts
65    // we manage are themselves gitignored, and we don't want a user's
66    // unrelated ignore rules (e.g. `node_modules/`) to swallow templates
67    // that live deeper. `.yuiignore` will eventually do its own filtering.
68    let walker = WalkBuilder::new(source)
69        .hidden(false)
70        .git_ignore(false)
71        .ignore(false)
72        .build();
73    for entry in walker {
74        let entry = match entry {
75            Ok(e) => e,
76            Err(_) => continue,
77        };
78        if !entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
79            continue;
80        }
81        let std_path = entry.path();
82        let Some(name) = std_path.file_name().and_then(|n| n.to_str()) else {
83            continue;
84        };
85        if !name.ends_with(".tera") {
86            continue;
87        }
88        let template_path = match Utf8PathBuf::from_path_buf(std_path.to_path_buf()) {
89            Ok(p) => p,
90            Err(_) => continue,
91        };
92        process_template(
93            &template_path,
94            source,
95            &rules,
96            &mut engine,
97            &ctx,
98            dry_run,
99            &mut report,
100        )?;
101    }
102
103    if !dry_run && config.render.manage_gitignore {
104        update_gitignore(source, &collect_managed_paths(&report))?;
105    }
106    Ok(report)
107}
108
109struct CompiledRule {
110    matcher: GlobSet,
111    when: Option<String>,
112}
113
114fn compile_rules(rules: &[RenderRule]) -> Result<Vec<CompiledRule>> {
115    let mut out = Vec::with_capacity(rules.len());
116    for r in rules {
117        let glob = Glob::new(&r.r#match)
118            .map_err(|e| Error::Config(format!("render.rule.match {:?}: {e}", r.r#match)))?;
119        let mut b = GlobSetBuilder::new();
120        b.add(glob);
121        let matcher = b
122            .build()
123            .map_err(|e| Error::Config(format!("globset build: {e}")))?;
124        out.push(CompiledRule {
125            matcher,
126            when: r.when.clone(),
127        });
128    }
129    Ok(out)
130}
131
132fn process_template(
133    template_path: &Utf8Path,
134    source: &Utf8Path,
135    rules: &[CompiledRule],
136    engine: &mut Engine,
137    ctx: &TeraContext,
138    dry_run: bool,
139    report: &mut RenderReport,
140) -> Result<()> {
141    let raw = std::fs::read_to_string(template_path)
142        .map_err(|e| Error::Template(format!("read {template_path}: {e}")))?;
143    let target = template_target(template_path);
144
145    // Strip any `{# yui:when EXPR #}\n` header before handing the body to
146    // Tera, so a falsy header doesn't leave a stray newline at the top of
147    // a successful render.
148    let body_input = if let Some((expr, body)) = split_yui_when(&raw) {
149        if !eval_when(expr, engine, ctx)? {
150            return skip_when_false(template_path, &target, dry_run, report);
151        }
152        body.to_string()
153    } else {
154        raw
155    };
156
157    let rel = relative_to(source, template_path);
158    let rel_for_match = rel.as_str().replace('\\', "/");
159    for rule in rules {
160        if rule.matcher.is_match(&rel_for_match) {
161            if let Some(w) = &rule.when {
162                if !eval_when(w, engine, ctx)? {
163                    return skip_when_false(template_path, &target, dry_run, report);
164                }
165            }
166        }
167    }
168
169    let body = engine.render(&body_input, ctx)?;
170
171    match std::fs::read_to_string(&target) {
172        Ok(existing) if existing == body => {
173            report.unchanged.push(target);
174            return Ok(());
175        }
176        Ok(_) => {
177            report.diverged.push(target);
178            return Ok(());
179        }
180        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
181        Err(e) => return Err(Error::Template(format!("read {target}: {e}"))),
182    }
183
184    if !dry_run {
185        if let Some(parent) = target.parent() {
186            std::fs::create_dir_all(parent)?;
187        }
188        std::fs::write(&target, &body)?;
189    }
190    report.written.push(target);
191    Ok(())
192}
193
194/// Common path for `when=false` skips: drops any stale rendered output so
195/// the link walk doesn't end up linking yesterday's render of a now-disabled
196/// template. Records the skip on the report.
197fn skip_when_false(
198    template_path: &Utf8Path,
199    target: &Utf8Path,
200    dry_run: bool,
201    report: &mut RenderReport,
202) -> Result<()> {
203    if !dry_run && target.exists() {
204        std::fs::remove_file(target)
205            .map_err(|e| Error::Template(format!("removing stale rendered {target}: {e}")))?;
206    }
207    report.skipped_when_false.push(template_path.to_path_buf());
208    Ok(())
209}
210
211/// If the file begins with a `{# yui:when EXPR #}` header (after optional
212/// leading whitespace) followed by an immediate newline, returns
213/// `(expr, body)` where `body` is the file content with that header line
214/// stripped. Otherwise None.
215fn split_yui_when(raw: &str) -> Option<(&str, &str)> {
216    let leading_ws = raw.len() - raw.trim_start().len();
217    let after_ws = &raw[leading_ws..];
218    let after_open = after_ws.strip_prefix("{#")?;
219    let close = after_open.find("#}")?;
220    let inside = &after_open[..close];
221    let expr = inside.trim().strip_prefix("yui:when")?.trim();
222
223    let mut body_start = leading_ws + 2 + close + 2;
224    if raw[body_start..].starts_with("\r\n") {
225        body_start += 2;
226    } else if raw[body_start..].starts_with('\n') {
227        body_start += 1;
228    }
229    Some((expr, &raw[body_start..]))
230}
231
232/// Local alias for [`template::eval_truthy`] to keep call sites short.
233fn eval_when(expr: &str, engine: &mut Engine, ctx: &TeraContext) -> Result<bool> {
234    template::eval_truthy(expr, engine, ctx)
235}
236
237fn template_target(template_path: &Utf8Path) -> Utf8PathBuf {
238    let s = template_path.as_str();
239    debug_assert!(s.ends_with(".tera"));
240    Utf8PathBuf::from(&s[..s.len() - ".tera".len()])
241}
242
243fn relative_to(base: &Utf8Path, p: &Utf8Path) -> Utf8PathBuf {
244    p.strip_prefix(base)
245        .map(Utf8PathBuf::from)
246        .unwrap_or_else(|_| p.to_path_buf())
247}
248
249fn collect_managed_paths(report: &RenderReport) -> Vec<Utf8PathBuf> {
250    let mut all: Vec<_> = report
251        .written
252        .iter()
253        .chain(report.unchanged.iter())
254        .chain(report.diverged.iter())
255        .cloned()
256        .collect();
257    all.sort();
258    all.dedup();
259    all
260}
261
262fn update_gitignore(source: &Utf8Path, rendered_abs_paths: &[Utf8PathBuf]) -> Result<()> {
263    let gi_path = source.join(".gitignore");
264    let existing = match std::fs::read_to_string(&gi_path) {
265        Ok(s) => s,
266        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
267        Err(e) => return Err(Error::Template(format!("read {gi_path}: {e}"))),
268    };
269
270    let mut managed: Vec<String> = rendered_abs_paths
271        .iter()
272        .filter_map(|p| p.strip_prefix(source).ok())
273        .map(|p| p.as_str().replace('\\', "/"))
274        .collect();
275    managed.sort();
276    managed.dedup();
277
278    let new_section = build_managed_section(&managed);
279    let updated = replace_or_append_section(&existing, &new_section);
280
281    if updated != existing {
282        std::fs::write(&gi_path, updated)?;
283    }
284    Ok(())
285}
286
287fn build_managed_section(lines: &[String]) -> String {
288    let mut s = String::new();
289    s.push_str(GITIGNORE_BEGIN);
290    s.push('\n');
291    for l in lines {
292        s.push_str(l);
293        s.push('\n');
294    }
295    s.push_str(GITIGNORE_END);
296    s.push('\n');
297    s
298}
299
300fn replace_or_append_section(existing: &str, new_section: &str) -> String {
301    // Refactored from `if let ... && cond` (let-chains) to nested if so the
302    // crate's MSRV (rust-version = "1.85") stays buildable; let-chains were
303    // stabilized in 1.88.
304    if let (Some(start), Some(end)) = (existing.find(GITIGNORE_BEGIN), existing.find(GITIGNORE_END))
305    {
306        if start < end {
307            let end_line_end = match existing[end..].find('\n') {
308                Some(idx) => end + idx + 1,
309                None => existing.len(),
310            };
311            let mut out = String::with_capacity(existing.len() + new_section.len());
312            out.push_str(&existing[..start]);
313            out.push_str(new_section);
314            out.push_str(&existing[end_line_end..]);
315            return out;
316        }
317    }
318
319    let mut out = String::from(existing);
320    if !out.is_empty() && !out.ends_with('\n') {
321        out.push('\n');
322    }
323    if !out.is_empty() {
324        out.push('\n');
325    }
326    out.push_str(new_section);
327    out
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333    use tempfile::TempDir;
334
335    fn yui_vars(source: &Utf8Path) -> YuiVars {
336        YuiVars {
337            os: "linux".into(),
338            arch: "x86_64".into(),
339            host: "test".into(),
340            user: "u".into(),
341            source: source.to_string(),
342        }
343    }
344
345    fn root(tmp: &TempDir) -> Utf8PathBuf {
346        Utf8PathBuf::from_path_buf(tmp.path().to_path_buf()).unwrap()
347    }
348
349    fn empty_config() -> Config {
350        Config::default()
351    }
352
353    fn write(p: &Utf8Path, body: &str) {
354        if let Some(parent) = p.parent() {
355            std::fs::create_dir_all(parent).unwrap();
356        }
357        std::fs::write(p, body).unwrap();
358    }
359
360    #[test]
361    fn split_yui_when_basic() {
362        assert_eq!(
363            split_yui_when("{# yui:when yui.os == 'linux' #}\nbody"),
364            Some(("yui.os == 'linux'", "body"))
365        );
366        assert_eq!(
367            split_yui_when("\n  {#yui:when 1 == 1#}\nbody"),
368            Some(("1 == 1", "body"))
369        );
370        // CRLF line endings
371        assert_eq!(
372            split_yui_when("{# yui:when true #}\r\nbody"),
373            Some(("true", "body"))
374        );
375        // No newline after header — header still parsed, body is the rest
376        assert_eq!(
377            split_yui_when("{# yui:when true #}body"),
378            Some(("true", "body"))
379        );
380        assert_eq!(split_yui_when("body without header"), None);
381        assert_eq!(split_yui_when("{# regular comment #}body"), None);
382    }
383
384    #[test]
385    fn template_target_strips_tera_extension() {
386        assert_eq!(
387            template_target(Utf8Path::new("/a/b/foo.tera")),
388            Utf8PathBuf::from("/a/b/foo")
389        );
390        assert_eq!(
391            template_target(Utf8Path::new("home/.gitconfig.tera")),
392            Utf8PathBuf::from("home/.gitconfig")
393        );
394    }
395
396    #[test]
397    fn renders_simple_template_to_sibling() {
398        let tmp = TempDir::new().unwrap();
399        let r = root(&tmp);
400        write(
401            &r.join("home/.gitconfig.tera"),
402            "[user]\n  os = {{ yui.os }}\n",
403        );
404        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
405        assert_eq!(report.written.len(), 1);
406        assert_eq!(
407            std::fs::read_to_string(r.join("home/.gitconfig")).unwrap(),
408            "[user]\n  os = linux\n"
409        );
410    }
411
412    #[test]
413    fn renders_user_vars() {
414        let tmp = TempDir::new().unwrap();
415        let r = root(&tmp);
416        write(&r.join("home/foo.tera"), "{{ vars.greet }}");
417        let mut cfg = empty_config();
418        cfg.vars
419            .insert("greet".into(), toml::Value::String("hello".into()));
420        let _ = render_all(&r, &cfg, &yui_vars(&r), false).unwrap();
421        assert_eq!(
422            std::fs::read_to_string(r.join("home/foo")).unwrap(),
423            "hello"
424        );
425    }
426
427    #[test]
428    fn skips_when_file_header_false() {
429        let tmp = TempDir::new().unwrap();
430        let r = root(&tmp);
431        write(
432            &r.join("home/foo.tera"),
433            "{# yui:when yui.os == 'windows' #}\nbody",
434        );
435        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
436        assert!(report.written.is_empty());
437        assert_eq!(report.skipped_when_false.len(), 1);
438        assert!(!r.join("home/foo").exists());
439    }
440
441    #[test]
442    fn includes_when_file_header_true() {
443        let tmp = TempDir::new().unwrap();
444        let r = root(&tmp);
445        write(
446            &r.join("home/foo.tera"),
447            "{# yui:when yui.os == 'linux' #}\nbody",
448        );
449        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
450        assert_eq!(report.written.len(), 1);
451        assert_eq!(std::fs::read_to_string(r.join("home/foo")).unwrap(), "body");
452    }
453
454    #[test]
455    fn config_rule_when_false_skips_matching_template() {
456        let tmp = TempDir::new().unwrap();
457        let r = root(&tmp);
458        write(&r.join("home/win/settings.tera"), "body");
459        let mut cfg = empty_config();
460        cfg.render.rule.push(RenderRule {
461            r#match: "home/win/**".into(),
462            when: Some("{{ yui.os == 'windows' }}".into()),
463        });
464        let report = render_all(&r, &cfg, &yui_vars(&r), false).unwrap();
465        assert_eq!(report.skipped_when_false.len(), 1);
466        assert!(report.written.is_empty());
467    }
468
469    #[test]
470    fn config_rule_no_match_does_not_filter() {
471        let tmp = TempDir::new().unwrap();
472        let r = root(&tmp);
473        write(&r.join("home/foo.tera"), "body");
474        let mut cfg = empty_config();
475        // glob doesn't match foo.tera
476        cfg.render.rule.push(RenderRule {
477            r#match: "home/win/**".into(),
478            when: Some("{{ yui.os == 'windows' }}".into()),
479        });
480        let report = render_all(&r, &cfg, &yui_vars(&r), false).unwrap();
481        assert_eq!(report.written.len(), 1);
482    }
483
484    #[test]
485    fn unchanged_when_existing_matches() {
486        let tmp = TempDir::new().unwrap();
487        let r = root(&tmp);
488        write(&r.join("home/foo.tera"), "body");
489        write(&r.join("home/foo"), "body"); // already in sync
490        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
491        assert!(report.written.is_empty());
492        assert_eq!(report.unchanged.len(), 1);
493    }
494
495    #[test]
496    fn detects_drift_when_existing_diverges() {
497        let tmp = TempDir::new().unwrap();
498        let r = root(&tmp);
499        write(&r.join("home/foo.tera"), "fresh body");
500        write(&r.join("home/foo"), "manually edited");
501        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
502        assert!(report.has_drift());
503        assert_eq!(report.diverged.len(), 1);
504        // existing content NOT overwritten
505        assert_eq!(
506            std::fs::read_to_string(r.join("home/foo")).unwrap(),
507            "manually edited"
508        );
509    }
510
511    #[test]
512    fn dry_run_does_not_write_or_touch_gitignore() {
513        let tmp = TempDir::new().unwrap();
514        let r = root(&tmp);
515        write(&r.join("home/foo.tera"), "body");
516        let _ = render_all(&r, &empty_config(), &yui_vars(&r), true).unwrap();
517        assert!(!r.join("home/foo").exists());
518        assert!(!r.join(".gitignore").exists());
519    }
520
521    #[test]
522    fn updates_gitignore_managed_section() {
523        let tmp = TempDir::new().unwrap();
524        let r = root(&tmp);
525        write(&r.join("home/foo.tera"), "body");
526        write(&r.join("home/bar.tera"), "body2");
527        let _ = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
528        let gi = std::fs::read_to_string(r.join(".gitignore")).unwrap();
529        assert!(gi.contains(GITIGNORE_BEGIN));
530        assert!(gi.contains(GITIGNORE_END));
531        assert!(gi.contains("home/bar"));
532        assert!(gi.contains("home/foo"));
533        // sorted: bar before foo
534        let bar_pos = gi.find("home/bar").unwrap();
535        let foo_pos = gi.find("home/foo").unwrap();
536        assert!(bar_pos < foo_pos);
537    }
538
539    #[test]
540    fn preserves_existing_gitignore_content() {
541        let tmp = TempDir::new().unwrap();
542        let r = root(&tmp);
543        write(&r.join(".gitignore"), "node_modules/\ntarget/\n");
544        write(&r.join("home/foo.tera"), "body");
545        let _ = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
546        let gi = std::fs::read_to_string(r.join(".gitignore")).unwrap();
547        assert!(gi.contains("node_modules/"));
548        assert!(gi.contains("target/"));
549        assert!(gi.contains("home/foo"));
550    }
551
552    #[test]
553    fn replaces_existing_managed_section() {
554        let tmp = TempDir::new().unwrap();
555        let r = root(&tmp);
556        // Pre-existing managed section with stale content
557        write(
558            &r.join(".gitignore"),
559            &format!("node_modules/\n\n{GITIGNORE_BEGIN}\nstale/path\n{GITIGNORE_END}\n\nfoo\n"),
560        );
561        write(&r.join("home/foo.tera"), "body");
562        let _ = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
563        let gi = std::fs::read_to_string(r.join(".gitignore")).unwrap();
564        assert!(gi.contains("node_modules/"));
565        assert!(gi.contains("home/foo"));
566        assert!(!gi.contains("stale/path"));
567        // post-section content preserved
568        assert!(gi.contains("\nfoo\n"));
569    }
570
571    #[test]
572    fn walks_into_gitignored_directories() {
573        let tmp = TempDir::new().unwrap();
574        let r = root(&tmp);
575        // Pre-existing .gitignore that would normally hide `node_modules/`.
576        write(&r.join(".gitignore"), "node_modules/\n");
577        write(&r.join("node_modules/foo.tera"), "body");
578        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
579        // Template under a gitignored dir is still discovered + rendered.
580        assert_eq!(report.written.len(), 1);
581        assert!(r.join("node_modules/foo").exists());
582    }
583
584    #[test]
585    fn removes_stale_rendered_when_file_header_becomes_false() {
586        let tmp = TempDir::new().unwrap();
587        let r = root(&tmp);
588        // Previously rendered output sitting on disk
589        write(
590            &r.join("home/foo.tera"),
591            "{# yui:when yui.os == 'windows' #}\nbody",
592        );
593        write(&r.join("home/foo"), "old rendered output");
594        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
595        assert_eq!(report.skipped_when_false.len(), 1);
596        // Stale sibling was cleaned up so apply won't link it.
597        assert!(!r.join("home/foo").exists());
598    }
599
600    #[test]
601    fn removes_stale_rendered_when_rule_when_becomes_false() {
602        let tmp = TempDir::new().unwrap();
603        let r = root(&tmp);
604        write(&r.join("home/win/settings.tera"), "body");
605        write(&r.join("home/win/settings"), "old rendered output");
606        let mut cfg = empty_config();
607        cfg.render.rule.push(RenderRule {
608            r#match: "home/win/**".into(),
609            when: Some("{{ yui.os == 'windows' }}".into()),
610        });
611        let report = render_all(&r, &cfg, &yui_vars(&r), false).unwrap();
612        assert_eq!(report.skipped_when_false.len(), 1);
613        assert!(!r.join("home/win/settings").exists());
614    }
615
616    #[test]
617    fn dry_run_does_not_remove_stale_rendered() {
618        let tmp = TempDir::new().unwrap();
619        let r = root(&tmp);
620        write(&r.join("home/foo.tera"), "{# yui:when false #}\nbody");
621        write(&r.join("home/foo"), "old rendered output");
622        let _ = render_all(&r, &empty_config(), &yui_vars(&r), true).unwrap();
623        // Dry-run leaves the on-disk file alone.
624        assert_eq!(
625            std::fs::read_to_string(r.join("home/foo")).unwrap(),
626            "old rendered output"
627        );
628    }
629
630    #[test]
631    fn manage_gitignore_disabled_does_not_write_gitignore() {
632        let tmp = TempDir::new().unwrap();
633        let r = root(&tmp);
634        write(&r.join("home/foo.tera"), "body");
635        let mut cfg = empty_config();
636        cfg.render.manage_gitignore = false;
637        let _ = render_all(&r, &cfg, &yui_vars(&r), false).unwrap();
638        assert!(r.join("home/foo").exists());
639        assert!(!r.join(".gitignore").exists());
640    }
641}