yui-cli 0.2.0

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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
//! Command implementations.
//!
//! Each `Command` variant in `cli.rs` calls one of these. Currently
//! implemented: `apply`, `init`, `doctor`. The rest are `todo!()`.

use std::fmt::Write as _;

use anyhow::{Context as _, Result};
use camino::{Utf8Path, Utf8PathBuf};
use tera::Context as TeraContext;
use tracing::{info, warn};

use crate::config::{self, Config, IconsMode, MountStrategy};
use crate::icons::Icons;
use crate::link::{self, EffectiveDirMode, EffectiveFileMode, resolve_dir_mode, resolve_file_mode};
use crate::marker::{self, MarkerSpec};
use crate::mount::{self, ResolvedMount};
use crate::render::{self, RenderReport};
use crate::template;
use crate::vars::YuiVars;
use crate::{backup, paths};

// NOTE: `owo_colors::OwoColorize` is intentionally NOT imported at module
// scope — its blanket impl shadows inherent methods of unrelated types
// (e.g. `ignore::WalkBuilder::hidden(bool)` collides with
// `OwoColorize::hidden(&self)`). Each print function imports the trait
// locally with `use owo_colors::OwoColorize as _;`.

pub fn init(source: Option<Utf8PathBuf>, _git_hooks: bool) -> Result<()> {
    let dir = match source {
        Some(s) => absolutize(&s)?,
        None => current_dir_utf8()?,
    };
    std::fs::create_dir_all(&dir)?;
    let config_path = dir.join("config.toml");
    if config_path.exists() {
        anyhow::bail!("config.toml already exists at {config_path}");
    }
    std::fs::write(&config_path, SKELETON_CONFIG)?;
    let gitignore_path = dir.join(".gitignore");
    if !gitignore_path.exists() {
        std::fs::write(&gitignore_path, SKELETON_GITIGNORE)?;
    }
    info!("initialized yui source repo at {dir}");
    info!("created: {config_path}");
    info!("next: edit config.toml, then run `yui apply`");
    Ok(())
}

pub fn apply(source: Option<Utf8PathBuf>, dry_run: bool) -> Result<()> {
    let source = resolve_source(source)?;
    let yui = YuiVars::detect(&source);
    let config = config::load(&source, &yui)?;

    // 1. Render templates first so the link walk picks up rendered files.
    let render_report = render::render_all(&source, &config, &yui, dry_run)?;
    log_render_report(&render_report);
    if render_report.has_drift() {
        anyhow::bail!(
            "render drift detected ({} file(s)); reflect target edits back into the .tera before re-running apply",
            render_report.diverged.len()
        );
    }

    // 2. Resolve mounts and link.
    let mut engine = template::Engine::new();
    let tera_ctx = template::template_context(&yui, &config.vars);
    let mounts = mount::resolve(
        &config.mount.entry,
        config.mount.default_strategy,
        &mut engine,
        &tera_ctx,
    )?;

    let backup_root = source.join(&config.backup.dir);
    let ctx = ApplyCtx {
        config: &config,
        file_mode: resolve_file_mode(config.link.file_mode),
        dir_mode: resolve_dir_mode(config.link.dir_mode),
        backup_root: &backup_root,
        dry_run,
    };

    info!("source: {source}");
    info!("modes: file={:?} dir={:?}", ctx.file_mode, ctx.dir_mode);
    if dry_run {
        info!("dry-run: nothing will be written");
    }

    for m in &mounts {
        info!("mount: {} → {}", m.src, m.dst);
        process_mount(&source, m, &ctx, &mut engine, &tera_ctx)?;
    }
    Ok(())
}

fn log_render_report(r: &RenderReport) {
    if !r.written.is_empty() {
        info!("rendered {} new file(s)", r.written.len());
    }
    if !r.unchanged.is_empty() {
        info!("rendered {} file(s) unchanged", r.unchanged.len());
    }
    if !r.skipped_when_false.is_empty() {
        info!(
            "skipped {} template(s) (when=false)",
            r.skipped_when_false.len()
        );
    }
    for d in &r.diverged {
        warn!("rendered file diverged from template: {d}");
    }
}

/// Bundle of immutable settings threaded through the apply walk.
struct ApplyCtx<'a> {
    config: &'a Config,
    file_mode: EffectiveFileMode,
    dir_mode: EffectiveDirMode,
    backup_root: &'a Utf8Path,
    dry_run: bool,
}

