yui-cli 0.7.20

Target-as-truth dotfiles manager: edit your live configs, source repo updates automatically via hardlink/junction/symlink.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
//! Tera template rendering for `*.tera` files.
//!
//! Output goes to the **same directory** as the source `.tera` file (e.g.
//! `home/.gitconfig.tera` → `home/.gitconfig`). When `manage_gitignore` is
//! true, the rendered files are listed in a `# >>> yui rendered ... <<<`
//! managed section of `.gitignore` so they aren't committed.
//!
//! Conditional render (both honored, AND'd together when both present):
//!   - file-header: `{# yui:when EXPR #}` as the first Tera comment in the
//!     `.tera` file. Tera comments are stripped from output, so the header
//!     never bleeds into the rendered file.
//!   - config rule: `[[render.rule]] match = "<glob>", when = "<expr>"` —
//!     the glob is matched against the path relative to the source root.
//!
//! Drift policy: if the rendered file already exists with content that
//! diverges from what the template would produce now, we DO NOT overwrite
//! it as a side effect of rendering. Each divergence is recorded as a
//! [`DivergedEntry`] (with both paths, the fresh body, and best-effort
//! mtimes) so callers can resolve it however they want — `apply` walks
//! the list and prompts the user per entry, `render --check` bails as
//! the CI gate.

use std::time::SystemTime;

use camino::{Utf8Path, Utf8PathBuf};
use globset::{Glob, GlobSet, GlobSetBuilder};
use tera::Context as TeraContext;

use crate::config::{Config, RenderRule};
use crate::paths;
use crate::template::{self, Engine};
use crate::vars::YuiVars;
use crate::{Error, Result};

const GITIGNORE_BEGIN: &str = "# >>> yui rendered (auto-managed, do not edit) >>>";
const GITIGNORE_END: &str = "# <<< yui rendered (auto-managed) <<<";

/// A render-drift case: the on-disk rendered file's content differs
/// from what the template would produce now. Carries the template
/// path, the rendered path, the fresh output (so callers can apply
/// it without re-rendering), and best-effort mtimes that the apply
/// prompt uses to pick a sensible default choice.
#[derive(Debug, Clone)]
pub struct DivergedEntry {
    /// `*.tera` source path.
    pub tera_path: Utf8PathBuf,
    /// Rendered sibling-without-suffix path (the on-disk file that diverged).
    pub rendered_path: Utf8PathBuf,
    /// What the template would produce right now (with current vars).
    pub fresh_body: String,
    /// `mtime` of the `.tera`, if obtainable.
    pub tera_mtime: Option<SystemTime>,
    /// `mtime` of the on-disk rendered file, if obtainable.
    pub rendered_mtime: Option<SystemTime>,
}

#[derive(Debug, Default)]
pub struct RenderReport {
    /// Templates rendered for the first time (or after deletion).
    pub written: Vec<Utf8PathBuf>,
    /// Rendered output identical to existing file — no write needed.
    pub unchanged: Vec<Utf8PathBuf>,
    /// Skipped because file-header or config rule `when` evaluated to false.
    pub skipped_when_false: Vec<Utf8PathBuf>,
    /// Existing rendered file diverges from current template output.
    /// `apply` resolves these interactively (`[o]verwrite` / `[s]kip` / …);
    /// `render --check` bails on them as the CI gate.
    pub diverged: Vec<DivergedEntry>,
}

impl RenderReport {
    pub fn has_drift(&self) -> bool {
        !self.diverged.is_empty()
    }
}

pub fn render_all(
    source: &Utf8Path,
    config: &Config,
    yui: &YuiVars,
    dry_run: bool,
) -> Result<RenderReport> {
    let mut engine = Engine::new();
    let ctx = template::template_context(yui, &config.vars);
    let rules = compile_rules(&config.render.rule)?;
    let mut report = RenderReport::default();

    // Walk every file under source. Filtering is centralized in
    // `paths::source_walker`: ignore-files OFF (so unrelated user rules
    // don't swallow `.tera`s) and `.yui/` skipped (backup mirrors etc.
    // shouldn't be rendered). `.yuiignore` is registered as a custom
    // ignore filename, so nested `.yuiignore` files are honored
    // automatically — no extra per-entry check needed here.
    let walker = paths::source_walker(source).build();
    for entry in walker {
        let entry = match entry {
            Ok(e) => e,
            Err(_) => continue,
        };
        if !entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
            continue;
        }
        let std_path = entry.path();
        let Some(name) = std_path.file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        if !name.ends_with(".tera") {
            continue;
        }
        let template_path = match Utf8PathBuf::from_path_buf(std_path.to_path_buf()) {
            Ok(p) => p,
            Err(_) => continue,
        };
        process_template(
            &template_path,
            source,
            &rules,
            &mut engine,
            &ctx,
            dry_run,
            &mut report,
        )?;
    }

    Ok(report)
}

