verctl-core 0.9.6

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
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
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
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
use indoc::{formatdoc, indoc};

use super::*;
use crate::asset_rules;

/// A whole config, so what is under test is what a repo actually writes.
fn load(body: &str) -> Result<Config> {
    Config::parse(body)
}

/// The one package every fixture below needs, and nothing else.
const PACKAGE: &str = indoc! {"
    packages:
      - name: demo
        path: Cargo.toml
"};

/// `publisher: none` uploads nothing, so a registry or an upload command
/// beside it fails the load instead of being ignored.
#[test]
fn a_release_only_package_names_no_registry() {
    let config = load(indoc! {"
        packages:
          - name: demo
            path: Cargo.toml
            publisher: none
    "})
    .unwrap();
    assert_eq!(config.packages[0].publisher.as_deref(), Some("none"));
    let error = load(&formatdoc! {r#"
        {PACKAGE}
        publishers:
          none:
            argv: ["true"]
    "#})
    .expect_err("publishers.none is reserved");
    assert!(
        format!("{error:#}").contains("publishers.none is reserved"),
        "{error:#}"
    );
    for extra in ["registry: crates-io", "publish: [cargo, publish]"] {
        let error = load(&formatdoc! {"
            packages:
              - name: demo
                path: Cargo.toml
                publisher: none
                {extra}
        "})
        .expect_err(extra);
        assert!(
            format!("{error:#}").contains("has publisher: none"),
            "{extra}: {error:#}"
        );
    }
}

/// `packslip` is a mapping of `manifest`, `attest` and `pubkey`, and the
/// path form it replaced fails with the mapping to write.
#[test]
fn packslip_is_a_mapping_and_the_path_form_shows_it() {
    let with = |packslip: &str| {
        load(&formatdoc! {"
            {PACKAGE}
            assets:
              linux-x64: {{}}
            packslip: {packslip}
        "})
    };
    let both = with("{ manifest: .ctl/packslip.toml, attest: link }").unwrap();
    let both = both.packslip.expect("packslip");
    assert_eq!(
        both.manifest.as_deref(),
        Some(Path::new(".ctl/packslip.toml"))
    );
    assert_eq!(both.attest, Attest::Link);
    let off = with("{ attest: false }")
        .unwrap()
        .packslip
        .expect("packslip");
    assert_eq!((off.manifest, off.attest), (None, Attest::False));
    let empty = with("{}").unwrap().packslip.expect("packslip");
    assert_eq!(
        (empty.manifest, empty.attest, empty.pubkey),
        (None, Attest::True, None)
    );
    let keyed = with("{ pubkey: RWQexample }")
        .unwrap()
        .packslip
        .expect("packslip");
    assert_eq!(keyed.pubkey.as_deref(), Some("RWQexample"));
    let report = format!("{:#}", with(".ctl/packslip.toml").expect_err("path form"));
    assert!(
        report.contains("packslip: { manifest: .ctl/packslip.toml }"),
        "{report}"
    );
}

/// A `pubkey` with no text in it fails the load, naming the field.
#[test]
fn a_blank_pubkey_fails_the_load() {
    for blank in ["''", "'  '"] {
        let error = load(&formatdoc! {"
            {PACKAGE}
            assets:
              linux-x64: {{}}
            packslip: {{ pubkey: {blank} }}
        "})
        .expect_err(blank);
        let report = format!("{error:#}");
        assert!(report.contains("packslip.pubkey"), "{blank}: {report}");
        assert!(report.contains("cannot be empty"), "{blank}: {report}");
    }
}

/// An `attest` that is not `true`, `link`, or `false` names the field and
/// the three values.
#[test]
fn an_unknown_attest_mode_names_the_three_values() {
    let error = load(&formatdoc! {"
        {PACKAGE}
        assets:
          linux-x64: {{}}
        packslip: {{ attest: maybe }}
    "})
    .expect_err("maybe is no mode");
    let report = format!("{error:#}");
    assert!(report.contains("packslip.attest"), "{report}");
    assert!(report.contains("true, link, or false"), "{report}");
}

/// A target's `packslip` table is kept as written, and renders as TOML.
#[test]
fn a_target_packslip_table_is_kept_unread() {
    let config = load(&formatdoc! {r#"
        {PACKAGE}
        assets:
          darwin-arm64:
            packslip:
              requires: {{ os_min: "11.0" }}
    "#})
    .unwrap();
    let table = config.assets.expect("assets").targets["darwin-arm64"]
        .packslip
        .clone();
    assert_eq!(table.to_string(), "requires = { os_min = \"11.0\" }\n");
}

/// A target that sets no `packslip` has an empty table.
#[test]
fn a_target_without_a_packslip_table_has_an_empty_one() {
    let config = load(&formatdoc! {"
        {PACKAGE}
        assets:
          linux-x64: {{}}
    "})
    .unwrap();
    let table = &config.assets.expect("assets").targets["linux-x64"].packslip;
    assert_eq!(table.entries().count(), 0);
}

/// The tarball's `path` is verctl's to write, and TOML has no null.
#[test]
fn a_target_packslip_table_refuses_a_path_and_a_null() {
    for (key, said) in [
        ("path: elsewhere.tar.gz", "packslip.path"),
        ("requires: ~", "null has no TOML form"),
    ] {
        let error = load(&formatdoc! {"
            {PACKAGE}
            assets:
              darwin-arm64:
                packslip:
                  {key}
        "})
        .expect_err(key);
        let report = format!("{error:#}");
        assert!(report.contains(said), "{key}: {report}");
    }
}

/// A candidate tag is lowercase letters. Another spelling fails the load,
/// naming the package and the field.
#[test]
fn a_prerelease_is_lowercase_letters() {
    for tag in ["rc", "alpha", "beta", "next", "canary"] {
        let config = load(&formatdoc! {"
            packages:
              - name: demo
                path: Cargo.toml
                prerelease: {tag}
        "})
        .expect(tag);
        let spec = config.find("demo").expect("demo");
        assert_eq!(spec.prerelease.as_ref().map(Prerelease::as_str), Some(tag));
    }
    for tag in ["rc1", "RC", "rc.1", "1", "x", "latest", r#""""#] {
        let error = load(&formatdoc! {"
            packages:
              - name: demo
                path: Cargo.toml
                prerelease: {tag}
        "})
        .expect_err(tag);
        let message = format!("{error:#}");
        assert!(
            message.contains(r#"package "demo" has prerelease"#)
                && message.contains("lowercase ASCII letters"),
            "{tag}: {message}"
        );
    }
}

/// `marker: true` already marks where the version is. A driver beside it
/// fails the load instead of being ignored. `after` still applies.
#[test]
fn a_marker_names_no_driver() {
    for extra in [
        "driver: cargo",
        "format: toml",
        "keys: [project.version]",
        "read: [cat]",
        "write: [cat]",
    ] {
        let error = load(&formatdoc! {"
            packages:
              - name: ci
                path: ci.yml
                marker: true
                {extra}
        "})
        .expect_err(extra);
        assert!(
            format!("{error:#}").contains("has marker: true"),
            "{extra}: {error:#}"
        );
    }
    load(indoc! {"
        packages:
          - name: ci
            path: ci.yml
            marker: true
            after: mise run render
    "})
    .expect("after runs beside a marker");
}

/// No stock recipe uploads to the Python Package Index, so a Python
/// package names its publisher, or `none`, before anything is released.
#[test]
fn a_python_package_names_its_publisher() {
    let error = load(indoc! {"
        packages:
          - name: demo
            path: pyproject.toml
    "})
    .expect_err("no publisher");
    assert!(
        format!("{error:#}").contains("needs a publisher"),
        "{error:#}"
    );
    for named in [
        "publisher: none",
        "publish: [uv, publish]",
        "publisher: pypi",
    ] {
        load(&formatdoc! {"
            packages:
              - name: demo
                path: pyproject.toml
                {named}
            publishers:
              pypi:
                argv: [uv, publish]
        "})
        .unwrap_or_else(|error| panic!("{named}: {error:#}"));
    }
    load(indoc! {"
        packages:
          - name: demo
            path: pyproject.toml
        publishers:
          demo:
            argv: [uv, publish]
    "})
    .expect("a publishers entry under the package name");
}

/// A `path` is relative to the repository, not to the directory the
/// declarations happen to sit in, so `.ctl` never lands in front of it.
#[test]
fn the_root_is_the_directory_holding_the_ctl_dir() {
    let cases = [
        (".ctl/ver.yaml", "."),
        ("crates/foo/.ctl/ver.yaml", "crates/foo"),
        ("/srv/repo/.ctl/ver.yaml", "/srv/repo"),
        ("ver.yaml", "."),
        ("/tmp/scratch/ver.yaml", "/tmp/scratch"),
    ];
    for (config, expected) in cases {
        assert_eq!(root_of(Path::new(config)), Path::new(expected), "{config}");
    }
}

/// Every arity a repo can write, in the spelling it writes it.
#[test]
fn every_occurrence_form_parses_and_means_what_it_says() {
    let config = load(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/fixtures/config/occurrences.yaml"
    )))
    .unwrap();
    let allowed: Vec<Vec<usize>> = config.pins[0]
        .patterns
        .iter()
        .map(|pattern| (0..4).filter(|n| pattern.occurrences.allows(*n)).collect())
        .collect();
    assert_eq!(
        allowed,
        [
            vec![1],       // omitted: exactly once
            vec![1],       // once
            vec![1, 2, 3], // many
            vec![0],       // never
            vec![2],       // exactly 2
            vec![2, 3],    // at least 2
        ]
    );
}

/// A section verctl does not know is a typo. A typo that loads is a
/// release that does none of what the section was meant to do.
#[test]
fn a_misspelled_section_stops_the_load() {
    let error = load(&formatdoc! {r#"
        {PACKAGE}
        pattern:
          install:
            match: "demo@{{version}} --"
    "#})
    .expect_err("pattern is not a section");
    assert!(format!("{error:#}").contains("pattern"), "{error:#}");
}

/// A bound is one key and its number. A second key means the arity was
/// mistyped, and falling through to whichever variant the first key
/// satisfies would pin a count nobody wrote.
#[test]
fn a_bound_with_a_second_key_is_not_the_bound_it_starts_with() {
    let error = load(&formatdoc! {r#"
        {PACKAGE}
        patterns:
          wrong:
            match: "a@{{version}} --"
            occurrences: {{exactly: 2, at_leats: 3}}

        pins:
          - file: README.md
            package: demo
            patterns: [wrong]
    "#})
    .expect_err("at_leats is not a key");
    assert!(format!("{error:#}").contains(ARITY), "{error:#}");
}

/// A count that is not a whole number is the same mistake as a wrong
/// key. It is reported in the same words instead of serde's.
#[test]
fn a_bound_with_a_bad_count_names_the_arity() {
    for count in ["-1", "many"] {
        let error = load(&formatdoc! {r#"
            {PACKAGE}
            patterns:
              wrong:
                match: "a@{{version}} --"
                occurrences: {{exactly: {count}}}

            pins:
              - file: README.md
                package: demo
                patterns: [wrong]
        "#})
        .expect_err("the count is not a whole number");
        assert!(format!("{error:#}").contains(ARITY), "{count}: {error:#}");
    }
}

#[test]
fn an_unknown_arity_is_not_silently_a_default() {
    let broken = load(&formatdoc! {r#"
        {PACKAGE}
        patterns:
          wrong:
            match: "a@{{version}} --"
            occurrences: sometimes

        pins:
          - file: README.md
            package: demo
            patterns: [wrong]
    "#});
    let _ = broken.expect_err("unknown occurrences");
}

/// One spelling, named once, carried by two files: what ids are for.
#[test]
fn one_named_pattern_serves_every_file_that_lists_it() {
    let config = load(&formatdoc! {r#"
        {PACKAGE}
        patterns:
          install:
            match: "demo@{{version}} --"
          mention:
            match: "v{{version}} --"
            occurrences: many

        pins:
          - file: README.md
            package: demo
            patterns: [install, mention]
          - file: docs/install.md
            package: demo
            patterns: [install]
    "#})
    .unwrap();
    let carried: Vec<Vec<&str>> = config
        .pins
        .iter()
        .map(|pin| {
            pin.patterns
                .iter()
                .map(|pattern| pattern.r#match.as_str())
                .collect()
        })
        .collect();
    assert_eq!(
        carried,
        [
            vec!["demo@{version} --", "v{version} --"],
            vec!["demo@{version} --"]
        ],
        "each file carries the patterns it lists, in the order it lists them"
    );
}

/// Each side of `{version}` needs text a version cannot contain, or the
/// line under `whole_line`. Every refusal names the pattern and the side.
#[test]
fn a_pattern_marks_where_the_version_starts_and_ends() {
    let only = "contains only digits, '.', '-', and '+'";
    let cases = [
        ("name-{version}.tar.gz", false, None),
        ("download/v{version}-linux", false, None),
        ("v{version}.tar", false, None),
        ("demo@{version} --", false, None),
        ("`demo@{version}`", false, None),
        ("verctl-{version}", true, None),
        ("version: {version}", true, None),
        ("{version}", true, None),
        (
            "{version}",
            false,
            Some("nothing before {version}".to_owned()),
        ),
        (
            "verctl-{version}",
            false,
            Some("nothing after {version}".to_owned()),
        ),
        (
            "version: {version}",
            false,
            Some("skill: nothing after {version}".to_owned()),
        ),
        (
            "verctl@{version}.",
            false,
            Some(format!(r#""." after {{version}} {only}"#)),
        ),
        (
            "v{version}-",
            false,
            Some(format!(r#""-" after {{version}} {only}"#)),
        ),
        (
            "v{version}+",
            false,
            Some(format!(r#""+" after {{version}} {only}"#)),
        ),
        (
            "-{version}",
            false,
            Some(format!(r#""-" before {{version}} {only}"#)),
        ),
        (
            "{version}.1",
            false,
            Some("nothing before {version}".to_owned()),
        ),
        (
            "{version}.1",
            true,
            Some(format!(r#"".1" after {{version}} {only}"#)),
        ),
        (
            "version: {version}-",
            true,
            Some(format!(r#""-" after {{version}} {only}"#)),
        ),
    ];
    assert_bounds(cases);
}

/// A digit, or a `.` and a digit, next to `{version}` lets a longer version
/// match in part, whatever the rest of the literal contains.
#[test]
fn a_digit_next_to_the_version_leaves_the_side_open() {
    let near = "puts a digit, or a '.' and a digit, next to the version";
    assert_bounds([
        ("v{version}.tar", false, None),
        ("v{version}-1x", false, None),
        (
            "v{version}.5x",
            false,
            Some(format!(r#"".5x" after {{version}} {near}"#)),
        ),
        (
            "v{version}1x",
            false,
            Some(format!(r#""1x" after {{version}} {near}"#)),
        ),
        (
            "x1.{version}-linux",
            false,
            Some(format!(r#""x1." before {{version}} {near}"#)),
        ),
        (
            "x1{version}-linux",
            false,
            Some(format!(r#""x1" before {{version}} {near}"#)),
        ),
        (
            "{version}.1x",
            true,
            Some(format!(r#"".1x" after {{version}} {near}"#)),
        ),
    ]);
}

/// Loads one `skill` pattern per case and checks that it loads, or that
/// the refusal names the needle.
fn assert_bounds<const N: usize>(cases: [(&str, bool, Option<String>); N]) {
    for (text, whole_line, refusal) in cases {
        let loaded = load(&formatdoc! {"
            {PACKAGE}
            patterns:
              skill:
                match: '{text}'
                whole_line: {whole_line}

            pins:
              - file: README.md
                package: demo
                patterns: [skill]
        "});
        match (loaded, refusal) {
            (Ok(_), None) => {}
            (Err(error), Some(needle)) => {
                let report = format!("{error:#}");
                assert!(report.contains(needle.as_str()), "{text}: {report}");
            }
            (outcome, _) => panic!("{text} (whole_line: {whole_line}): {outcome:?}"),
        }
    }
}

/// Every rule the schema declares, each naming what a repo has to fix.
#[test]
#[expect(
    clippy::too_many_lines,
    reason = "one case per rule; a table, not logic"
)]
fn a_config_that_breaks_a_rule_stops_the_load() {
    let cases = [
        (
            "an id no patterns section declares",
            formatdoc! {r#"
                {PACKAGE}
                patterns:
                  install:
                    match: "demo@{{version}} --"

                pins:
                  - file: README.md
                    package: demo
                    patterns: [install, instal]
            "#},
            "pins[0].pattern_ids: no patterns.instal",
        ),
        (
            "the same id listed twice",
            formatdoc! {r#"
                {PACKAGE}
                patterns:
                  install:
                    match: "demo@{{version}} --"

                pins:
                  - file: README.md
                    package: demo
                    patterns: [install, install]
            "#},
            r#"pins[0].pattern_ids: lists "install" twice"#,
        ),
        (
            "a pattern no pin lists",
            formatdoc! {r#"
                {PACKAGE}
                patterns:
                  install:
                    match: "demo@{{version}} --"
                  orphan:
                    match: "old@{{version}} --"

                pins:
                  - file: README.md
                    package: demo
                    patterns: [install]
            "#},
            r#"patterns: "orphan" is declared and no pin lists it"#,
        ),
        (
            "a pin with nothing to rewrite",
            formatdoc! {"
                {PACKAGE}
                pins:
                  - file: README.md
                    package: demo
            "},
            "pins[0].pattern_ids: needs a tool or a pattern to rewrite",
        ),
        (
            "a spelling with nowhere to put the version",
            formatdoc! {r#"
                {PACKAGE}
                patterns:
                  install:
                    match: "demo@1.2.3"

                pins:
                  - file: README.md
                    package: demo
                    patterns: [install]
            "#},
            "patterns: install: match says {version} 0 times",
        ),
        (
            "a pin reaching out of the repository",
            formatdoc! {r#"
                {PACKAGE}
                patterns:
                  install:
                    match: "demo@{{version}} --"

                pins:
                  - file: ../elsewhere/README.md
                    package: demo
                    patterns: [install]
            "#},
            "pins[0].file: must stay inside the repository",
        ),
        (
            "a machine no label can find",
            formatdoc! {"
                {PACKAGE}
                runners:
                  ghost:
                    labels: []
            "},
            "runners.ghost.labels: must declare at least one label",
        ),
        (
            "a suffix that makes every file a template",
            formatdoc! {r#"
                {PACKAGE}
                templates:
                  suffix: ""
            "#},
            "templates.suffix: cannot be empty — it is what marks a file",
        ),
        (
            "a tag template naming a placeholder that does not exist",
            formatdoc! {r#"
                {PACKAGE}
                tags:
                  template: "v{{ver}}"
            "#},
            "tags.template: names {ver}, and the only placeholders are {version} and {name}",
        ),
        (
            "a tag template with no placeholder",
            formatdoc! {r#"
                {PACKAGE}
                tags:
                  template: "latest"
            "#},
            "tags.template: has no placeholder",
        ),
        (
            "a tag template with only the package name",
            formatdoc! {r#"
                {PACKAGE}
                tags:
                  template: "{{name}}"
            "#},
            "tags.template: must say {version}",
        ),
        (
            "an empty tag template",
            formatdoc! {r#"
                {PACKAGE}
                tags:
                  template: ""
            "#},
            "tags.template: cannot be empty",
        ),
        (
            "a tag template with a leftover brace",
            formatdoc! {r#"
                {PACKAGE}
                tags:
                  template: "v{{version}}}}"
            "#},
            "tags.template: has a '{' or '}' that is not {version} or {name}",
        ),
    ];
    for (scenario, body, expected) in cases {
        let error = load(&body).expect_err(scenario);
        assert!(
            format!("{error:#}").contains(expected),
            "{scenario}: {error:#}"
        );
    }
}

/// A vendored set with every required key over one declared machine and
/// no package, plus `extra` as one more key of the set.
fn vendored(extra: &str) -> String {
    formatdoc! {"
        runners:
          linux:
            labels: [ubuntu-26.04]
        vendored:
          lib:
            version: 1.4.0
            dir: out
            files: [lib]
            targets:
              linux-x64:
                runner: linux
            {extra}
    "}
}

#[test]
fn a_vendored_set_alone_is_a_config_and_takes_the_default_names() {
    let config = load(&vendored("")).unwrap();
    assert!(config.packages.is_empty());
    let set = &config.vendored["lib"];
    assert_eq!(set.tag, "{name}-{version}");
    assert_eq!(set.archive, "{name}-{version}-{id}.tar.gz");
    assert_eq!(set.build, Vec::<String>::new());
    assert_eq!(set.notes, None);
}

#[test]
fn a_config_with_no_package_and_no_vendored_set_fails() {
    let error = load("runners: {}\n").unwrap_err();
    assert!(
        format!("{error:#}").contains("must declare at least one package, or a vendored set"),
        "{error:#}"
    );
}

#[test]
fn a_vendored_set_without_targets_fails() {
    let error = load(indoc! {"
        vendored:
          lib:
            version: 1.4.0
            dir: out
            files: [lib]
            targets: {}
    "})
    .unwrap_err();
    assert!(
        format!("{error:#}").contains("must declare at least one target"),
        "{error:#}"
    );
}

#[test]
fn a_vendored_set_rejects_what_it_cannot_publish() {
    let base = vendored("");
    let cases = [
        (
            "archive without the target",
            vendored("archive: lib.tar.gz"),
            "must contain {id}",
        ),
        (
            "archive in another format",
            vendored(r#"archive: "{id}.zip""#),
            "must end in .tar.gz",
        ),
        (
            "archive in a directory",
            vendored(r#"archive: "dist/{id}.tar.gz""#),
            "must be one file name",
        ),
        (
            "archive with a typo",
            vendored(r#"archive: "{ids}.tar.gz""#),
            "that is not {name}, {version}, {id}",
        ),
        (
            "tag that varies by target",
            vendored(r#"tag: "lib-{id}""#),
            "that is not {name}, {version}",
        ),
        ("empty tag", vendored(r#"tag: """#), "cannot be empty"),
        (
            "notes outside the repo",
            vendored("notes: ../notes.md"),
            "must stay inside the repository",
        ),
        ("unknown key", vendored("bin: lib"), "bin"),
        (
            "empty version",
            base.replace("version: 1.4.0", r#"version: """#),
            "cannot be empty",
        ),
        (
            "dir outside the repo",
            base.replace("dir: out", "dir: /tmp"),
            "must stay inside the repository",
        ),
        (
            "no files",
            base.replace("files: [lib]", "files: []"),
            "must declare at least one file",
        ),
        (
            "a file outside the repo",
            base.replace("files: [lib]", "files: [../secret]"),
            "must stay inside the repository",
        ),
        (
            "version with a path separator",
            base.replace("version: 1.4.0", "version: 1.4/../../x"),
            "must be one plain name",
        ),
        (
            "target key with a parent step",
            base.replace("linux-x64:", r#""..":"#),
            "must be one plain name",
        ),
        (
            "target key with a path separator",
            base.replace("linux-x64:", "a/b:"),
            "must be one plain name",
        ),
        (
            "set name with a path separator",
            base.replace("  lib:", r#"  "../lib":"#),
            "must be one plain name",
        ),
        (
            "undeclared machine",
            base.replace("runner: linux", "runner: big"),
            r#""big" is not declared in runners (declared: linux)"#,
        ),
    ];
    for (scenario, body, expected) in cases {
        let error = load(&body).expect_err(scenario);
        assert!(
            format!("{error:#}").contains(expected),
            "{scenario}: {error:#}"
        );
    }
}

/// The package config followed by `section`, an `assets` mapping.
fn assets(section: &str) -> String {
    format!("{PACKAGE}{section}")
}

#[test]
fn asset_files_are_packed_from_their_dir() {
    let config = load(&assets(indoc! {"
        assets:
          dir: target/{triple}/release
          files: [demo, demod, LICENSE]
          linux-x64: {}
    "}))
    .unwrap();
    let recipe = config.assets.unwrap();
    assert_eq!(recipe.dir, Some(PathBuf::from("target/{triple}/release")));
    assert_eq!(
        recipe.files,
        [
            PathBuf::from("demo"),
            PathBuf::from("demod"),
            PathBuf::from("LICENSE")
        ]
    );
    assert_eq!(recipe.targets.keys().collect::<Vec<_>>(), ["linux-x64"]);
}

#[test]
fn a_target_lists_its_own_files() {
    let config = load(&assets(indoc! {"
        assets:
          dir: out/{triple}
          darwin-arm64:
            files: [proof]
          linux-x64:
            files: [bench, proof]
    "}))
    .unwrap();
    let recipe = config.assets.unwrap();
    assert_eq!(recipe.files, Vec::<PathBuf>::new());
    assert_eq!(
        recipe.targets["darwin-arm64"].files,
        Some(vec![PathBuf::from("proof")])
    );
    assert_eq!(
        recipe.targets["linux-x64"].files,
        Some(vec![PathBuf::from("bench"), PathBuf::from("proof")])
    );
}

#[test]
fn asset_files_reject_what_they_cannot_pack() {
    let cases = [
        (
            "dir without files",
            indoc! {"
                assets:
                  dir: out
                  linux-x64: {}
            "},
            "must come with files",
        ),
        (
            "dir with no files",
            indoc! {"
                assets:
                  dir: out
                  files: []
                  linux-x64: {}
            "},
            "must come with files",
        ),
        (
            "files without dir",
            indoc! {"
                assets:
                  files: [demo]
                  linux-x64: {}
            "},
            "must come with dir",
        ),
        (
            "binary beside files",
            indoc! {"
                assets:
                  binary: out/{bin}
                  dir: out
                  files: [demo]
                  linux-x64: {}
            "},
            "list the binary in files",
        ),
        (
            "dir outside the repo",
            indoc! {"
                assets:
                  dir: /tmp
                  files: [demo]
                  linux-x64: {}
            "},
            "must stay inside the repository",
        ),
        (
            "a file outside the repo",
            indoc! {"
                assets:
                  dir: out
                  files: [../secret]
                  linux-x64: {}
            "},
            "must stay inside the repository",
        ),
    ];
    for (scenario, section, expected) in cases {
        let error = load(&assets(section)).expect_err(scenario);
        assert!(
            format!("{error:#}").contains(expected),
            "{scenario}: {error:#}"
        );
    }
}

#[test]
fn asset_target_files_reject_what_they_cannot_pack() {
    let cases = [
        (
            "target files without dir",
            indoc! {"
                assets:
                  linux-x64:
                    files: [demo]
            "},
            "assets.linux-x64.files: must come with assets.dir",
        ),
        (
            "an empty target list",
            indoc! {"
                assets:
                  dir: out
                  files: [demo]
                  linux-x64:
                    files: []
            "},
            "assets.linux-x64.files: must declare at least one file",
        ),
        (
            "binary beside target files",
            indoc! {"
                assets:
                  binary: out/{bin}
                  darwin-arm64: {}
                  linux-x64:
                    files: [demo]
            "},
            "assets.binary: must be omitted when assets.linux-x64.files lists what the tarball contains",
        ),
        (
            "a target file outside the repo",
            indoc! {"
                assets:
                  dir: out
                  linux-x64:
                    files: [../secret]
            "},
            "assets.linux-x64.files[0]: must stay inside the repository",
        ),
        (
            "dir with a target that lists no files",
            indoc! {"
                assets:
                  dir: out
                  darwin-arm64: {}
                  linux-x64:
                    files: [demo]
            "},
            "must come with files",
        ),
    ];
    for (scenario, section, expected) in cases {
        let error = load(&assets(section)).expect_err(scenario);
        assert!(
            format!("{error:#}").contains(expected),
            "{scenario}: {error:#}"
        );
    }
}

/// The targets map is flattened under `assets`, so the file has no
/// `targets` key. The problem names the path the file contains and sits on
/// the line of `files`, the sixth after the three package lines.
#[test]
fn an_asset_target_problem_sits_on_its_own_line() {
    let error = load(&assets(indoc! {"
        assets:
          linux-x64:
            files: [demo]
    "}))
    .expect_err("target files without dir");
    assert!(
        format!("{error:#}")
            .contains(".ctl/ver.yaml:6:12: assets.linux-x64.files: must come with assets.dir"),
        "{error:#}"
    );
}

const ONE_PACKAGE: &str = indoc! {"
    packages:
      - name: demo
        path: Cargo.toml
"};

#[test]
fn a_proposal_left_out_is_todays_title_and_message() {
    let config = load(ONE_PACKAGE).unwrap();
    assert_eq!(config.proposal.title(), "chore(release): version packages");
    assert_eq!(
        config.proposal.commit_message(),
        "chore(release): version packages"
    );
}

#[test]
fn a_title_alone_is_also_the_commit_message() {
    let config = load(&formatdoc! {"
        {ONE_PACKAGE}proposal:
          title: 'chore: release'
    "})
    .unwrap();
    assert_eq!(config.proposal.title(), "chore: release");
    assert_eq!(config.proposal.commit_message(), "chore: release");
}

#[test]
fn an_empty_title_and_message_are_unset() {
    let config = load(&formatdoc! {"
        {ONE_PACKAGE}proposal:
          title: ''
          commit_message: ''
    "})
    .unwrap();
    assert_eq!(config.proposal.title(), "chore(release): version packages");
    assert_eq!(
        config.proposal.commit_message(),
        "chore(release): version packages"
    );
}

#[test]
fn a_commit_message_differs_from_the_title() {
    let config = load(&formatdoc! {"
        {ONE_PACKAGE}proposal:
          title: 'chore: release'
          commit_message: 'chore: release [skip ci]'
    "})
    .unwrap();
    assert_eq!(config.proposal.title(), "chore: release");
    assert_eq!(config.proposal.commit_message(), "chore: release [skip ci]");
}

#[test]
fn a_version_label_is_refused_with_what_to_do() {
    for value in [" release", "", " ~", " null"] {
        let error = load(&formatdoc! {"
            {ONE_PACKAGE}prepare:
              version_label:{value}
        "})
        .unwrap_err();
        let error = format!("{error:#}");
        assert!(
            error.contains("prepare.version_label is removed"),
            "{value:?}: {error}"
        );
        assert!(error.contains("no longer labeled"), "{value:?}: {error}");
        assert!(error.contains("delete this key"), "{value:?}: {error}");
    }
}

/// A misspelled key under a package, whether its own or a flattened
/// driver field, fails the load and names the key and the package.
#[test]
fn an_unknown_key_under_a_package_fails() {
    for (line, key) in [
        ("publsher: none", "publsher"),
        ("foramt: toml", "foramt"),
        (
            indoc! {"
                keys: [package.version]
                    kes: [x]"},
            "kes",
        ),
    ] {
        let error = load(&formatdoc! {"
            packages:
              - name: demo
                path: Cargo.toml
                {line}
        "})
        .unwrap_err();
        let error = format!("{error:#}");
        assert!(error.contains(key), "{line}: {error}");
        assert!(error.contains(r#""demo""#), "{line}: {error}");
    }
    load(indoc! {"
        packages:
          - name: demo
            path: Cargo.toml
            format: toml
            keys: [package.version]
            publisher: none
    "})
    .unwrap();
}

#[test]
fn an_unknown_key_under_a_pin_fails() {
    let error = load(&formatdoc! {"
        {ONE_PACKAGE}pins:
          - file: README.md
            package: demo
            tool: github:acme/demo
            pattern: [readme]
    "})
    .unwrap_err();
    assert!(format!("{error:#}").contains("pattern"), "{error:#}");
}

#[test]
fn an_unknown_key_under_a_pattern_fails() {
    let error = load(&formatdoc! {"
        {ONE_PACKAGE}patterns:
          readme:
            match: 'demo@{{version}} in CI'
            ocurrences: many
        pins:
          - file: README.md
            package: demo
            patterns: [readme]
    "})
    .unwrap_err();
    assert!(format!("{error:#}").contains("ocurrences"), "{error:#}");
}

#[test]
fn an_unknown_key_under_prepare_fails() {
    let error = load(&formatdoc! {"
        {ONE_PACKAGE}prepare:
          stages: [docs]
    "})
    .unwrap_err();
    assert!(format!("{error:#}").contains("stages"), "{error:#}");
}

#[test]
fn an_unknown_key_under_proposal_fails() {
    let error = load(&formatdoc! {"
        {ONE_PACKAGE}proposal:
          label: release
    "})
    .unwrap_err();
    assert!(format!("{error:#}").contains("label"), "{error:#}");
}

#[test]
fn publish_reads_options_or_a_whole_command() {
    let config = load(indoc! {"
        packages:
          - name: demo
            path: Cargo.toml
            publish:
              verify: false
          - name: tool
            path: tool/pyproject.toml
            publish: [uv, publish]
          - name: quiet
            path: quiet/Cargo.toml
            publish: []
    "})
    .unwrap();
    let options = config.packages[0].publish_options().unwrap();
    assert_eq!(options.get("verify"), Some(&serde_json::Value::Bool(false)));
    assert_eq!(config.packages[0].publish_command(), None);
    assert_eq!(
        config.packages[1].publish_command(),
        Some(["uv".to_owned(), "publish".to_owned()].as_slice())
    );
    assert_eq!(config.packages[2].publish_command(), Some([].as_slice()));
}

#[test]
fn publish_of_another_shape_names_both() {
    let error = load(indoc! {"
        packages:
          - name: demo
            path: Cargo.toml
            publish: fast
    "})
    .unwrap_err();
    assert!(
        format!("{error:#}")
            .contains("a mapping of publisher options, or a list that is the whole upload command"),
        "{error:#}"
    );
}

/// Each option belongs to the publisher the package resolves to from the
/// file alone, and the load names what to remove.
#[test]
fn options_are_checked_against_the_publisher_at_load() {
    for (yaml, message) in [
        (
            indoc! {"
                packages:
                  - name: web
                    path: package.json
                    publish:
                      verify: false
            "},
            r#"package "web" publishes with bun, which has no publish options; remove publish.verify"#,
        ),
        (
            indoc! {"
                packages:
                  - name: demo
                    path: Cargo.toml
                    publish:
                      allow_dirty: true
            "},
            r#"package "demo": cargo has no publish option "allow_dirty"; its options are: verify"#,
        ),
        (
            indoc! {"
                packages:
                  - name: demo
                    path: Cargo.toml
                    publish:
                      verify: no thanks
            "},
            r#"package "demo": publish.verify is true or false"#,
        ),
        (
            indoc! {"
                publishers:
                  cargo:
                    argv: [cargo, publish, --workspace]
                packages:
                  - name: demo
                    path: Cargo.toml
                    publish:
                      verify: false
            "},
            r#"package "demo": publishers.cargo replaces the upload command, which takes no options; remove publish, or the argv"#,
        ),
    ] {
        let error = load(yaml).unwrap_err();
        assert!(format!("{error:#}").contains(message), "{error:#}");
    }
}

/// Two packages, `core` and `app`, under `top` and with `app` set to
/// `app` (each a line of YAML, or empty).
fn with_owners(top: &str, app: &str) -> Result<Config> {
    load(&formatdoc! {"
        {top}
        packages:
          - name: core
            path: core/Cargo.toml
          - name: app
            path: app/Cargo.toml
            {app}
    "})
}

/// The top-level `owners` applies to every package, and a package's own
/// list replaces it for that package alone. With neither, a package has
/// no owner proof.
#[test]
fn owners_default_to_the_top_level_list() {
    let config = with_owners("owners: [any-victor]", "").unwrap();
    for name in ["core", "app"] {
        let package = config.find(name).unwrap();
        assert_eq!(
            config.owners_of(package),
            Some(["any-victor".to_owned()].as_slice()),
            "{name}"
        );
    }
    let config = with_owners("owners: [any-victor]", "owners: [any-victor, alice]").unwrap();
    assert_eq!(
        config.owners_of(config.find("app").unwrap()),
        Some(["any-victor".to_owned(), "alice".to_owned()].as_slice())
    );
    assert_eq!(
        config.owners_of(config.find("core").unwrap()),
        Some(["any-victor".to_owned()].as_slice())
    );
    let config = with_owners("", "").unwrap();
    assert_eq!(config.owners_of(config.find("app").unwrap()), None);
}

/// An empty list or a login listed twice fails the load and names the
/// field, at the top level and on a package.
#[test]
fn an_empty_or_repeated_owners_list_fails_naming_the_field() {
    for (top, app, expected) in [
        (
            "owners: []",
            "",
            "owners: must list at least one crates.io login",
        ),
        (
            "owners: [any-victor, any-victor]",
            "",
            r#"owners: lists "any-victor" twice"#,
        ),
        (
            "",
            "owners: []",
            "packages[app].owners must list at least one crates.io login",
        ),
        (
            "owners: [any-victor]",
            "owners: [alice, alice]",
            r#"packages[app].owners lists "alice" twice"#,
        ),
    ] {
        let error = format!("{:#}", with_owners(top, app).unwrap_err());
        assert!(error.contains(expected), "{top} {app}: {error}");
    }
}

/// `release_workflow` is `release.yml` when omitted, takes another file
/// name, and refuses a path or a file that is not a workflow, naming the
/// field.
#[test]
fn release_workflow_is_a_workflow_file_name() {
    assert_eq!(load(PACKAGE).unwrap().release_workflow, "release.yml");
    for name in ["self-release.yml", "publish.yaml"] {
        let config = load(&formatdoc! {"
            {PACKAGE}release_workflow: {name}
        "})
        .unwrap();
        assert_eq!(config.release_workflow, name);
    }
    for (name, problem) in [
        (
            ".github/workflows/release.yml",
            "be a file name under .github/workflows/",
        ),
        (
            "release.toml",
            "name a workflow file, ending in .yml or .yaml",
        ),
        (r#""""#, "be a file name under .github/workflows/"),
    ] {
        let error = load(&formatdoc! {"
            {PACKAGE}release_workflow: {name}
        "})
        .unwrap_err();
        let error = format!("{error:#}");
        assert!(
            error.contains(&format!("release_workflow: must {problem}")),
            "{name}: {error}"
        );
    }
}

/// `release_checks` is `[registry, trust]` when omitted, takes `[]` and
/// any one name, and refuses a name listed twice or one release does not
/// run, naming the field.
#[test]
fn release_checks_name_the_checks_release_runs() {
    assert_eq!(
        load(PACKAGE).unwrap().release_checks,
        [ReleaseCheck::Registry, ReleaseCheck::Trust]
    );
    for (list, expected) in [
        ("[]", [].as_slice()),
        ("[registry]", [ReleaseCheck::Registry].as_slice()),
        (
            "[trust, registry]",
            [ReleaseCheck::Trust, ReleaseCheck::Registry].as_slice(),
        ),
    ] {
        let config = load(&formatdoc! {"
            {PACKAGE}release_checks: {list}
        "})
        .unwrap();
        assert_eq!(config.release_checks, expected, "{list}");
    }
    let error = format!(
        "{:#}",
        load(&formatdoc! {"
            {PACKAGE}release_checks: [registry, registry]
        "})
        .unwrap_err()
    );
    assert!(
        error.contains(r#"release_checks: lists "registry" twice"#),
        "{error}"
    );
    let error = format!(
        "{:#}",
        load(&formatdoc! {"
            {PACKAGE}release_checks: [versions]
        "})
        .unwrap_err()
    );
    for name in ["release_checks", "versions", "registry", "trust"] {
        assert!(error.contains(name), "{name}: {error}");
    }
}

#[test]
fn asset_formats_and_names_load_and_validate() {
    let config = load(&formatdoc! {"
        {PACKAGE}assets:
          linux-x64: {{}}
          darwin-arm64:
            format: zip
          macos-pkg:
            format: raw
            file: build/App.pkg
          external-pkg:
            format: raw
            external: true
            name: Other.pkg
    "})
    .unwrap();
    let targets = &config.assets.as_ref().unwrap().targets;
    assert_eq!(targets["linux-x64"].format, AssetFormat::TarGz);
    assert_eq!(targets["darwin-arm64"].format, AssetFormat::Zip);
    assert_eq!(targets["macos-pkg"].format, AssetFormat::Raw);
    assert!(!targets["macos-pkg"].external);
    assert!(targets["external-pkg"].external);
    assert_eq!(
        asset_rules::asset_name(
            "darwin-arm64",
            &targets["darwin-arm64"],
            "demo",
            "1.2.3",
            Some("darwin"),
            Some("arm64"),
            Some("aarch64-apple-darwin"),
        ),
        Some("demo_1.2.3_macos_arm64.zip".to_owned())
    );
    assert_eq!(
        asset_rules::asset_name(
            "macos-pkg",
            &targets["macos-pkg"],
            "demo",
            "1.2.3",
            None,
            None,
            None,
        ),
        Some("App.pkg".to_owned())
    );
    assert_eq!(
        asset_rules::asset_name(
            "external-pkg",
            &targets["external-pkg"],
            "demo",
            "1.2.3",
            None,
            None,
            None,
        ),
        Some("Other.pkg".to_owned())
    );
}

#[test]
fn invalid_asset_format_and_name_combinations_fail_load() {
    for (snippet, expected) in [
        (
            indoc! {"
                assets:
                  linux-x64:
                    format: 7z
            "},
            "tar.gz, zip, or raw",
        ),
        (
            indoc! {"
                assets:
                  linux-x64:
                    name: demo.tar.gz
                    tarball: demo.tar.gz
            "},
            "assets.linux-x64.tarball",
        ),
        (
            indoc! {"
                assets:
                  macos-pkg:
                    format: raw
                    tarball: App.tar.gz
                    file: build/App.pkg
            "},
            "assets.macos-pkg.tarball",
        ),
        (
            indoc! {"
                assets:
                  macos-pkg:
                    format: raw
            "},
            "assets.macos-pkg.file",
        ),
        (
            indoc! {"
                assets:
                  macos-pkg:
                    format: raw
                    external: true
            "},
            "assets.macos-pkg.name",
        ),
    ] {
        let error = format!(
            "{:#}",
            load(&format!("{PACKAGE}{snippet}")).expect_err(expected)
        );
        assert!(error.contains(expected), "{snippet} | error: {error}");
    }
}

#[test]
fn invalid_raw_file_and_generated_combinations_fail_load() {
    for (snippet, expected) in [
        (
            indoc! {"
                assets:
                  linux-x64:
                    format: tar.gz
                    file: build/demo
            "},
            "assets.linux-x64.file",
        ),
        (
            indoc! {"
                assets:
                  dir: dist
                  files: [demo]
                  macos-pkg:
                    format: raw
                    file: build/App.pkg
                    files: [App.pkg]
            "},
            "assets.macos-pkg.files",
        ),
        (
            indoc! {"
                assets:
                  macos-pkg:
                    format: raw
                    file: ../App.pkg
            "},
            "must stay inside the repository",
        ),
        (
            indoc! {r#"
                assets:
                  generated:
                    - path: share/usage/{bin}.kdl
                      run: ["{binary}", --usage-spec]
                  macos-pkg:
                    format: raw
                    file: build/App.pkg
            "#},
            "assets.generated",
        ),
        (
            indoc! {"
                assets:
                  first-pkg:
                    format: raw
                    file: build/App.pkg
                  second-pkg:
                    format: raw
                    external: true
                    name: App.pkg
            "},
            "App.pkg",
        ),
    ] {
        let error = format!(
            "{:#}",
            load(&format!("{PACKAGE}{snippet}")).expect_err(expected)
        );
        assert!(error.contains(expected), "{snippet} | error: {error}");
    }
}

#[test]
fn trusted_publishing_only_defaults_true_and_supports_overrides() {
    let default_cfg = load(PACKAGE).unwrap();
    assert!(default_cfg.trusted_publishing_only);
    assert!(default_cfg.trusted_publishing_only_of(&default_cfg.packages[0]));

    let overridden = load(indoc! {"
        trusted_publishing_only: false
        packages:
          - name: inherited
            path: a/Cargo.toml
          - name: strict
            path: b/Cargo.toml
            trusted_publishing_only: true
    "})
    .unwrap();
    assert!(!overridden.trusted_publishing_only);
    assert!(!overridden.trusted_publishing_only_of(&overridden.packages[0]));
    assert!(overridden.trusted_publishing_only_of(&overridden.packages[1]));
}