/// Show the resolved src→dst mappings for the current source repo.
///
/// By default only entries whose `when` matches the current host are shown
/// (`active`). With `--all`, inactive entries are included with a dim row
/// and the `when` condition that excluded them.
pub fn list(
    source: Option<Utf8PathBuf>,
    all: bool,
    icons_override: Option<IconsMode>,
    no_color: bool,
) -> Result<()> {
    let source = resolve_source(source)?;
    let yui = YuiVars::detect(&source);
    let config = config::load(&source, &yui)?;

    let icons_mode = icons_override.unwrap_or(config.ui.icons);
    let icons = Icons::for_mode(icons_mode);
    let color = !no_color && supports_color_stdout();

    let items = collect_list_items(&source, &config, &yui)?;
    let displayed: Vec<&ListItem> = if all {
        items.iter().collect()
    } else {
        items.iter().filter(|i| i.active).collect()
    };

    print_list_table(&displayed, icons, color);

    let total = items.len();
    let active = items.iter().filter(|i| i.active).count();
    let inactive = total - active;
    println!();
    if all {
        println!("  {total} entries · {active} active · {inactive} inactive");
    } else {
        println!(
            "  {} of {} entries shown ({} inactive hidden — use --all)",
            active, total, inactive
        );
    }
    Ok(())
}

#[derive(Debug)]
struct ListItem {
    src: Utf8PathBuf,
    dst: String,
    when: Option<String>,
    active: bool,
}

fn collect_list_items(source: &Utf8Path, config: &Config, yui: &YuiVars) -> Result<Vec<ListItem>> {
    let mut engine = template::Engine::new();
    let tera_ctx = template::template_context(yui, &config.vars);
    let mut items = Vec::new();

    // 1. config.toml [[mount.entry]] entries
    for entry in &config.mount.entry {
        let active = match &entry.when {
            None => true,
            Some(w) => template::eval_truthy(w, &mut engine, &tera_ctx)?,
        };
        let dst = engine
            .render(&entry.dst, &tera_ctx)
            .map(|s| s.trim().to_string())
            .unwrap_or_else(|_| entry.dst.clone());
        items.push(ListItem {
            src: entry.src.clone(),
            dst,
            when: entry.when.clone(),
            active,
        });
    }

    // 2. .yuilink overrides under source
    let walker = ignore::WalkBuilder::new(source)
        .hidden(false)
        .git_ignore(false)
        .ignore(false)
        .build();
    let marker_filename = &config.mount.marker_filename;
    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;
        }
        if entry.path().file_name().and_then(|n| n.to_str()) != Some(marker_filename.as_str()) {
            continue;
        }
        let dir = match entry.path().parent() {
            Some(d) => d,
            None => continue,
        };
        let dir_utf8 = match Utf8PathBuf::from_path_buf(dir.to_path_buf()) {
            Ok(p) => p,
            Err(_) => continue,
        };
        let spec = match marker::read_spec(&dir_utf8, marker_filename)? {
            Some(s) => s,
            None => continue,
        };
        let MarkerSpec::Override { links } = spec else {
            continue; // PassThrough markers are already implied by mount entry
        };
        let rel = dir_utf8
            .strip_prefix(source)
            .map(Utf8PathBuf::from)
            .unwrap_or(dir_utf8);
        for link in &links {
            let active = match &link.when {
                None => true,
                Some(w) => template::eval_truthy(w, &mut engine, &tera_ctx)?,
            };
            let dst = engine
                .render(&link.dst, &tera_ctx)
                .map(|s| s.trim().to_string())
                .unwrap_or_else(|_| link.dst.clone());
            items.push(ListItem {
                src: rel.clone(),
                dst,
                when: link.when.clone(),
                active,
            });
        }
    }

    items.sort_by(|a, b| a.src.cmp(&b.src).then_with(|| a.dst.cmp(&b.dst)));
    Ok(items)
}

fn supports_color_stdout() -> bool {
    use std::io::IsTerminal;
    std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none()
}

fn print_list_table(items: &[&ListItem], icons: Icons, color: bool) {
    let src_w = items
        .iter()
        .map(|i| i.src.as_str().chars().count())
        .max()
        .unwrap_or(0)
        .max("SRC".len());
    let dst_w = items
        .iter()
        .map(|i| i.dst.chars().count())
        .max()
        .unwrap_or(0)
        .max("DST".len());

    let status_w = "STATUS".len();
    let arrow_w = icons.arrow.chars().count();

    // Header
    print_header(status_w, src_w, arrow_w, dst_w, color);

    // Separator
    let sep = render_separator(icons.sep, status_w, src_w, arrow_w, dst_w);
    if color {
        use owo_colors::OwoColorize as _;
        println!("{}", sep.dimmed());
    } else {
        println!("{sep}");
    }

    // Rows
    for item in items {
        print_row(item, icons, status_w, src_w, arrow_w, dst_w, color);
    }
}