/// Every `*.tera` output path the report knows about — written /
/// unchanged / diverged. The apply orchestrator unions this with
/// the secret pipeline's plaintext outputs to drive a single
/// `write_managed_section` call (rather than render writing one
/// list of paths and secrets immediately overwriting it with a
/// different one). PR #57 review.
pub fn report_managed_paths(report: &RenderReport) -> Vec<Utf8PathBuf> {
    collect_managed_paths(report)
}

/// Render a single template and return the body it would produce
/// right now, or `Ok(None)` if `{# yui:when … #}` / a config rule
/// `when` would skip it for the current host. Used by `yui diff`
/// to compute what the rendered file *should* contain so the
/// drift can be diffed against what's actually on disk.
///
/// Mirrors `process_template`'s skip / render decisions exactly,
/// but doesn't touch the report or the on-disk rendered output.
pub fn render_to_string(
    template_path: &Utf8Path,
    source: &Utf8Path,
    config: &Config,
    yui: &YuiVars,
) -> Result<Option<String>> {
    let raw = std::fs::read_to_string(template_path)
        .map_err(|e| Error::Template(format!("read {template_path}: {e}")))?;
    let mut engine = Engine::new();
    let ctx = template::template_context(yui, &config.vars);
    let rules = compile_rules(&config.render.rule)?;

    let body_input = if let Some((expr, body)) = split_yui_when(&raw) {
        if !eval_when(expr, &mut engine, &ctx)? {
            return Ok(None);
        }
        body.to_string()
    } else {
        raw
    };

    let rel = relative_to(source, template_path);
    let rel_for_match = rel.as_str().replace('\\', "/");
    for rule in &rules {
        // Nested ifs (not let-chains) so the crate's MSRV
        // (rust-version = "1.85") stays buildable.
        if rule.matcher.is_match(&rel_for_match) {
            if let Some(w) = &rule.when {
                if !eval_when(w, &mut engine, &ctx)? {
                    return Ok(None);
                }
            }
        }
    }

    Ok(Some(engine.render(&body_input, &ctx)?))
}

struct CompiledRule {
    matcher: GlobSet,
    when: Option<String>,
}

