sennit 0.18.1

A dotfiles manager that keeps symlink semantics, and adds templating and drift detection
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
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
//! バイナリを実際に動かして、壊れると困る振る舞いを固定する。
//!
//! 単体テストは補助関数の形を見るだけで、`apply` が何をするかは見ていない。
//! 実際 --dry-run が書き込む、相対 --root が自分を指すリンクを作る、退避の
//! 記録が消える、といった不具合は 98 件のテストを 1 つも落とさずに再現できた。
//! ここでは $HOME を隔離して、コマンドの結果をファイルシステムで確かめる。

use std::path::{Path, PathBuf};
use std::process::{Command, Output};

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_sennit")
}

struct Repo {
    root: PathBuf,
    home: PathBuf,
}

impl Repo {
    fn new(name: &str) -> Self {
        let base = std::env::temp_dir().join(format!("sennit-it-{name}"));
        // 前回の実行が権限を狭めたまま終わっていると remove_dir_all が通らない。
        // テストが落ちた後にもう一度走らせられないのは、それ自体が困る。
        if base.exists() {
            let _ = Command::new("chmod")
                .arg("-R")
                .arg("u+rwX")
                .arg(&base)
                .status();
        }
        let _ = std::fs::remove_dir_all(&base);
        let root = base.join("repo");
        let home = base.join("home");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::create_dir_all(&home).unwrap();
        std::fs::write(root.join("packages.toml"), "[packages]\n").unwrap();
        Repo { root, home }
    }

    fn write(&self, rel: &str, body: &str) {
        let p = self.root.join(rel);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(p, body).unwrap();
    }

    fn write_home(&self, rel: &str, body: &str) {
        let p = self.home.join(rel);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(p, body).unwrap();
    }

    fn manifest(&self, body: &str) {
        std::fs::write(self.root.join("sennit.toml"), body).unwrap();
    }

    fn run(&self, args: &[&str]) -> Output {
        Command::new(bin())
            .arg("--root")
            .arg(&self.root)
            .arg("--home")
            .arg(&self.home)
            .args(args)
            .output()
            .unwrap()
    }

    /// カレントディャレクトリをリポジトリに置いたまま、相対の --root で走らせる
    fn run_relative(&self, args: &[&str]) -> Output {
        Command::new(bin())
            .current_dir(&self.root)
            .arg("--root")
            .arg(".")
            .arg("--home")
            .arg(&self.home)
            .args(args)
            .output()
            .unwrap()
    }

    fn home_path(&self, rel: &str) -> PathBuf {
        self.home.join(rel)
    }

    fn root_path(&self, rel: &str) -> PathBuf {
        self.root.join(rel)
    }
}