fn print_header(status_w: usize, src_w: usize, arrow_w: usize, dst_w: usize, color: bool) {
    use owo_colors::OwoColorize as _;
    let mut line = String::new();
    let _ = write!(
        &mut line,
        "  {:<status_w$}  {:<src_w$}  {:<arrow_w$}  {:<dst_w$}  WHEN",
        "STATUS", "SRC", "", "DST"
    );
    if color {
        println!("{}", line.bold());
    } else {
        println!("{line}");
    }
}

fn render_separator(
    sep_ch: char,
    status_w: usize,
    src_w: usize,
    arrow_w: usize,
    dst_w: usize,
) -> String {
    let bar = |n: usize| sep_ch.to_string().repeat(n);
    format!(
        "  {}  {}  {}  {}  {}",
        bar(status_w),
        bar(src_w),
        bar(arrow_w),
        bar(dst_w),
        bar("WHEN".len())
    )
}

fn print_row(
    item: &ListItem,
    icons: Icons,
    status_w: usize,
    src_w: usize,
    arrow_w: usize,
    dst_w: usize,
    color: bool,
) {
    use owo_colors::OwoColorize as _;
    let status = if item.active {
        icons.active
    } else {
        icons.inactive
    };
    let when_str = item
        .when
        .as_deref()
        .map(strip_braces)
        .unwrap_or_else(|| "(always)".to_string());

    // Normalize backslashes to forward slashes for cross-platform display.
    let src_display = item.src.as_str().replace('\\', "/");
    let src = src_display.as_str();
    let dst = &item.dst;
    let arrow = icons.arrow;

    // Pad each cell to its column width FIRST, then apply color. Doing it
    // the other way round lets ANSI escape codes count as printable chars
    // in `format!("{:<w$}")`, which silently breaks alignment when colors
    // are enabled (caught in PR #11 review).
    let cell_status = format!("{:<status_w$}", status);
    let cell_src = format!("{:<src_w$}", src);
    let cell_arrow = format!("{:<arrow_w$}", arrow);
    let cell_dst = format!("{:<dst_w$}", dst);

    if !color {
        println!("  {cell_status}  {cell_src}  {cell_arrow}  {cell_dst}  {when_str}");
        return;
    }

    if item.active {
        println!(
            "  {}  {}  {}  {}  {}",
            cell_status.green(),
            cell_src.cyan(),
            cell_arrow.dimmed(),
            cell_dst.green(),
            when_str.dimmed()
        );
    } else {
        println!(
            "  {}  {}  {}  {}  {}",
            cell_status.red().dimmed(),
            cell_src.dimmed(),
            cell_arrow.dimmed(),
            cell_dst.dimmed(),
            when_str.dimmed()
        );
    }
}

/// Strip the outer `{{ ... }}` Tera braces from a `when` expression for
/// display purposes (shorter line, easier to read at a glance).
fn strip_braces(expr: &str) -> String {
    let trimmed = expr.trim();
    if let Some(inner) = trimmed
        .strip_prefix("{{")
        .and_then(|s| s.strip_suffix("}}"))
    {
        inner.trim().to_string()
    } else {
        trimmed.to_string()
    }
}

pub fn render(source: Option<Utf8PathBuf>, check: bool, dry_run: bool) -> Result<()> {
    let source = resolve_source(source)?;
    let yui = YuiVars::detect(&source);
    let config = config::load(&source, &yui)?;
    // --check is a stricter dry-run: never writes, exits non-zero on drift.
    let report = render::render_all(&source, &config, &yui, dry_run || check)?;
    log_render_report(&report);
    if check && report.has_drift() {
        anyhow::bail!("render drift detected ({} file(s))", report.diverged.len());
    }
    Ok(())
}

pub fn link(source: Option<Utf8PathBuf>, dry_run: bool) -> Result<()> {
    // For now `link` and `apply` do the same thing (no render/absorb yet).
    apply(source, dry_run)
}