fn compile_rules(rules: &[RenderRule]) -> Result<Vec<CompiledRule>> {
    let mut out = Vec::with_capacity(rules.len());
    for r in rules {
        let glob = Glob::new(&r.r#match)
            .map_err(|e| Error::Config(format!("render.rule.match {:?}: {e}", r.r#match)))?;
        let mut b = GlobSetBuilder::new();
        b.add(glob);
        let matcher = b
            .build()
            .map_err(|e| Error::Config(format!("globset build: {e}")))?;
        out.push(CompiledRule {
            matcher,
            when: r.when.clone(),
        });
    }
    Ok(out)
}

fn process_template(
    template_path: &Utf8Path,
    source: &Utf8Path,
    rules: &[CompiledRule],
    engine: &mut Engine,
    ctx: &TeraContext,
    dry_run: bool,
    report: &mut RenderReport,
) -> Result<()> {
    let raw = std::fs::read_to_string(template_path)
        .map_err(|e| Error::Template(format!("read {template_path}: {e}")))?;
    let target = template_target(template_path);

    // Strip any `{# yui:when EXPR #}\n` header before handing the body to
    // Tera, so a falsy header doesn't leave a stray newline at the top of
    // a successful render.
    let body_input = if let Some((expr, body)) = split_yui_when(&raw) {
        if !eval_when(expr, engine, ctx)? {
            return skip_when_false(template_path, &target, dry_run, report);
        }
        body.to_string()
    } else {
        raw
    };

    let rel = relative_to(source, template_path);
    let rel_for_match = rel.as_str().replace('\\', "/");
    for rule in rules {
        if rule.matcher.is_match(&rel_for_match) {
            if let Some(w) = &rule.when {
                if !eval_when(w, engine, ctx)? {
                    return skip_when_false(template_path, &target, dry_run, report);
                }
            }
        }
    }

    let body = engine.render(&body_input, ctx)?;

    match std::fs::read_to_string(&target) {
        Ok(existing) if existing == body => {
            report.unchanged.push(target);
            return Ok(());
        }
        Ok(_) => {
            let tera_mtime = std::fs::metadata(template_path)
                .and_then(|m| m.modified())
                .ok();
            let rendered_mtime = std::fs::metadata(&target).and_then(|m| m.modified()).ok();
            report.diverged.push(DivergedEntry {
                tera_path: template_path.to_path_buf(),
                rendered_path: target,
                fresh_body: body,
                tera_mtime,
                rendered_mtime,
            });
            return Ok(());
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => return Err(Error::Template(format!("read {target}: {e}"))),
    }

    if !dry_run {
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&target, &body)?;
    }
    report.written.push(target);
    Ok(())
}

/// Common path for `when=false` skips: drops any stale rendered output so
/// the link walk doesn't end up linking yesterday's render of a now-disabled
/// template. Records the skip on the report.
fn skip_when_false(
    template_path: &Utf8Path,
    target: &Utf8Path,
    dry_run: bool,
    report: &mut RenderReport,
) -> Result<()> {
    if !dry_run && target.exists() {
        std::fs::remove_file(target)
            .map_err(|e| Error::Template(format!("removing stale rendered {target}: {e}")))?;
    }
    report.skipped_when_false.push(template_path.to_path_buf());
    Ok(())
}

/// If the file begins with a `{# yui:when EXPR #}` header (after optional
/// leading whitespace) followed by an immediate newline, returns
/// `(expr, body)` where `body` is the file content with that header line
/// stripped. Otherwise None.
fn split_yui_when(raw: &str) -> Option<(&str, &str)> {
    let leading_ws = raw.len() - raw.trim_start().len();
    let after_ws = &raw[leading_ws..];
    let after_open = after_ws.strip_prefix("{#")?;
    let close = after_open.find("#}")?;
    let inside = &after_open[..close];
    let expr = inside.trim().strip_prefix("yui:when")?.trim();

    let mut body_start = leading_ws + 2 + close + 2;
    if raw[body_start..].starts_with("\r\n") {
        body_start += 2;
    } else if raw[body_start..].starts_with('\n') {
        body_start += 1;
    }
    Some((expr, &raw[body_start..]))
}

/// Local alias for [`template::eval_truthy`] to keep call sites short.
fn eval_when(expr: &str, engine: &mut Engine, ctx: &TeraContext) -> Result<bool> {
    template::eval_truthy(expr, engine, ctx)
}

fn template_target(template_path: &Utf8Path) -> Utf8PathBuf {
    let s = template_path.as_str();
    debug_assert!(s.ends_with(".tera"));
    Utf8PathBuf::from(&s[..s.len() - ".tera".len()])
}

fn relative_to(base: &Utf8Path, p: &Utf8Path) -> Utf8PathBuf {
    p.strip_prefix(base)
        .map(Utf8PathBuf::from)
        .unwrap_or_else(|_| p.to_path_buf())
}

fn collect_managed_paths(report: &RenderReport) -> Vec<Utf8PathBuf> {
    let mut all: Vec<_> = report
        .written
        .iter()
        .chain(report.unchanged.iter())
        .chain(report.diverged.iter().map(|d| &d.rendered_path))
        .cloned()
        .collect();
    all.sort();
    all.dedup();
    all
}

/// Write or replace yui's managed `.gitignore` section in the
/// repo root, listing every absolute path the apply pipeline
/// produced as a sibling-without-suffix (rendered `.tera` outputs
/// AND decrypted `.age` outputs share this section). The block is
/// delimited by `# >>> yui rendered (auto-managed) >>>` /
/// `# <<< yui rendered (auto-managed) <<<` so successive runs
/// idempotently rewrite it without disturbing user content above
/// or below.
pub fn write_managed_section(source: &Utf8Path, managed_abs_paths: &[Utf8PathBuf]) -> Result<()> {
    update_gitignore(source, managed_abs_paths)
}

/// Additively merge `plaintext_abs_path` into yui's managed
/// `.gitignore` section, preserving every other entry already
/// there. Used by `yui secret encrypt` to close the window where a
/// freshly written plaintext sibling would be visible to `git add`
/// until the next `apply` rewrites the full managed block (issue
/// #71).
///
/// Unlike [`write_managed_section`], this is non-destructive: it
/// parses the existing section, unions the single new entry, sorts
/// and dedupes, and rewrites only the block between the markers.
/// Content above and below the markers is untouched.
pub fn add_to_managed_section(source: &Utf8Path, plaintext_abs_path: &Utf8Path) -> Result<()> {
    let gi_path = source.join(".gitignore");
    let existing = match std::fs::read_to_string(&gi_path) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(Error::Template(format!("read {gi_path}: {e}"))),
    };

    let new_entry = plaintext_abs_path
        .strip_prefix(source)
        .map(|p| p.as_str().to_string())
        .unwrap_or_else(|_| plaintext_abs_path.as_str().to_string())
        .replace('\\', "/");

    let mut managed = parse_managed_section(&existing);
    managed.push(new_entry);
    managed.sort();
    managed.dedup();

    let new_section = build_managed_section(&managed);
    let updated = replace_or_append_section(&existing, &new_section);

    if updated != existing {
        std::fs::write(&gi_path, updated)?;
    }
    Ok(())
}

fn parse_managed_section(text: &str) -> Vec<String> {
    let Some(start) = text.find(GITIGNORE_BEGIN) else {
        return Vec::new();
    };
    let Some(end) = text.find(GITIGNORE_END) else {
        return Vec::new();
    };
    if start >= end {
        return Vec::new();
    }
    let body_start = start + GITIGNORE_BEGIN.len();
    text[body_start..end]
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .map(str::to_string)
        .collect()
}

fn update_gitignore(source: &Utf8Path, rendered_abs_paths: &[Utf8PathBuf]) -> Result<()> {
    let gi_path = source.join(".gitignore");
    let existing = match std::fs::read_to_string(&gi_path) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(Error::Template(format!("read {gi_path}: {e}"))),
    };

    let mut managed: Vec<String> = rendered_abs_paths
        .iter()
        .filter_map(|p| p.strip_prefix(source).ok())
        .map(|p| p.as_str().replace('\\', "/"))
        .collect();
    managed.sort();
    managed.dedup();

    let new_section = build_managed_section(&managed);
    let updated = replace_or_append_section(&existing, &new_section);

    if updated != existing {
        std::fs::write(&gi_path, updated)?;
    }
    Ok(())
}

fn build_managed_section(lines: &[String]) -> String {
    let mut s = String::new();
    s.push_str(GITIGNORE_BEGIN);
    s.push('\n');
    for l in lines {
        s.push_str(l);
        s.push('\n');
    }
    s.push_str(GITIGNORE_END);
    s.push('\n');
    s
}

fn replace_or_append_section(existing: &str, new_section: &str) -> String {
    // Refactored from `if let ... && cond` (let-chains) to nested if so the
    // crate's MSRV (rust-version = "1.85") stays buildable; let-chains were
    // stabilized in 1.88.
    if let (Some(start), Some(end)) = (existing.find(GITIGNORE_BEGIN), existing.find(GITIGNORE_END))
    {
        if start < end {
            let end_line_end = match existing[end..].find('\n') {
                Some(idx) => end + idx + 1,
                None => existing.len(),
            };
            let mut out = String::with_capacity(existing.len() + new_section.len());
            out.push_str(&existing[..start]);
            out.push_str(new_section);
            out.push_str(&existing[end_line_end..]);
            return out;
        }
    }

    let mut out = String::from(existing);
    if !out.is_empty() && !out.ends_with('\n') {
        out.push('\n');
    }
    if !out.is_empty() {
        out.push('\n');
    }
    out.push_str(new_section);
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn yui_vars(source: &Utf8Path) -> YuiVars {
        YuiVars {
            os: "linux".into(),
            arch: "x86_64".into(),
            host: "test".into(),
            user: "u".into(),
            source: source.to_string(),
        }
    }

    fn root(tmp: &TempDir) -> Utf8PathBuf {
        Utf8PathBuf::from_path_buf(tmp.path().to_path_buf()).unwrap()
    }

    fn empty_config() -> Config {
        Config::default()
    }

    fn write(p: &Utf8Path, body: &str) {
        if let Some(parent) = p.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(p, body).unwrap();
    }

    #[test]
    fn split_yui_when_basic() {
        assert_eq!(
            split_yui_when("{# yui:when yui.os == 'linux' #}\nbody"),
            Some(("yui.os == 'linux'", "body"))
        );
        assert_eq!(
            split_yui_when("\n  {#yui:when 1 == 1#}\nbody"),
            Some(("1 == 1", "body"))
        );
        // CRLF line endings
        assert_eq!(
            split_yui_when("{# yui:when true #}\r\nbody"),
            Some(("true", "body"))
        );
        // No newline after header — header still parsed, body is the rest
        assert_eq!(
            split_yui_when("{# yui:when true #}body"),
            Some(("true", "body"))
        );
        assert_eq!(split_yui_when("body without header"), None);
        assert_eq!(split_yui_when("{# regular comment #}body"), None);
    }

    #[test]
    fn template_target_strips_tera_extension() {
        assert_eq!(
            template_target(Utf8Path::new("/a/b/foo.tera")),
            Utf8PathBuf::from("/a/b/foo")
        );
        assert_eq!(
            template_target(Utf8Path::new("home/.gitconfig.tera")),
            Utf8PathBuf::from("home/.gitconfig")
        );
    }

    #[test]
    fn renders_simple_template_to_sibling() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(
            &r.join("home/.gitconfig.tera"),
            "[user]\n  os = {{ yui.os }}\n",
        );
        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
        assert_eq!(report.written.len(), 1);
        assert_eq!(
            std::fs::read_to_string(r.join("home/.gitconfig")).unwrap(),
            "[user]\n  os = linux\n"
        );
    }

    #[test]
    fn renders_user_vars() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(&r.join("home/foo.tera"), "{{ vars.greet }}");
        let mut cfg = empty_config();
        cfg.vars
            .insert("greet".into(), toml::Value::String("hello".into()));
        let _ = render_all(&r, &cfg, &yui_vars(&r), false).unwrap();
        assert_eq!(
            std::fs::read_to_string(r.join("home/foo")).unwrap(),
            "hello"
        );
    }

    #[test]
    fn skips_when_file_header_false() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(
            &r.join("home/foo.tera"),
            "{# yui:when yui.os == 'windows' #}\nbody",
        );
        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
        assert!(report.written.is_empty());
        assert_eq!(report.skipped_when_false.len(), 1);
        assert!(!r.join("home/foo").exists());
    }

    #[test]
    fn includes_when_file_header_true() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(
            &r.join("home/foo.tera"),
            "{# yui:when yui.os == 'linux' #}\nbody",
        );
        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
        assert_eq!(report.written.len(), 1);
        assert_eq!(std::fs::read_to_string(r.join("home/foo")).unwrap(), "body");
    }

    #[test]
    fn config_rule_when_false_skips_matching_template() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(&r.join("home/win/settings.tera"), "body");
        let mut cfg = empty_config();
        cfg.render.rule.push(RenderRule {
            r#match: "home/win/**".into(),
            when: Some("{{ yui.os == 'windows' }}".into()),
        });
        let report = render_all(&r, &cfg, &yui_vars(&r), false).unwrap();
        assert_eq!(report.skipped_when_false.len(), 1);
        assert!(report.written.is_empty());
    }

    #[test]
    fn config_rule_no_match_does_not_filter() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(&r.join("home/foo.tera"), "body");
        let mut cfg = empty_config();
        // glob doesn't match foo.tera
        cfg.render.rule.push(RenderRule {
            r#match: "home/win/**".into(),
            when: Some("{{ yui.os == 'windows' }}".into()),
        });
        let report = render_all(&r, &cfg, &yui_vars(&r), false).unwrap();
        assert_eq!(report.written.len(), 1);
    }

    #[test]
    fn unchanged_when_existing_matches() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(&r.join("home/foo.tera"), "body");
        write(&r.join("home/foo"), "body"); // already in sync
        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
        assert!(report.written.is_empty());
        assert_eq!(report.unchanged.len(), 1);
    }

    #[test]
    fn detects_drift_when_existing_diverges() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(&r.join("home/foo.tera"), "fresh body");
        write(&r.join("home/foo"), "manually edited");
        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
        assert!(report.has_drift());
        assert_eq!(report.diverged.len(), 1);
        let entry = &report.diverged[0];
        assert_eq!(entry.tera_path, r.join("home/foo.tera"));
        assert_eq!(entry.rendered_path, r.join("home/foo"));
        // Fresh body is what the template would produce, NOT what's on disk.
        assert_eq!(entry.fresh_body, "fresh body");
        // Existing content NOT overwritten by render.
        assert_eq!(
            std::fs::read_to_string(r.join("home/foo")).unwrap(),
            "manually edited"
        );
    }

    #[test]
    fn dry_run_does_not_write_or_touch_gitignore() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(&r.join("home/foo.tera"), "body");
        let _ = render_all(&r, &empty_config(), &yui_vars(&r), true).unwrap();
        assert!(!r.join("home/foo").exists());
        assert!(!r.join(".gitignore").exists());
    }

    #[test]
    fn updates_gitignore_managed_section() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(&r.join("home/foo.tera"), "body");
        write(&r.join("home/bar.tera"), "body2");
        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
        // PR #57: render_all no longer manages .gitignore as a
        // side effect; callers (apply / cmd::render) drive the
        // single deterministic write.
        write_managed_section(&r, &report_managed_paths(&report)).unwrap();
        let gi = std::fs::read_to_string(r.join(".gitignore")).unwrap();
        assert!(gi.contains(GITIGNORE_BEGIN));
        assert!(gi.contains(GITIGNORE_END));
        assert!(gi.contains("home/bar"));
        assert!(gi.contains("home/foo"));
        // sorted: bar before foo
        let bar_pos = gi.find("home/bar").unwrap();
        let foo_pos = gi.find("home/foo").unwrap();
        assert!(bar_pos < foo_pos);
    }

    #[test]
    fn preserves_existing_gitignore_content() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(&r.join(".gitignore"), "node_modules/\ntarget/\n");
        write(&r.join("home/foo.tera"), "body");
        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
        write_managed_section(&r, &report_managed_paths(&report)).unwrap();
        let gi = std::fs::read_to_string(r.join(".gitignore")).unwrap();
        assert!(gi.contains("node_modules/"));
        assert!(gi.contains("target/"));
        assert!(gi.contains("home/foo"));
    }

    #[test]
    fn replaces_existing_managed_section() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        // Pre-existing managed section with stale content
        write(
            &r.join(".gitignore"),
            &format!("node_modules/\n\n{GITIGNORE_BEGIN}\nstale/path\n{GITIGNORE_END}\n\nfoo\n"),
        );
        write(&r.join("home/foo.tera"), "body");
        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
        write_managed_section(&r, &report_managed_paths(&report)).unwrap();
        let gi = std::fs::read_to_string(r.join(".gitignore")).unwrap();
        assert!(gi.contains("node_modules/"));
        assert!(gi.contains("home/foo"));
        assert!(!gi.contains("stale/path"));
        // post-section content preserved
        assert!(gi.contains("\nfoo\n"));
    }

    #[test]
    fn walks_into_gitignored_directories() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        // Pre-existing .gitignore that would normally hide `node_modules/`.
        write(&r.join(".gitignore"), "node_modules/\n");
        write(&r.join("node_modules/foo.tera"), "body");
        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
        // Template under a gitignored dir is still discovered + rendered.
        assert_eq!(report.written.len(), 1);
        assert!(r.join("node_modules/foo").exists());
    }

    #[test]
    fn removes_stale_rendered_when_file_header_becomes_false() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        // Previously rendered output sitting on disk
        write(
            &r.join("home/foo.tera"),
            "{# yui:when yui.os == 'windows' #}\nbody",
        );
        write(&r.join("home/foo"), "old rendered output");
        let report = render_all(&r, &empty_config(), &yui_vars(&r), false).unwrap();
        assert_eq!(report.skipped_when_false.len(), 1);
        // Stale sibling was cleaned up so apply won't link it.
        assert!(!r.join("home/foo").exists());
    }

    #[test]
    fn removes_stale_rendered_when_rule_when_becomes_false() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(&r.join("home/win/settings.tera"), "body");
        write(&r.join("home/win/settings"), "old rendered output");
        let mut cfg = empty_config();
        cfg.render.rule.push(RenderRule {
            r#match: "home/win/**".into(),
            when: Some("{{ yui.os == 'windows' }}".into()),
        });
        let report = render_all(&r, &cfg, &yui_vars(&r), false).unwrap();
        assert_eq!(report.skipped_when_false.len(), 1);
        assert!(!r.join("home/win/settings").exists());
    }

    #[test]
    fn dry_run_does_not_remove_stale_rendered() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(&r.join("home/foo.tera"), "{# yui:when false #}\nbody");
        write(&r.join("home/foo"), "old rendered output");
        let _ = render_all(&r, &empty_config(), &yui_vars(&r), true).unwrap();
        // Dry-run leaves the on-disk file alone.
        assert_eq!(
            std::fs::read_to_string(r.join("home/foo")).unwrap(),
            "old rendered output"
        );
    }

    #[test]
    fn add_to_managed_creates_section_when_missing() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        // No .gitignore at all yet — first encrypt should create one
        // with the new plaintext sibling inside the managed block.
        let plain = r.join("home/.config/foo/private.env");
        add_to_managed_section(&r, &plain).unwrap();
        let gi = std::fs::read_to_string(r.join(".gitignore")).unwrap();
        assert!(gi.contains(GITIGNORE_BEGIN));
        assert!(gi.contains(GITIGNORE_END));
        assert!(gi.contains("home/.config/foo/private.env"));
    }

    #[test]
    fn add_to_managed_preserves_existing_entries() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        // Pre-existing managed section with a render-produced entry
        // plus user content above + below.
        write(
            &r.join(".gitignore"),
            &format!(
                "node_modules/\n\n{GITIGNORE_BEGIN}\nhome/.gitconfig\n{GITIGNORE_END}\n\ntarget/\n"
            ),
        );
        let plain = r.join("home/.config/foo/private.env");
        add_to_managed_section(&r, &plain).unwrap();
        let gi = std::fs::read_to_string(r.join(".gitignore")).unwrap();
        // Existing render entry still there.
        assert!(gi.contains("home/.gitconfig"));
        // New secret entry merged in.
        assert!(gi.contains("home/.config/foo/private.env"));
        // User content above + below untouched.
        assert!(gi.contains("node_modules/"));
        assert!(gi.contains("target/"));
    }

    #[test]
    fn add_to_managed_is_idempotent() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        let plain = r.join("home/secret.env");
        add_to_managed_section(&r, &plain).unwrap();
        add_to_managed_section(&r, &plain).unwrap();
        let gi = std::fs::read_to_string(r.join(".gitignore")).unwrap();
        let occurrences = gi.matches("home/secret.env").count();
        assert_eq!(occurrences, 1, "duplicate entries in: {gi}");
    }

    #[test]
    fn add_to_managed_normalises_windows_separators() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        // Synthesise a backslash-bearing absolute path the way Windows
        // would; the managed section must always use forward slashes
        // so the `.gitignore` works on both platforms.
        let plain = Utf8PathBuf::from(format!("{}\\home\\.config\\foo\\private.env", r.as_str()));
        add_to_managed_section(&r, &plain).unwrap();
        let gi = std::fs::read_to_string(r.join(".gitignore")).unwrap();
        assert!(
            gi.contains("home/.config/foo/private.env"),
            "expected forward-slash entry in: {gi}"
        );
        assert!(
            !gi.contains("home\\.config"),
            "managed section should not carry backslashes: {gi}"
        );
    }

    #[test]
    fn manage_gitignore_disabled_does_not_write_gitignore() {
        let tmp = TempDir::new().unwrap();
        let r = root(&tmp);
        write(&r.join("home/foo.tera"), "body");
        let mut cfg = empty_config();
        cfg.render.manage_gitignore = false;
        let _ = render_all(&r, &cfg, &yui_vars(&r), false).unwrap();
        assert!(r.join("home/foo").exists());
        assert!(!r.join(".gitignore").exists());
    }
}