fn ok(out: &Output) -> String {
    assert!(
        out.status.success(),
        "command failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8_lossy(&out.stdout).to_string()
}

fn mode_of(p: &Path) -> u32 {
    use std::os::unix::fs::PermissionsExt;
    std::fs::metadata(p).unwrap().permissions().mode() & 0o777
}

/// --dry-run は symlink も生成物も書かない。
///
/// プロバイダと復号コマンドを呼ばないことは
/// dry_run_calls_neither_a_provider_nor_a_decryption_command で見る。
#[test]
fn dry_run_writes_nothing() {
    let r = Repo::new("dry-run");
    r.manifest(
        r#"
[link]
common = ["a.conf", "gen.conf"]
ignore = ["*.tmpl"]

[render]
"gen.conf" = "gen.conf.tmpl"
"#,
    );
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write("a.conf", "plain\n");
    r.write("gen.conf.tmpl", "x = {{ bg }}\n");

    let out = ok(&r.run(&["apply", "--dry-run"]));
    assert!(out.contains("nothing written"), "{out}");
    // 生成物がリポジトリに出来ていない
    assert!(!r.root_path("gen.conf").exists(), "dry-run wrote gen.conf");
    // $HOME に何も置かれていない
    assert_eq!(std::fs::read_dir(&r.home).unwrap().count(), 0);
    // これから起きることの件数は本番と一致する
    assert!(out.contains("2 change(s)"), "{out}");
}

/// 相対の --root でも、リンク先は絶対パスになる。
///
/// 相対のままだと a.conf -> ./a.conf という自分自身を指すリンクになり、
/// 元のファイルは退避された後で二度と読めなくなる。
#[test]
fn a_relative_root_does_not_produce_a_self_link() {
    let r = Repo::new("relative-root");
    r.manifest("[link]\ncommon = [\"a.conf\"]\n");
    r.write("a.conf", "from the repo\n");

    ok(&r.run_relative(&["apply"]));
    let target = std::fs::read_link(r.home_path("a.conf")).unwrap();
    assert!(target.is_absolute(), "link target is relative: {target:?}");
    assert_eq!(
        std::fs::read_to_string(r.home_path("a.conf")).unwrap(),
        "from the repo\n"
    );
}

/// 退避の記録は次の apply でも残り、rollback が効く。
#[test]
fn a_backup_survives_a_later_apply() {
    let r = Repo::new("backup-survives");
    r.manifest("[link]\ncommon = [\"a.conf\"]\n");
    r.write("a.conf", "repo\n");
    r.write("b.conf", "repo b\n");
    r.write_home("a.conf", "MINE\n");

    ok(&r.run(&["apply"]));
    // 宣言を足して 2 回目
    r.manifest("[link]\ncommon = [\"a.conf\", \"b.conf\"]\n");
    ok(&r.run(&["apply"]));

    let out = ok(&r.run(&["rollback"]));
    assert!(out.contains("1 file(s) restored"), "{out}");
    assert_eq!(
        std::fs::read_to_string(r.home_path("a.conf")).unwrap(),
        "MINE\n"
    );
}

/// 同じ行き先に退避が 2 つあっても、古い方を消さない。
#[test]
fn rollback_does_not_destroy_an_older_backup() {
    let r = Repo::new("rollback-two");
    r.manifest("[link]\ncommon = [\"a.conf\"]\n");
    r.write("a.conf", "repo\n");
    r.write_home("a.conf", "FIRST\n");

    ok(&r.run(&["apply"]));
    // 利用者がリンクを外して自分のファイルを置き直した
    std::fs::remove_file(r.home_path("a.conf")).unwrap();
    r.write_home("a.conf", "SECOND\n");
    ok(&r.run(&["apply"]));

    ok(&r.run(&["rollback"]));
    // 最も新しいものが戻る
    assert_eq!(
        std::fs::read_to_string(r.home_path("a.conf")).unwrap(),
        "SECOND\n"
    );
    // 古い方はファイルとして残っている
    let first = std::fs::read_dir(&r.home)
        .unwrap()
        .filter_map(Result::ok)
        .any(|e| std::fs::read_to_string(e.path()).unwrap_or_default() == "FIRST\n");
    assert!(first, "the older backup was destroyed");
}

/// フックが落ちても、退避したファイルの在り処は失われない。
#[test]
fn a_failing_hook_does_not_strand_a_backup() {
    let r = Repo::new("hook-fails");
    r.manifest("[link]\ncommon = [\"a.conf\"]\n\n[hooks.boom]\nrun = \"exit 1\"\n");
    r.write("a.conf", "repo\n");
    r.write_home("a.conf", "MINE\n");

    let out = r.run(&["apply"]);
    assert!(!out.status.success(), "the failing hook should fail apply");

    ok(&r.run(&["rollback"]));
    assert_eq!(
        std::fs::read_to_string(r.home_path("a.conf")).unwrap(),
        "MINE\n"
    );
}

/// prune が消すのは、自分が張ったリンクだけ。
#[test]
fn prune_leaves_a_foreign_link_alone() {
    let r = Repo::new("prune-foreign");
    r.manifest("[link]\ncommon = [\"a.conf\"]\n");
    r.write("a.conf", "repo\n");
    ok(&r.run(&["apply"]));

    // 利用者が管理をやめて、自分で別の場所へリンクを張り直した
    std::fs::remove_file(r.home_path("a.conf")).unwrap();
    let elsewhere = r.home.join("elsewhere.conf");
    std::fs::write(&elsewhere, "theirs\n").unwrap();
    std::os::unix::fs::symlink(&elsewhere, r.home_path("a.conf")).unwrap();

    r.manifest("[link]\ncommon = []\n");
    let out = ok(&r.run(&["apply"]));
    assert!(out.contains("left alone"), "{out}");
    assert_eq!(
        std::fs::read_link(r.home_path("a.conf")).unwrap(),
        elsewhere
    );
}

/// prune が消すのは、自分が張ったリンク。宣言から外れたら消える。
#[test]
fn prune_removes_a_link_it_made() {
    let r = Repo::new("prune-own");
    r.manifest("[link]\ncommon = [\"a.conf\"]\n");
    r.write("a.conf", "repo\n");
    ok(&r.run(&["apply"]));
    assert!(r.home_path("a.conf").exists());

    r.manifest("[link]\ncommon = []\n");
    let out = ok(&r.run(&["apply"]));
    assert!(out.contains("prune"), "{out}");
    assert!(std::fs::symlink_metadata(r.home_path("a.conf")).is_err());
}

/// ignore を書き忘れても、テンプレート本体は $HOME に置かれない。
#[test]
fn a_template_is_never_placed_even_without_ignore() {
    let r = Repo::new("no-ignore");
    // ignore を意図的に書かない
    r.manifest(
        r#"
[link]
common = ["conf"]

[render]
"conf/app.conf" = "conf/app.conf.tmpl"
"#,
    );
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write("conf/app.conf.tmpl", "x = {{ bg }}\n");

    ok(&r.run(&["apply"]));
    assert!(
        std::fs::symlink_metadata(r.home_path("conf/app.conf.tmpl")).is_err(),
        "the template itself was placed in $HOME"
    );
    assert_eq!(
        std::fs::read_to_string(r.home_path("conf/app.conf")).unwrap(),
        "x = zzz\n"
    );
}

/// 宣言したモードは、ただ張っただけのファイルにも効く。
#[test]
fn a_declared_mode_is_applied_to_a_plain_link() {
    let r = Repo::new("modes");
    r.manifest("[link]\ncommon = [\".npmrc\"]\n\n[modes]\n\".npmrc\" = \"600\"\n");
    r.write(".npmrc", "token\n");
    std::fs::set_permissions(
        r.root_path(".npmrc"),
        <std::fs::Permissions as std::os::unix::fs::PermissionsExt>::from_mode(0o644),
    )
    .unwrap();

    ok(&r.run(&["apply"]));
    assert_eq!(mode_of(&r.root_path(".npmrc")), 0o600);
    // verify も同じ判断をする
    let out = r.run(&["verify"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

/// 生成物は読み取り専用で置かれる。
#[test]
fn generated_files_are_read_only() {
    let r = Repo::new("read-only");
    r.manifest(
        r#"
[link]
common = ["gen.conf"]
ignore = ["*.tmpl"]

[render]
"gen.conf" = "gen.conf.tmpl"
"#,
    );
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write("gen.conf.tmpl", "x = {{ bg }}\n");

    ok(&r.run(&["apply"]));
    assert_eq!(mode_of(&r.root_path("gen.conf")), 0o444);
}

/// まだ生成していないものにリンクを張らない。
///
/// 秘密を読むテンプレートは --secrets を渡すまで飛ばされる。その状態で
/// 張ると、行き先の無いリンクが $HOME に残る。
#[test]
fn a_deferred_output_is_not_linked() {
    let r = Repo::new("deferred");
    r.manifest(
        r#"
[link]
common = ["secret.conf"]
ignore = ["*.tmpl"]

[render]
"secret.conf" = "secret.conf.tmpl"

[providers.never]
command = "false {}"
"#,
    );
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write("secret.conf.tmpl", "token = {{ never://a/b }}\n");

    let out = ok(&r.run(&["apply"]));
    assert!(out.contains("deferred"), "{out}");
    assert!(
        std::fs::symlink_metadata(r.home_path("secret.conf")).is_err(),
        "a link was made to a file that does not exist"
    );
    // 「最新です」とは言わない
    assert!(!out.contains("already up to date"), "{out}");
}

/// 他の OS 向けに括ってある秘密は、このマシンでは要らない。
#[test]
fn a_secret_behind_a_false_condition_does_not_defer() {
    let r = Repo::new("guarded-secret");
    r.manifest(
        r#"
[link]
common = ["gen.conf"]
ignore = ["*.tmpl"]

[render]
"gen.conf" = "gen.conf.tmpl"

[providers.never]
command = "false {}"
"#,
    );
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write(
        "gen.conf.tmpl",
        "x = {{ bg }}\n{{ if sennit.os == \"no-such-os\" }}t = {{ never://a/b }}\n{{ end }}",
    );

    let out = ok(&r.run(&["apply"]));
    assert!(!out.contains("deferred"), "{out}");
    assert_eq!(
        std::fs::read_to_string(r.home_path("gen.conf")).unwrap(),
        "x = zzz\n"
    );
}

/// リポジトリの外を指す宣言は、配置を始める前に断る。
#[test]
fn a_declaration_that_escapes_is_refused() {
    let r = Repo::new("escape");
    r.manifest("[link]\ncommon = [\"../outside\"]\n");
    let out = r.run(&["apply"]);
    assert!(!out.status.success());
    assert!(
        String::from_utf8_lossy(&out.stderr).contains(".."),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

/// 読めないディレクトリは失敗にする。黙って飛ばすと、その下のリンクが
/// 「宣言から外れた」ものとして $HOME から消える。
#[test]
fn an_unreadable_directory_fails_instead_of_pruning() {
    use std::os::unix::fs::PermissionsExt;
    // root では権限が効かないので飛ばす
    if euid() == 0 {
        return;
    }
    let r = Repo::new("unreadable");
    r.manifest("[link]\ncommon = [\"conf\"]\n");
    r.write("conf/a.conf", "a\n");
    r.write("conf/b.conf", "b\n");
    ok(&r.run(&["apply"]));

    std::fs::set_permissions(r.root_path("conf"), std::fs::Permissions::from_mode(0o000)).unwrap();
    let out = r.run(&["apply"]);
    std::fs::set_permissions(r.root_path("conf"), std::fs::Permissions::from_mode(0o755)).unwrap();

    assert!(!out.status.success(), "an unreadable directory should fail");
    // リンクは残っている
    assert!(std::fs::symlink_metadata(r.home_path("conf/a.conf")).is_ok());
    assert!(std::fs::symlink_metadata(r.home_path("conf/b.conf")).is_ok());
}

/// std に euid が無いので id -u で代用する。
fn euid() -> u32 {
    Command::new("id")
        .arg("-u")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .and_then(|s| s.trim().parse().ok())
        .unwrap_or(1000)
}

/// 読めなくなっただけのファイルを「消えた」と読まない。
///
/// Path::exists() は EACCES も false を返す。それを「宣言から外れた」と
/// 読むと、権限が変わっただけで $HOME のリンクが消える。
#[test]
fn an_unreadable_file_is_not_treated_as_removed() {
    use std::os::unix::fs::PermissionsExt;
    if euid() == 0 {
        return;
    }
    let r = Repo::new("unreadable-file");
    r.manifest("[link]\ncommon = [\"conf\"]\n");
    r.write("conf/sub/b.conf", "b\n");
    ok(&r.run(&["apply"]));

    // readdir は通るが stat が通らない状態にする
    std::fs::set_permissions(
        r.root_path("conf/sub"),
        std::fs::Permissions::from_mode(0o600),
    )
    .unwrap();
    let out = r.run(&["apply"]);
    std::fs::set_permissions(
        r.root_path("conf/sub"),
        std::fs::Permissions::from_mode(0o755),
    )
    .unwrap();

    assert!(
        !out.status.success(),
        "an unreadable file should be an error, not a prune: {}",
        String::from_utf8_lossy(&out.stdout)
    );
    assert!(
        std::fs::symlink_metadata(r.home_path("conf/sub/b.conf")).is_ok(),
        "the link was pruned"
    );
}

/// rollback は何度打っても同じ結果になる。
///
/// 古い退避を記録に残していた頃は、2 度目が今戻したファイルの上に
/// 古い方を書き、3 つあれば 2 つが消えた。
#[test]
fn rollback_is_idempotent() {
    let r = Repo::new("rollback-twice");
    r.manifest("[link]\ncommon = [\"a.conf\"]\n");
    r.write("a.conf", "repo\n");

    for body in ["FIRST\n", "SECOND\n", "THIRD\n"] {
        if r.home_path("a.conf").exists()
            || std::fs::symlink_metadata(r.home_path("a.conf")).is_ok()
        {
            std::fs::remove_file(r.home_path("a.conf")).unwrap();
        }
        r.write_home("a.conf", body);
        ok(&r.run(&["apply"]));
    }

    ok(&r.run(&["rollback"]));
    assert_eq!(
        std::fs::read_to_string(r.home_path("a.conf")).unwrap(),
        "THIRD\n"
    );
    let out = ok(&r.run(&["rollback"]));
    assert!(out.contains("nothing to roll back"), "{out}");
    assert_eq!(
        std::fs::read_to_string(r.home_path("a.conf")).unwrap(),
        "THIRD\n"
    );
    // 古い 2 つはファイルとして残っている
    let bodies: Vec<String> = std::fs::read_dir(&r.home)
        .unwrap()
        .filter_map(Result::ok)
        .filter_map(|e| std::fs::read_to_string(e.path()).ok())
        .collect();
    for want in ["FIRST\n", "SECOND\n"] {
        assert!(bodies.iter().any(|b| b == want), "{want:?} was destroyed");
    }
}

/// 生成物の置き場が symlink なら断る。リンクを辿って書くと、
/// リポジトリの外のファイルを黙って潰せる。
#[test]
fn a_generated_output_is_not_written_through_a_symlink() {
    let r = Repo::new("symlink-output");
    r.manifest(
        r#"
[link]
common = ["gen.conf"]
ignore = ["*.tmpl"]

[render]
"gen.conf" = "gen.conf.tmpl"
"#,
    );
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write("gen.conf.tmpl", "x = {{ bg }}\n");

    let victim = r.home.parent().unwrap().join("victim");
    std::fs::write(&victim, "PRECIOUS\n").unwrap();
    std::os::unix::fs::symlink(&victim, r.root_path("gen.conf")).unwrap();

    let out = r.run(&["apply"]);
    assert!(
        !out.status.success(),
        "writing through a symlink should fail"
    );
    assert_eq!(std::fs::read_to_string(&victim).unwrap(), "PRECIOUS\n");
}

/// --dry-run の 1 行ずつの予告が、本番と食い違わない。
#[test]
fn dry_run_previews_what_apply_will_link() {
    let r = Repo::new("dry-run-preview");
    r.manifest(
        r#"
[link]
common = ["a.conf", "gen.conf"]
ignore = ["*.tmpl"]

[render]
"gen.conf" = "gen.conf.tmpl"
"#,
    );
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write("a.conf", "plain\n");
    r.write("gen.conf.tmpl", "x = {{ bg }}\n");

    let preview = ok(&r.run(&["apply", "--dry-run"]));
    assert!(
        !preview.contains("not generated yet"),
        "dry-run said it cannot link a file it also said it would render:\n{preview}"
    );
    let real = ok(&r.run(&["apply"]));
    assert!(real.contains("2 link(s) updated"), "{real}");
}

/// 自分が入れなくなるモードをディレクトリに掛けない。
#[test]
fn a_directory_mode_that_locks_you_out_is_refused() {
    let r = Repo::new("dir-mode");
    r.manifest("[link]\ncommon = [\".ssh\"]\n\n[modes]\n\".ssh\" = \"600\"\n");
    r.write(".ssh/config", "Host x\n");

    let out = r.run(&["apply"]);
    assert!(
        !out.status.success(),
        "600 on a directory should be refused"
    );
    use std::os::unix::fs::PermissionsExt;
    assert_ne!(
        std::fs::metadata(r.root_path(".ssh"))
            .unwrap()
            .permissions()
            .mode()
            & 0o777,
        0o600
    );
}

/// rollback は、戻す先に居るファイルを潰さない。
///
/// apply のあとに利用者がそこへ書いたものは、退避の記録には無い。
/// その上に rename すると、退避を戻すコマンドが別のファイルを消す。
#[test]
fn rollback_does_not_destroy_what_is_at_the_destination() {
    let r = Repo::new("rollback-dest");
    r.manifest("[link]\ncommon = [\"a.conf\"]\n");
    r.write("a.conf", "repo\n");
    r.write_home("a.conf", "ORIGINAL\n");
    ok(&r.run(&["apply"]));

    // 利用者がリンクを外して自分で書いた
    std::fs::remove_file(r.home_path("a.conf")).unwrap();
    r.write_home("a.conf", "NEW WORK\n");

    ok(&r.run(&["rollback"]));
    assert_eq!(
        std::fs::read_to_string(r.home_path("a.conf")).unwrap(),
        "ORIGINAL\n"
    );
    let bodies: Vec<String> = std::fs::read_dir(&r.home)
        .unwrap()
        .filter_map(Result::ok)
        .filter_map(|e| std::fs::read_to_string(e.path()).ok())
        .collect();
    assert!(
        bodies.iter().any(|b| b == "NEW WORK\n"),
        "what was at the destination was destroyed: {bodies:?}"
    );
}

/// 退避を取った直後に落ちても、記録は残っている。
#[test]
fn a_backup_is_recorded_before_anything_else_can_fail() {
    let r = Repo::new("backup-early");
    // a.conf は退避され、そのあと zz/b.conf の配置が失敗する
    r.manifest("[link]\ncommon = [\"a.conf\", \"zz\"]\n");
    r.write("a.conf", "repo\n");
    r.write("zz/b.conf", "b\n");
    r.write_home("a.conf", "MINE\n");
    // $HOME/zz を実体のファイルにしておくと、その下に作れない
    r.write_home("zz", "not a directory\n");

    let out = r.run(&["apply"]);
    assert!(!out.status.success(), "apply should have failed");

    ok(&r.run(&["rollback"]));
    assert_eq!(
        std::fs::read_to_string(r.home_path("a.conf")).unwrap(),
        "MINE\n"
    );
}

/// 生成物の書き先がディレクトリなら、権限を触る前に断る。
#[test]
fn a_generated_output_is_not_written_over_a_directory() {
    let r = Repo::new("dir-output");
    r.manifest(
        r#"
[link]
common = ["gen.conf"]
ignore = ["*.tmpl"]

[render]
"gen.conf" = "gen.conf.tmpl"
"#,
    );
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write("gen.conf.tmpl", "x = {{ bg }}\n");
    std::fs::create_dir_all(r.root_path("gen.conf")).unwrap();
    std::fs::write(r.root_path("gen.conf/inner"), "inner\n").unwrap();

    let out = r.run(&["apply"]);
    assert!(!out.status.success());
    // 中身が読めなくなっていない
    assert_eq!(
        mode_of(&r.root_path("gen.conf")) & 0o700,
        0o700,
        "the directory was chmod-ed before the refusal"
    );
    assert!(r.root_path("gen.conf/inner").exists());
}

/// --no-backup は apply 経由でも、退避せずに消す。
#[test]
fn no_backup_replaces_without_keeping_a_copy() {
    let r = Repo::new("no-backup-apply");
    r.manifest("[link]\ncommon = [\"a.conf\"]\n");
    r.write("a.conf", "repo\n");
    r.write_home("a.conf", "MINE\n");

    let out = ok(&r.run(&["apply", "--no-backup"]));
    assert!(out.contains("replace"), "{out}");
    assert_eq!(
        std::fs::read_to_string(r.home_path("a.conf")).unwrap(),
        "repo\n"
    );
    let out = ok(&r.run(&["rollback"]));
    assert!(out.contains("nothing to roll back"), "{out}");
}

/// 宣言したモードが違えば verify が落ちる。
#[test]
fn verify_fails_on_a_wrong_mode() {
    use std::os::unix::fs::PermissionsExt;
    let r = Repo::new("verify-mode");
    r.manifest("[link]\ncommon = [\".npmrc\"]\n\n[modes]\n\".npmrc\" = \"600\"\n");
    r.write(".npmrc", "token\n");
    ok(&r.run(&["apply"]));

    std::fs::set_permissions(
        r.root_path(".npmrc"),
        std::fs::Permissions::from_mode(0o644),
    )
    .unwrap();
    let out = r.run(&["verify"]);
    assert!(!out.status.success(), "verify should fail on a wrong mode");
    assert!(
        String::from_utf8_lossy(&out.stdout).contains("declared 600"),
        "{}",
        String::from_utf8_lossy(&out.stdout)
    );
}

/// 暗号文を復号して置く。鍵が無ければ保留する。
#[test]
fn an_encrypted_file_is_decrypted_and_kept_private() {
    let r = Repo::new("encrypted");
    r.write("secret.age", "PLAINTEXT\n");
    // 復号コマンドは中身をそのまま出すだけのもので代用する
    r.manifest(
        r#"
[link]
common = ["secret"]
ignore = ["*.age"]

[encrypted]
"secret" = "secret.age"

[encryption]
command = "cat {}"
"#,
    );

    ok(&r.run(&["apply"]));
    assert_eq!(
        std::fs::read_to_string(r.home_path("secret")).unwrap(),
        "PLAINTEXT\n"
    );
    assert_eq!(mode_of(&r.root_path("secret")), 0o400);
}

/// 鍵が宣言されていて存在しないなら、失敗ではなく保留。
#[test]
fn an_encrypted_file_is_deferred_without_its_key() {
    let r = Repo::new("encrypted-nokey");
    r.write("secret.age", "PLAINTEXT\n");
    r.manifest(
        r#"
[link]
common = ["secret"]
ignore = ["*.age"]

[encrypted]
"secret" = "secret.age"

[encryption]
command = "cat {}"
identity = "/nonexistent/key.txt"
"#,
    );

    let out = ok(&r.run(&["apply"]));
    assert!(out.contains("no decryption key"), "{out}");
    assert!(std::fs::symlink_metadata(r.home_path("secret")).is_err());
}

/// --secrets を渡すとプロバイダが呼ばれ、結果は本人だけが読める。
#[test]
fn a_secret_is_fetched_with_secrets_and_written_private() {
    let r = Repo::new("secrets");
    r.manifest(
        r#"
[link]
common = ["conf"]
ignore = ["*.tmpl"]

[render]
"conf" = "conf.tmpl"

[providers.fake]
command = "echo {}"
"#,
    );
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write("conf.tmpl", "token = {{ fake://hello }}\n");

    ok(&r.run(&["apply", "--secrets"]));
    assert_eq!(
        std::fs::read_to_string(r.home_path("conf")).unwrap(),
        "token = hello\n"
    );
    assert_eq!(mode_of(&r.root_path("conf")), 0o400);
}

/// 宣言の無い scheme は、名指しで断る。
#[test]
fn an_undeclared_scheme_is_named() {
    let r = Repo::new("unknown-scheme");
    r.manifest(
        r#"
[link]
common = ["conf"]
ignore = ["*.tmpl"]

[render]
"conf" = "conf.tmpl"

[providers.fake]
command = "echo {}"
"#,
    );
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write("conf.tmpl", "token = {{ nosuch://x }}\n");

    let out = r.run(&["apply", "--secrets"]);
    assert!(!out.status.success());
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("nosuch"), "{err}");
    assert!(err.contains("fake"), "{err}");
}

/// フックが実際に走った回は「最新です」と言わない。
#[test]
fn apply_does_not_claim_nothing_happened_after_running_a_hook() {
    let r = Repo::new("hook-ran");
    r.manifest("[link]\ncommon = [\"a.conf\"]\n\n[hooks.always]\nrun = \"true\"\n");
    r.write("a.conf", "repo\n");
    ok(&r.run(&["apply"]));

    let out = ok(&r.run(&["apply"]));
    assert!(out.contains("hook"), "{out}");
    assert!(
        !out.contains("already up to date"),
        "a hook ran, so something happened:\n{out}"
    );
}

/// 締め出すモードは preview の時点で断る。
#[test]
fn dry_run_refuses_a_directory_mode_that_locks_you_out() {
    let r = Repo::new("dry-run-dir-mode");
    r.manifest("[link]\ncommon = [\".ssh\"]\n\n[modes]\n\".ssh\" = \"600\"\n");
    r.write(".ssh/config", "Host x\n");

    let out = r.run(&["apply", "--dry-run"]);
    assert!(
        !out.status.success(),
        "the preview should refuse what the real apply refuses"
    );
}

/// 途中のディレクトリが symlink でも、リポジトリの外へは書かない。
///
/// symlink_metadata が見るのは最後の 1 要素だけ。`out -> /outside` を
/// 置くだけで、宣言の検査を回り込んで外のファイルを潰せていた。
#[test]
fn a_generated_output_cannot_escape_through_a_symlinked_parent() {
    let r = Repo::new("symlink-parent");
    let outside = r.home.parent().unwrap().join("outside");
    std::fs::create_dir_all(&outside).unwrap();
    std::fs::write(outside.join("gen.conf"), "PRECIOUS\n").unwrap();

    r.manifest(
        r#"
[link]
common = ["out"]
ignore = ["*.tmpl"]

[render]
"out/gen.conf" = "gen.conf.tmpl"
"#,
    );
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write("gen.conf.tmpl", "x = {{ bg }}\n");
    std::os::unix::fs::symlink(&outside, r.root_path("out")).unwrap();

    let out = r.run(&["apply"]);
    assert!(
        !out.status.success(),
        "writing outside the repo should fail"
    );
    assert_eq!(
        std::fs::read_to_string(outside.join("gen.conf")).unwrap(),
        "PRECIOUS\n"
    );
}

/// ディレクトリから所有者の読みを落とすモードも断る。
#[test]
fn a_directory_mode_without_read_is_refused() {
    let r = Repo::new("dir-mode-read");
    r.manifest("[link]\ncommon = [\".ssh\"]\n\n[modes]\n\".ssh\" = \"300\"\n");
    r.write(".ssh/config", "Host x\n");

    let out = r.run(&["apply"]);
    assert!(
        !out.status.success(),
        "300 on a directory should be refused"
    );
    // 掛かっていない
    assert_ne!(mode_of(&r.root_path(".ssh")) & 0o500, 0);
}

/// モードで落ちても、張ったリンクは記録に残る。
///
/// 記録が無いと、次の apply はそのリンクを知らないので prune もできず、
/// 宣言から外しても $HOME に残り続ける。
#[test]
fn links_are_recorded_even_if_a_later_step_fails() {
    let r = Repo::new("record-before-modes");
    r.manifest("[link]\ncommon = [\"a.conf\", \".ssh\"]\n\n[modes]\n\".ssh\" = \"600\"\n");
    r.write("a.conf", "repo\n");
    r.write(".ssh/config", "Host x\n");

    let out = r.run(&["apply"]);
    assert!(!out.status.success());
    assert!(std::fs::symlink_metadata(r.home_path("a.conf")).is_ok());

    // 宣言から外せば prune できる = 記録されていた
    r.manifest("[link]\ncommon = []\n");
    let out = ok(&r.run(&["apply"]));
    assert!(out.contains("prune"), "the link was never recorded:\n{out}");
    assert!(std::fs::symlink_metadata(r.home_path("a.conf")).is_err());
}

/// 読めない宣言パスを verify が「問題なし」と言わない。
///
/// apply は同じ宣言について「stat できない」で落ちる。片方が拒み、
/// 片方が承認するなら、宣言した制限は誰にも適用されないまま通る。
#[test]
fn verify_does_not_approve_a_mode_it_could_not_read() {
    use std::os::unix::fs::PermissionsExt;
    if euid() == 0 {
        return;
    }
    let r = Repo::new("verify-unreadable");
    r.manifest("[link]\ncommon = []\n\n[modes]\n\"scripts/tool\" = \"600\"\n");
    r.write("scripts/tool", "#!/bin/sh\n");

    std::fs::set_permissions(
        r.root_path("scripts"),
        std::fs::Permissions::from_mode(0o600),
    )
    .unwrap();
    let out = r.run(&["verify"]);
    std::fs::set_permissions(
        r.root_path("scripts"),
        std::fs::Permissions::from_mode(0o755),
    )
    .unwrap();

    assert!(
        !out.status.success(),
        "verify approved a mode it could not read:\n{}",
        String::from_utf8_lossy(&out.stdout)
    );
}

/// 配置の途中で落ちても、そこまでに張ったリンクは記録される。
///
/// 記録されないと、次の apply はそのリンクを知らない。宣言から外しても
/// prune の対象にならず、誰も管理していないリンクが $HOME に残る。
#[test]
fn a_link_placed_before_a_failure_is_still_recorded() {
    let r = Repo::new("record-midloop");
    // a.conf は張れるが、そのあと zz/ を作るところで落ちる
    r.manifest("[link]\ncommon = [\"a.conf\", \"zz\"]\n");
    r.write("a.conf", "repo\n");
    r.write("zz/b.conf", "b\n");
    r.write_home("zz", "a file, not a directory\n");

    let out = r.run(&["apply"]);
    assert!(!out.status.success());
    assert!(std::fs::symlink_metadata(r.home_path("a.conf")).is_ok());

    // 宣言から外せば prune できる = 記録されていた
    r.manifest("[link]\ncommon = []\n");
    let out = ok(&r.run(&["apply"]));
    assert!(out.contains("prune"), "the link was never recorded:\n{out}");
    assert!(std::fs::symlink_metadata(r.home_path("a.conf")).is_err());
}

/// 退避が消えているなら「戻した」と言わない。
#[test]
fn rollback_does_not_claim_to_restore_a_backup_that_is_gone() {
    let r = Repo::new("rollback-gone");
    r.manifest("[link]\ncommon = [\"a.conf\"]\n");
    r.write("a.conf", "repo\n");
    r.write_home("a.conf", "MINE\n");
    ok(&r.run(&["apply"]));

    // 利用者が .sennit-backup を掃除した
    std::fs::remove_file(r.home_path("a.conf.sennit-backup")).unwrap();

    let out = ok(&r.run(&["rollback", "--dry-run"]));
    assert!(!out.contains("1 file(s) would be restored"), "{out}");
    let out = ok(&r.run(&["rollback"]));
    assert!(!out.contains("1 file(s) restored"), "{out}");
    assert!(
        out.contains("already gone") || out.contains("nothing to put back"),
        "{out}"
    );
}

/// ignore の前方一致は要素単位。名前の頭が同じだけの別のディレクトリを
/// 巻き込むと、そこは配置されず、次の apply が「宣言から外れた」と読んで
/// $HOME から消す。
#[test]
fn ignore_does_not_swallow_a_sibling_with_a_shared_name_prefix() {
    let r = Repo::new("ignore-sibling");
    r.manifest("[link]\ncommon = [\"conf\"]\nignore = [\"conf/nvim\"]\n");
    r.write("conf/nvim/init.lua", "-- ignored\n");
    r.write("conf/nvim-extra/x.lua", "-- kept\n");

    ok(&r.run(&["apply"]));
    assert!(
        std::fs::symlink_metadata(r.home_path("conf/nvim-extra/x.lua")).is_ok(),
        "a sibling sharing the prefix was ignored"
    );
    assert!(std::fs::symlink_metadata(r.home_path("conf/nvim/init.lua")).is_err());

    // 2 回目で消されない
    ok(&r.run(&["apply"]));
    assert!(std::fs::symlink_metadata(r.home_path("conf/nvim-extra/x.lua")).is_ok());
}

/// --dry-run はプロバイダも復号コマンドも呼ばない。
///
/// どちらも人にロック解除を求めたり、任意のコマンドを走らせたりする。
/// 「何も起きない」と言ったコマンドがそれを出すのは筋が通らない。
#[test]
fn dry_run_calls_neither_a_provider_nor_a_decryption_command() {
    let r = Repo::new("dry-run-no-exec");
    // 呼ばれたら痕跡が残るコマンドにする
    let marker = r.home.parent().unwrap().join("called");
    r.manifest(&format!(
        r#"
[link]
common = ["gen.conf", "secret"]
ignore = ["*.tmpl", "*.age"]

[render]
"gen.conf" = "gen.conf.tmpl"

[encrypted]
"secret" = "secret.age"

[encryption]
command = "sh -c 'echo decrypt >> {m}; cat' {{}}"

[providers.fake]
command = "sh -c 'echo provider >> {m}; echo v'"
"#,
        m = marker.display()
    ));
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write("gen.conf.tmpl", "t = {{ fake://a }}\n");
    r.write("secret.age", "PLAIN\n");

    ok(&r.run(&["apply", "--dry-run", "--secrets"]));
    assert!(
        !marker.exists(),
        "--dry-run ran: {}",
        std::fs::read_to_string(&marker).unwrap_or_default()
    );
}

/// [link] の対象が重なっていても、同じパスを二度張ろうとしない。
#[test]
fn overlapping_link_targets_do_not_break_the_first_apply() {
    let r = Repo::new("overlap");
    r.manifest("[link]\ncommon = [\"conf\", \"conf/nvim\"]\n");
    r.write("conf/nvim/init.lua", "-- x\n");
    r.write("conf/zzz.conf", "z\n");

    let out = ok(&r.run(&["apply"]));
    assert!(out.contains("2 link(s) updated"), "{out}");
    assert!(std::fs::symlink_metadata(r.home_path("conf/nvim/init.lua")).is_ok());
    assert!(std::fs::symlink_metadata(r.home_path("conf/zzz.conf")).is_ok());
}

/// 宣言したモードのパスが symlink なら、リンク先を触らずに断る。
#[test]
fn a_declared_mode_does_not_follow_a_symlink_out_of_the_repository() {
    use std::os::unix::fs::PermissionsExt;
    let r = Repo::new("mode-symlink");
    let outside = r.home.parent().unwrap().join("secret");
    std::fs::write(&outside, "key\n").unwrap();
    std::fs::set_permissions(&outside, std::fs::Permissions::from_mode(0o600)).unwrap();

    r.manifest("[link]\ncommon = []\n\n[modes]\n\"keylink\" = \"644\"\n");
    std::os::unix::fs::symlink(&outside, r.root_path("keylink")).unwrap();

    let out = r.run(&["apply"]);
    assert!(
        !out.status.success(),
        "a symlinked mode target should be refused"
    );
    assert_eq!(mode_of(&outside), 0o600, "the link target was chmod-ed");
}

/// 読めなくなった「親」を、宣言から外れたものとして扱わない。
///
/// 対象そのものではなくその上のディレクトリが読めなくなる場合、対象の
/// stat は通るので、対象を狭めるテストでは捕まらない。
#[test]
fn an_unreadable_ancestor_does_not_prune() {
    use std::os::unix::fs::PermissionsExt;
    if euid() == 0 {
        return;
    }
    let r = Repo::new("unreadable-ancestor");
    r.manifest("[link]\ncommon = [\"conf/nvim\"]\n");
    r.write("conf/nvim/init.lua", "-- x\n");
    ok(&r.run(&["apply"]));

    std::fs::set_permissions(r.root_path("conf"), std::fs::Permissions::from_mode(0o000)).unwrap();
    let out = r.run(&["apply"]);
    std::fs::set_permissions(r.root_path("conf"), std::fs::Permissions::from_mode(0o755)).unwrap();

    assert!(
        !out.status.success(),
        "an unreadable ancestor should be an error, not a prune:\n{}",
        String::from_utf8_lossy(&out.stdout)
    );
    assert!(
        std::fs::symlink_metadata(r.home_path("conf/nvim/init.lua")).is_ok(),
        "the link was pruned"
    );
}

/// 宣言したモードは、途中のディレクトリが symlink でもリポジトリの外へ
/// 出ない。最後の 1 要素だけ見ていた頃は素通りしていた。
#[test]
fn a_declared_mode_cannot_escape_through_a_symlinked_parent() {
    use std::os::unix::fs::PermissionsExt;
    let r = Repo::new("mode-symlink-parent");
    let outside = r.home.parent().unwrap().join("outside");
    std::fs::create_dir_all(&outside).unwrap();
    let victim = outside.join("victim");
    std::fs::write(&victim, "key\n").unwrap();
    std::fs::set_permissions(&victim, std::fs::Permissions::from_mode(0o600)).unwrap();

    r.manifest("[link]\ncommon = []\n\n[modes]\n\"out/victim\" = \"777\"\n");
    std::os::unix::fs::symlink(&outside, r.root_path("out")).unwrap();

    let out = r.run(&["apply"]);
    assert!(
        !out.status.success(),
        "should refuse to chmod outside the repo"
    );
    assert_eq!(mode_of(&victim), 0o600, "the file outside was chmod-ed");
}

/// コメントアウトした設定を、生きている宣言として読まない。
#[test]
fn commented_out_settings_are_not_requirements() {
    let r = Repo::new("comments");
    r.manifest("[link]\ncommon = []\n");
    std::fs::write(r.root_path("packages.toml"), "[packages]\n").unwrap();
    r.write(
        ".config/alacritty/alacritty.toml",
        "[font.normal]\n# family = \"JetBrains Mono\"\nfamily = \"Hack Nerd Font Mono\"\n",
    );
    r.write(
        ".config/zed/settings.json",
        "{\n  // \"buffer_font_family\": \"Zed Plex Mono\",\n  \"auto_install_extensions\": {\n    // \"html\": true,\n    \"toml\": true,\n  },\n}\n",
    );

    let out = r.run(&["check"]);
    let text = String::from_utf8_lossy(&out.stdout);
    for phantom in ["JetBrains Mono", "Zed Plex Mono", "html"] {
        assert!(
            !text.contains(phantom),
            "{phantom} came from a comment:\n{text}"
        );
    }
    // 生きている宣言は拾えている
    assert!(text.contains("Hack Nerd Font Mono"), "{text}");
    assert!(text.contains("toml"), "{text}");
}

/// まだ生成されていない出力にモードを宣言していても、apply は落ちない。
///
/// 秘密を読むテンプレートは --secrets を渡すまで生成されないので、初回や
/// CI では親ディレクトリごと存在しない。これを異常扱いにすると、その状態が
/// 常態であるコンテナで一度も apply が通らなくなる。
#[test]
fn a_declared_mode_on_a_deferred_output_does_not_fail_the_run() {
    let r = Repo::new("mode-deferred");
    r.manifest(
        r#"
[link]
common = ["a.conf", "gh"]
ignore = ["*.tmpl"]

[render]
"gh/hosts.yml" = "hosts.yml.tmpl"

[modes]
"gh/hosts.yml" = "600"

[providers.never]
command = "false {}"
"#,
    );
    r.write("theme.toml", "bg = \"zzz\"\n");
    r.write("a.conf", "plain\n");
    r.write("hosts.yml.tmpl", "token = {{ never://a/b }}\n");

    let preview = ok(&r.run(&["apply", "--dry-run"]));
    assert!(preview.contains("nothing written"), "{preview}");

    let out = ok(&r.run(&["apply"]));
    assert!(out.contains("link(s) updated"), "{out}");
    assert!(std::fs::symlink_metadata(r.home_path("a.conf")).is_ok());
}