pub fn unlink(source: Option<Utf8PathBuf>, paths_arg: Vec<Utf8PathBuf>) -> Result<()> {
    let _source = resolve_source(source)?;
    if paths_arg.is_empty() {
        anyhow::bail!("yui unlink: provide at least one target path");
    }
    for p in paths_arg {
        let abs = absolutize(&p)?;
        info!("unlink: {abs}");
        link::unlink(&abs)?;
    }
    Ok(())
}

pub fn status(_source: Option<Utf8PathBuf>) -> Result<()> {
    todo!("yui status — drift detection (needs absorb classifier)")
}

pub fn absorb(_source: Option<Utf8PathBuf>, _target: Utf8PathBuf, _dry_run: bool) -> Result<()> {
    todo!("yui absorb — manual absorb (needs absorb classifier)")
}

pub fn doctor(source: Option<Utf8PathBuf>) -> Result<()> {
    let yui = YuiVars::detect(Utf8Path::new("."));
    println!("yui doctor");
    println!("==========");
    println!("os:    {}", yui.os);
    println!("arch:  {}", yui.arch);
    println!("user:  {}", yui.user);
    println!("host:  {}", yui.host);
    match resolve_source(source) {
        Ok(s) => {
            println!("source: {s}");
            // Probe: try loading config
            match config::load(&s, &yui) {
                Ok(cfg) => println!(
                    "config: ok ({} mount entries, {} render rules)",
                    cfg.mount.entry.len(),
                    cfg.render.rule.len()
                ),
                Err(e) => println!("config: ERROR — {e}"),
            }
        }
        Err(e) => println!("source: NOT FOUND — {e}"),
    }
    println!();
    println!("link mode (auto resolves to):");
    if cfg!(windows) {
        println!("  files: hardlink");
        println!("  dirs:  junction");
    } else {
        println!("  files: symlink");
        println!("  dirs:  symlink");
    }
    Ok(())
}

pub fn gc_backup(_source: Option<Utf8PathBuf>, _older_than: Option<String>) -> Result<()> {
    todo!("yui gc-backup — clean up old backups")
}

// ---------------------------------------------------------------------------
// internals
// ---------------------------------------------------------------------------

fn process_mount(
    source: &Utf8Path,
    m: &ResolvedMount,
    ctx: &ApplyCtx<'_>,
    engine: &mut template::Engine,
    tera_ctx: &TeraContext,
) -> Result<()> {
    let src_root = source.join(&m.src);
    if !src_root.is_dir() {
        warn!("mount src missing: {src_root}");
        return Ok(());
    }
    walk_and_link(&src_root, &m.dst, ctx, m.strategy, engine, tera_ctx)
}

fn walk_and_link(
    src_dir: &Utf8Path,
    dst_dir: &Utf8Path,
    ctx: &ApplyCtx<'_>,
    strategy: MountStrategy,
    engine: &mut template::Engine,
    tera_ctx: &TeraContext,
) -> Result<()> {
    let marker_filename = &ctx.config.mount.marker_filename;

    if strategy == MountStrategy::Marker {
        match marker::read_spec(src_dir, marker_filename)? {
            None => {} // no marker — fall through to recursive walk
            Some(MarkerSpec::PassThrough) => {
                link_dir_with_backup(src_dir, dst_dir, ctx)?;
                return Ok(());
            }
            Some(MarkerSpec::Override { links }) => {
                let mut linked_any = false;
                for link in &links {
                    // Nested ifs (not let-chains) so the crate's MSRV
                    // (rust-version = "1.85") stays buildable; let-chains
                    // were stabilized in 1.88.
                    if let Some(when) = &link.when {
                        if !template::eval_truthy(when, engine, tera_ctx)? {
                            continue;
                        }
                    }
                    let dst_str = engine.render(&link.dst, tera_ctx)?;
                    let dst = Utf8PathBuf::from(dst_str.trim());
                    link_dir_with_backup(src_dir, &dst, ctx)?;
                    linked_any = true;
                }
                if !linked_any {
                    info!("marker override at {src_dir} had no active links — skipping");
                }
                return Ok(());
            }
        }
    }

    for entry in std::fs::read_dir(src_dir)? {
        let entry = entry?;
        let name_os = entry.file_name();
        let Some(name) = name_os.to_str() else {
            continue;
        };
        if name == marker_filename {
            continue;
        }
        if name.ends_with(".tera") {
            // Templates are handled by the render flow before linking.
            continue;
        }

        let src_path = src_dir.join(name);
        let dst_path = dst_dir.join(name);
        let ft = entry.file_type()?;

        if ft.is_dir() {
            walk_and_link(&src_path, &dst_path, ctx, strategy, engine, tera_ctx)?;
        } else if ft.is_file() {
            link_file_with_backup(&src_path, &dst_path, ctx)?;
        }
    }
    Ok(())
}

fn link_file_with_backup(src: &Utf8Path, dst: &Utf8Path, ctx: &ApplyCtx<'_>) -> Result<()> {
    if ctx.dry_run {
        info!("[dry-run] link file: {src} → {dst}");
        return Ok(());
    }
    if std::fs::symlink_metadata(dst).is_ok() {
        backup_existing(dst, ctx.backup_root, /*is_dir=*/ false)?;
        link::unlink(dst)?;
    }
    info!("link file: {src} → {dst}");
    link::link_file(src, dst, ctx.file_mode)?;
    Ok(())
}

fn link_dir_with_backup(src: &Utf8Path, dst: &Utf8Path, ctx: &ApplyCtx<'_>) -> Result<()> {
    if ctx.dry_run {
        info!("[dry-run] link dir: {src} → {dst}");
        return Ok(());
    }
    if std::fs::symlink_metadata(dst).is_ok() {
        backup_existing(dst, ctx.backup_root, /*is_dir=*/ true)?;
        link::unlink(dst)?;
    }
    info!("link dir: {src} → {dst}");
    link::link_dir(src, dst, ctx.dir_mode)?;
    Ok(())
}

fn backup_existing(target: &Utf8Path, backup_root: &Utf8Path, is_dir: bool) -> Result<()> {
    let abs_target = absolutize(target)?;
    let ts = backup::current_timestamp("%Y%m%d_%H%M%S%3f")?;
    let bp = paths::append_timestamp(&paths::mirror_into_backup(backup_root, &abs_target), &ts);
    info!("backup → {bp}");
    if is_dir {
        backup::backup_dir(target, &bp)?;
    } else {
        backup::backup_file(target, &bp)?;
    }
    Ok(())
}

fn resolve_source(source: Option<Utf8PathBuf>) -> Result<Utf8PathBuf> {
    if let Some(s) = source {
        return absolutize(&s);
    }
    if let Ok(s) = std::env::var("YUI_SOURCE") {
        return absolutize(Utf8Path::new(&s));
    }
    let cwd = current_dir_utf8()?;
    for ancestor in cwd.ancestors() {
        if ancestor.join("config.toml").is_file() {
            return Ok(ancestor.to_path_buf());
        }
    }
    if let Some(home) = home_dir() {
        for c in ["dotfiles", ".dotfiles", "src/dotfiles"] {
            let p = home.join(c);
            if p.join("config.toml").is_file() {
                return Ok(p);
            }
        }
    }
    anyhow::bail!("source repo not found (set --source / $YUI_SOURCE)")
}

fn absolutize(p: &Utf8Path) -> Result<Utf8PathBuf> {
    if p.is_absolute() {
        return Ok(p.to_path_buf());
    }
    let cwd = current_dir_utf8()?;
    Ok(cwd.join(p))
}

fn current_dir_utf8() -> Result<Utf8PathBuf> {
    let cwd = std::env::current_dir().context("getting cwd")?;
    Utf8PathBuf::from_path_buf(cwd).map_err(|p| anyhow::anyhow!("non-UTF8 cwd: {}", p.display()))
}

fn home_dir() -> Option<Utf8PathBuf> {
    std::env::var("HOME")
        .ok()
        .or_else(|| std::env::var("USERPROFILE").ok())
        .map(Utf8PathBuf::from)
}

const SKELETON_CONFIG: &str = r#"# yui config — see https://github.com/yukimemi/yui

[vars]
# user-defined values; templates can reference these as {{ vars.foo }}

# [link]
# file_mode = "auto"   # auto | symlink | hardlink
# dir_mode  = "auto"   # auto | symlink | junction

[mount]
default_strategy = "marker"

[[mount.entry]]
src = "home"
dst = "{{ env(name='HOME') | default(value=env(name='USERPROFILE')) }}"

# [[mount.entry]]
# src  = "appdata"
# dst  = "{{ env(name='APPDATA') }}"
# # NOTE: write `when` as a *bare* expression (no `{{ … }}`) so it survives
# # config.toml's whole-file Tera render and shows up cleanly in `yui list`.
# when = "yui.os == 'windows'"
"#;

const SKELETON_GITIGNORE: &str = r#"# yui internals (regenerable, do not commit)
/.yui/

# >>> yui rendered (auto-managed, do not edit) >>>
# <<< yui rendered (auto-managed) <<<

# config.local.toml is per-machine; commit a config.local.example.toml instead.
config.local.toml
"#;

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

    fn utf8(p: std::path::PathBuf) -> Utf8PathBuf {
        Utf8PathBuf::from_path_buf(p).unwrap()
    }

    /// Convert a path to a TOML-string-safe form (forward slashes).
    fn toml_path(p: &Utf8Path) -> String {
        p.as_str().replace('\\', "/")
    }

    #[test]
    fn apply_links_a_raw_file() {
        let tmp = TempDir::new().unwrap();
        let source = utf8(tmp.path().join("dotfiles"));
        let target = utf8(tmp.path().join("target"));
        std::fs::create_dir_all(source.join("home")).unwrap();
        std::fs::create_dir_all(&target).unwrap();
        std::fs::write(source.join("home/.bashrc"), "echo hi\n").unwrap();

        let cfg = format!(
            r#"
[[mount.entry]]
src = "home"
dst = "{}"
"#,
            toml_path(&target)
        );
        std::fs::write(source.join("config.toml"), cfg).unwrap();

        apply(Some(source), false).unwrap();

        let linked = target.join(".bashrc");
        assert!(linked.exists(), "expected {linked} to exist");
        assert_eq!(std::fs::read_to_string(&linked).unwrap(), "echo hi\n");
    }

    #[test]
    fn apply_with_marker_links_whole_directory() {
        let tmp = TempDir::new().unwrap();
        let source = utf8(tmp.path().join("dotfiles"));
        let target = utf8(tmp.path().join("target"));
        let nvim_src = source.join("home/nvim");
        std::fs::create_dir_all(&nvim_src).unwrap();
        std::fs::create_dir_all(&target).unwrap();
        std::fs::write(nvim_src.join(".yuilink"), "").unwrap();
        std::fs::write(nvim_src.join("init.lua"), "-- hi\n").unwrap();
        std::fs::write(nvim_src.join("plugins.lua"), "-- plugins\n").unwrap();

        let cfg = format!(
            r#"
[[mount.entry]]
src = "home"
dst = "{}"
"#,
            toml_path(&target)
        );
        std::fs::write(source.join("config.toml"), cfg).unwrap();

        apply(Some(source.clone()), false).unwrap();

        let nvim_dst = target.join("nvim");
        assert!(nvim_dst.exists());
        assert_eq!(
            std::fs::read_to_string(nvim_dst.join("init.lua")).unwrap(),
            "-- hi\n"
        );
        // Marker file itself shouldn't be visible as a separate link in target;
        // however with junction/symlink the whole dir shows up so the marker
        // file IS visible inside. That's fine — the marker is informational.
    }

    #[test]
    fn apply_dry_run_does_not_write() {
        let tmp = TempDir::new().unwrap();
        let source = utf8(tmp.path().join("dotfiles"));
        let target = utf8(tmp.path().join("target"));
        std::fs::create_dir_all(source.join("home")).unwrap();
        std::fs::create_dir_all(&target).unwrap();
        std::fs::write(source.join("home/.bashrc"), "echo hi").unwrap();

        let cfg = format!(
            r#"
[[mount.entry]]
src = "home"
dst = "{}"
"#,
            toml_path(&target)
        );
        std::fs::write(source.join("config.toml"), cfg).unwrap();

        apply(Some(source), true).unwrap();

        assert!(!target.join(".bashrc").exists());
    }

    #[test]
    fn apply_renders_templates_then_links_rendered_outputs() {
        let tmp = TempDir::new().unwrap();
        let source = utf8(tmp.path().join("dotfiles"));
        let target = utf8(tmp.path().join("target"));
        std::fs::create_dir_all(source.join("home")).unwrap();
        std::fs::create_dir_all(&target).unwrap();
        std::fs::write(
            source.join("home/.gitconfig.tera"),
            "[user]\n  os = {{ yui.os }}\n",
        )
        .unwrap();
        std::fs::write(source.join("home/.bashrc"), "raw").unwrap();

        let cfg = format!(
            r#"
[[mount.entry]]
src = "home"
dst = "{}"
"#,
            toml_path(&target)
        );
        std::fs::write(source.join("config.toml"), cfg).unwrap();

        apply(Some(source.clone()), false).unwrap();

        // Raw file: linked.
        assert!(target.join(".bashrc").exists());
        // Template's rendered output: written to source then linked.
        assert!(source.join("home/.gitconfig").exists());
        assert!(target.join(".gitconfig").exists());
        // The .tera file itself is never linked into target.
        assert!(!target.join(".gitconfig.tera").exists());
        // Rendered file content carries the yui.os substitution.
        let linked = std::fs::read_to_string(target.join(".gitconfig")).unwrap();
        assert!(linked.contains("os = "));
    }

    #[test]
    fn apply_marker_override_links_to_custom_dst() {
        let tmp = TempDir::new().unwrap();
        let source = utf8(tmp.path().join("dotfiles"));
        let target_a = utf8(tmp.path().join("target_a"));
        let target_b = utf8(tmp.path().join("target_b"));
        std::fs::create_dir_all(source.join("home/.config/nvim")).unwrap();
        std::fs::create_dir_all(&target_a).unwrap();
        std::fs::create_dir_all(&target_b).unwrap();
        std::fs::write(
            source.join("home/.config/nvim/init.lua"),
            "-- nvim config\n",
        )
        .unwrap();

        // Marker tells yui to ignore the parent mount's dst for this dir
        // and link it to two custom places (the second only if condition matches).
        std::fs::write(
            source.join("home/.config/nvim/.yuilink"),
            format!(
                r#"
[[link]]
dst = "{}/nvim"

[[link]]
dst = "{}/nvim"
when = "{{{{ yui.os == '{}' }}}}"
"#,
                toml_path(&target_a),
                toml_path(&target_b),
                std::env::consts::OS
            ),
        )
        .unwrap();

        let parent_target = utf8(tmp.path().join("parent_target"));
        std::fs::create_dir_all(&parent_target).unwrap();
        let cfg = format!(
            r#"
[[mount.entry]]
src = "home"
dst = "{}"
"#,
            toml_path(&parent_target)
        );
        std::fs::write(source.join("config.toml"), cfg).unwrap();

        apply(Some(source.clone()), false).unwrap();

        // Both override targets received the link (the second's when matches OS).
        assert!(
            target_a.join("nvim/init.lua").exists(),
            "target_a/nvim/init.lua should be reachable through the link"
        );
        assert!(
            target_b.join("nvim/init.lua").exists(),
            "target_b/nvim/init.lua should be reachable through the link"
        );
        // Parent mount did NOT also link this dir (it would have appeared at
        // parent_target/.config/nvim — the marker claims the dir).
        assert!(
            !parent_target.join(".config/nvim").exists(),
            "parent mount should have skipped the marker-claimed sub-dir"
        );
    }

    #[test]
    fn apply_marker_override_skips_inactive_link() {
        let tmp = TempDir::new().unwrap();
        let source = utf8(tmp.path().join("dotfiles"));
        let target_inactive = utf8(tmp.path().join("inactive"));
        let parent_target = utf8(tmp.path().join("parent"));
        std::fs::create_dir_all(source.join("home/.config/nvim")).unwrap();
        std::fs::create_dir_all(&parent_target).unwrap();
        std::fs::write(source.join("home/.config/nvim/init.lua"), "x").unwrap();

        // when=false on every link → marker has no active links.
        std::fs::write(
            source.join("home/.config/nvim/.yuilink"),
            format!(
                r#"
[[link]]
dst = "{}/nvim"
when = "{{{{ yui.os == 'no-such-os' }}}}"
"#,
                toml_path(&target_inactive)
            ),
        )
        .unwrap();

        let cfg = format!(
            r#"
[[mount.entry]]
src = "home"
dst = "{}"
"#,
            toml_path(&parent_target)
        );
        std::fs::write(source.join("config.toml"), cfg).unwrap();

        apply(Some(source.clone()), false).unwrap();

        // Inactive target untouched.
        assert!(!target_inactive.join("nvim").exists());
        // Parent mount also skipped the dir (marker claims it even when
        // all links are inactive — the user's intent was per-dir override).
        assert!(!parent_target.join(".config/nvim").exists());
    }

    #[test]
    fn list_shows_mount_entries_and_marker_overrides() {
        let tmp = TempDir::new().unwrap();
        let source = utf8(tmp.path().join("dotfiles"));
        std::fs::create_dir_all(source.join("home/.config/nvim")).unwrap();
        std::fs::write(source.join("home/.config/nvim/init.lua"), "x").unwrap();
        std::fs::write(
            source.join("home/.config/nvim/.yuilink"),
            r#"
[[link]]
dst = "/custom/nvim"
"#,
        )
        .unwrap();
        std::fs::write(
            source.join("config.toml"),
            r#"
[[mount.entry]]
src = "home"
dst = "/h"
"#,
        )
        .unwrap();

        // Just verify it runs without error — output format is covered by
        // unit-level helpers below.
        list(Some(source), false, None, true).unwrap();
    }

    #[test]
    fn strip_braces_removes_outer_template_braces() {
        assert_eq!(strip_braces("{{ yui.os == 'linux' }}"), "yui.os == 'linux'");
        assert_eq!(strip_braces("yui.os == 'linux'"), "yui.os == 'linux'");
        assert_eq!(strip_braces("  {{x}}  "), "x");
    }

    #[test]
    fn apply_aborts_on_render_drift() {
        let tmp = TempDir::new().unwrap();
        let source = utf8(tmp.path().join("dotfiles"));
        let target = utf8(tmp.path().join("target"));
        std::fs::create_dir_all(source.join("home")).unwrap();
        std::fs::create_dir_all(&target).unwrap();
        std::fs::write(source.join("home/foo.tera"), "fresh body").unwrap();
        std::fs::write(source.join("home/foo"), "manually edited").unwrap();

        let cfg = format!(
            r#"
[[mount.entry]]
src = "home"
dst = "{}"
"#,
            toml_path(&target)
        );
        std::fs::write(source.join("config.toml"), cfg).unwrap();

        let err = apply(Some(source.clone()), false).unwrap_err();
        assert!(format!("{err}").contains("drift"));
        // Existing rendered file untouched.
        assert_eq!(
            std::fs::read_to_string(source.join("home/foo")).unwrap(),
            "manually edited"
        );
        // Linking aborted — target empty.
        assert!(!target.join("foo").exists());
    }

    #[test]
    fn init_creates_skeleton_when_dir_empty() {
        let tmp = TempDir::new().unwrap();
        let dir = utf8(tmp.path().join("new_dotfiles"));
        init(Some(dir.clone()), false).unwrap();
        assert!(dir.join("config.toml").is_file());
        assert!(dir.join(".gitignore").is_file());
    }

    #[test]
    fn init_refuses_to_overwrite_existing_config() {
        let tmp = TempDir::new().unwrap();
        let dir = utf8(tmp.path().join("dotfiles"));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("config.toml"), "preexisting").unwrap();
        let err = init(Some(dir), false).unwrap_err();
        assert!(format!("{err}").contains("already exists"));
    }

    #[test]
    fn apply_with_existing_target_backs_up() {
        let tmp = TempDir::new().unwrap();
        let source = utf8(tmp.path().join("dotfiles"));
        let target = utf8(tmp.path().join("target"));
        std::fs::create_dir_all(source.join("home")).unwrap();
        std::fs::create_dir_all(&target).unwrap();
        std::fs::write(source.join("home/.bashrc"), "new content").unwrap();
        // Pre-existing target file with different content.
        std::fs::write(target.join(".bashrc"), "old content").unwrap();

        let cfg = format!(
            r#"
[[mount.entry]]
src = "home"
dst = "{}"
"#,
            toml_path(&target)
        );
        std::fs::write(source.join("config.toml"), cfg).unwrap();

        apply(Some(source.clone()), false).unwrap();

        // Target now has new content (linked from source).
        assert_eq!(
            std::fs::read_to_string(target.join(".bashrc")).unwrap(),
            "new content"
        );

        // A backup of the old content should exist somewhere under .yui/backup.
        let backup_root = source.join(".yui/backup");
        assert!(backup_root.exists(), "backup root should exist");
        let mut found_old = false;
        for entry in walkdir(&backup_root) {
            if let Ok(s) = std::fs::read_to_string(&entry) {
                if s == "old content" {
                    found_old = true;
                    break;
                }
            }
        }
        assert!(found_old, "expected backup containing 'old content'");
    }

    fn walkdir(root: &Utf8Path) -> Vec<Utf8PathBuf> {
        let mut out = Vec::new();
        let mut stack = vec![root.to_path_buf()];
        while let Some(dir) = stack.pop() {
            let Ok(entries) = std::fs::read_dir(&dir) else {
                continue;
            };
            for e in entries.flatten() {
                let p = utf8(e.path());
                if e.file_type().map(|t| t.is_dir()).unwrap_or(false) {
                    stack.push(p);
                } else {
                    out.push(p);
                }
            }
        }
        out
    }
}