oakum 0.12.1

A polyglot release tool that derives dependent version bumps from the dependency graph
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
use std::collections::{BTreeMap, BTreeSet};

use oakum::changeset::{is_bump_file_name, load_bump_files};
use oakum::commits::path_crate_changes;
use oakum::plan::{BumpFile, Ecosystem, Package, PackageId, Workspace};
use oakum::state::{BumpName, ChangedPackage, CoverSource, Coverage, ReleasingCommit};
use oakum::tags::Declared;

use super::changelog;
use super::dependency_updates::{self, Ask, HeadPackages, Verdicts};
use super::generate::{resolve_from_ref, CommitTypes};
use super::git::{Commit, Followed, Git, Op};
use super::intent::BranchCommits;
use super::reasons;
use super::root_files::{self, RootReach};
use super::CliError;

/// What the config says about a changed package. `Excluded` is a decision
/// someone wrote in `include`/`exclude`; `Unmanaged` is the absence of one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Standing {
    Excluded,
    Unmanaged,
    Managed,
}

/// The intent the coverage look reads, kept apart by kind so the answer can
/// say which piece covered a package.
#[derive(Clone, Debug)]
pub(super) enum Covering {
    /// The branch's bump files, and its commits that release nothing.
    ChangeFiles {
        files: Vec<BumpFile>,
        commits: BranchCommits,
    },
    /// Intent from commits alone, each a [`BumpFile`] whose id is its hash.
    /// No command covers a package here; only a commit can.
    CommitsOnly {
        commits: Vec<BumpFile>,
        types: CommitTypes,
    },
}

impl Covering {
    pub(super) fn files(&self) -> &[BumpFile] {
        match self {
            Self::ChangeFiles { files, .. } => files,
            Self::CommitsOnly { .. } => &[],
        }
    }

    fn commits(&self) -> (&[BumpFile], &CommitTypes) {
        match self {
            Self::ChangeFiles { commits, .. } => (&commits.files, &commits.types),
            Self::CommitsOnly { commits, types } => (commits, types),
        }
    }

    fn sources(&self, id: &PackageId) -> Vec<CoverSource> {
        let named = |file: &BumpFile| {
            file.entries
                .iter()
                .filter(|(named, _)| named == id)
                .map(|(_, level)| *level)
                .max()
        };
        let mut sources = Vec::new();
        for file in self.files() {
            let path = format!("{BUMP_DIR}/{}", file.id);
            if file.entries.is_empty() {
                sources.push(CoverSource::EmptyFile { file: path });
            } else if let Some(level) = named(file) {
                sources.push(CoverSource::file(path, level));
            }
        }
        let (commits, types) = self.commits();
        for commit in commits {
            if let Some(level) = named(commit) {
                let kind = types.get(&commit.id).and_then(|read| read.kind.clone());
                sources.push(CoverSource::commit(commit.id.clone(), kind, level));
            }
        }
        sources
    }

    fn released_by(&self, id: &PackageId) -> Vec<ReleasingCommit> {
        match self {
            Self::ChangeFiles { commits, .. } => {
                commits.released.get(id).cloned().unwrap_or_default()
            }
            Self::CommitsOnly { .. } => Vec::new(),
        }
    }

    /// The level is the highest a commit asks for, since that is the release
    /// it is missing; a placeholder where no commit implies one.
    fn fix(&self, id: &PackageId, released_by: &[ReleasingCommit]) -> Option<String> {
        if let Self::CommitsOnly { .. } = self {
            return None;
        }
        let level = released_by
            .iter()
            .map(|commit| commit.bump)
            .max()
            .map_or("<level>", BumpName::as_str);
        Some(format!("oakum add --packages {}:{level}", id.name))
    }
}

/// The coverage answer for `from...HEAD`, as [`answer`] reads it.
pub(super) fn changed_by_standing(
    git: &Git,
    workspace: &Workspace,
    covering: &Covering,
    from: Option<&str>,
    standing: impl Fn(&Package) -> Standing,
) -> Result<Coverage, CliError> {
    Ok(answer(
        &committed_changes(git, workspace, from)?,
        workspace,
        covering,
        &classify(workspace, standing),
    ))
}

/// What a branch changed: its paths, what they changed in a Cargo
/// workspace's root files, and which of those are dependency updates.
struct Changes {
    paths: Vec<String>,
    root: RootReach,
    verdicts: Verdicts,
}

/// The committed half reads `from...HEAD`, so the root files are compared at
/// the merge base, not at `from`.
struct Committed {
    changes: Changes,
    base: String,
    /// Version commits' writes kept: the root comparison excuses only those parts.
    listed: Vec<String>,
}

fn committed_changes(
    git: &Git,
    workspace: &Workspace,
    from: Option<&str>,
) -> Result<Changes, CliError> {
    committed(git, workspace, from).map(|committed| committed.changes)
}

fn committed(git: &Git, workspace: &Workspace, from: Option<&str>) -> Result<Committed, CliError> {
    let (base, listed, paths) = changed_paths(git, workspace, from)?;
    let root_touched = root_files::touched(workspace, &listed);
    if !root_touched && !dependency_updates::names_a_manifest(workspace, &paths) {
        return Ok(Committed {
            changes: Changes {
                paths,
                root: RootReach::default(),
                verdicts: Verdicts::default(),
            },
            base,
            listed,
        });
    }
    let (fork, head) = (fork_point(git, &base)?, git.head()?);
    let root = if root_touched {
        root_files::between_commits(git, workspace, &fork, &head, &listed)?
    } else {
        RootReach::default()
    };
    let sides = (&fork, HeadPackages::Commit(&head));
    let verdicts = dependency_updates::verdicts(git, workspace, sides, &paths, &root, &|wanted| {
        dependency_updates::followed(git, &head, wanted)
    })?;
    Ok(Committed {
        changes: Changes {
            paths,
            root,
            verdicts,
        },
        base,
        listed,
    })
}

fn fork_point(git: &Git, base: &str) -> Result<Commit, CliError> {
    git.merge_base(base)?.ok_or_else(|| {
        CliError::unverified(format!(
            "unverified: `{base}` and `HEAD` share no commit, so the workspace's root files have no side to compare against"
        ))
    })
}

/// Managed packages whose change lives outside `HEAD` and which nothing would
/// cover once committed.
///
/// A newtype because the alternative — a bare `Vec<PackageId>` beside
/// [`Coverage::uncovered`] — is the same shape as the list it must never be
/// confused with. Swapping the two compiles cleanly and inverts the report: a
/// dirty worktree starts failing `--strict` while a real uncovered commit
/// passes.
#[derive(Debug, Default)]
pub(super) struct Unseen(Vec<ChangedPackage>);

impl Unseen {
    /// The report, built here so the packages never become a bare slice
    /// beside `Coverage::uncovered`. That slice is the one place the two could
    /// be swapped, so a newtype unwrapped before reaching it guards the
    /// plumbing and abandons the use site.
    pub(super) fn lines(&self, hint: impl Fn(&ChangedPackage) -> String) -> Vec<String> {
        self.0
            .iter()
            .map(|package| {
                format!(
                    "{}: changed{} outside `HEAD`, which the coverage look does not read; \
                     commit it and {}",
                    package.id(),
                    reasons::via_clause(package),
                    hint(package)
                )
            })
            .collect()
    }
}

/// What the coverage look established, in the two tenses it has to answer in.
pub(super) struct Uncovered {
    /// The answer for `HEAD`, which is the one a pull request is judged on.
    pub(super) committed: Coverage,
    /// What the same question would add once the working tree is committed.
    ///
    /// `Err` is a look that could not run, never a clean answer, and it is
    /// held here rather than raised so that it cannot take [`Self::committed`]
    /// with it: a `git status` that fails says nothing about the refusal the
    /// commits already established. The caller reports it without gating,
    /// because this half does not gate when it answers either.
    pub(super) outside_head: Result<Worktree, CliError>,
}

/// What reading the working tree added to the committed answer.
#[derive(Debug)]
pub(super) struct Worktree {
    pub(super) unseen: Unseen,
    /// Packages the committed answer calls covered only because intent on disk
    /// says so, where `HEAD`'s own intent does not.
    ///
    /// The mirror of [`Self::unseen`]: there the change is invisible, here the
    /// coverage is. Both halves of the question read different worlds, so both
    /// directions have to be said.
    ///
    /// `Err` when `HEAD`'s intent could not be read, which is a different
    /// failure from an unreadable working tree and has to say so: the run
    /// could not work out what a pull request would be covered by.
    ///
    /// Said, not gated. The committed half is what a pull request is judged on
    /// and it still answers and still refuses, so losing this one costs the
    /// warning and nothing else — the run lands exactly where it did before
    /// this look existed. Decided rather than inherited: a refusal here would
    /// be a refusal on a tree that passes today.
    pub(super) covered_off_disk: Result<Vec<OffDisk>, CliError>,
}

/// A package whose coverage rests on intent a pull request will not receive.
#[derive(Debug)]
pub(super) struct OffDisk {
    pub(super) package: PackageId,
    /// The files it rests on, repository-relative.
    pub(super) files: Vec<String>,
}

impl Worktree {
    /// The report, built here so neither list becomes a bare sequence of ids
    /// beside `Coverage::uncovered` — the one place the three could be
    /// confused for one another.
    pub(super) fn lines(&self, hint: impl Fn(&ChangedPackage) -> String) -> Vec<String> {
        let mut lines = self.unseen.lines(hint);
        let off_disk = match &self.covered_off_disk {
            Ok(off_disk) => off_disk,
            Err(err) => {
                lines.push(format!(
                    "the intent `HEAD` carries could not be read, so what a pull request would \
                     be covered by is unknown: {}",
                    err.detail()
                ));
                return lines;
            }
        };
        lines.extend(off_disk.iter().map(|off| {
            let quoted: Vec<String> = off.files.iter().map(|file| format!("`{file}`")).collect();
            let quoted: Vec<&str> = quoted.iter().map(String::as_str).collect();
            format!(
                "{}: covered on disk by {}, not by `HEAD`; commit that, or a pull request gets \
                 this package with nothing covering it",
                off.package,
                super::verdict::named(&quoted)
            )
        }));
        lines
    }
}

/// The coverage answer, beside the packages it would also refuse once
/// everything outside `HEAD` is committed.
///
/// Under `change-files` the two halves read different worlds — changed
/// packages from commits, intent from the working tree — so a change that is
/// only staged, only edited or not yet tracked sits in neither and the look
/// passes over it in silence. The second list is how it says so.
///
/// Under `conventional-commits` both halves read commits and no such gap
/// exists; the list is then a prediction of what committing would refuse
/// rather than a hole being closed. Worth saying either way, which is why this
/// does not branch on the intent source.
///
/// Only packages the first answer does not already name reach it: a package
/// that is uncovered either way is one refusal, not two.
///
/// Costs one `git status` beyond [`changed_by_standing`], which is why the
/// pipelines that build a plan keep the cheaper call — the question only
/// matters where someone is about to push.
pub(super) fn changed_by_standing_and_unseen(
    git: &Git,
    workspace: &Workspace,
    covering: &Covering,
    from: Option<&str>,
    branch: Option<&BranchBumpFiles>,
    standing: impl Fn(&Package) -> Standing,
    read_disk: impl Fn(&str) -> Result<Option<String>, CliError>,
) -> Result<Uncovered, CliError> {
    let classified = classify(workspace, standing);
    let Committed {
        changes: committed_changes,
        base,
        listed,
    } = committed(git, workspace, from)?;
    let committed = answer(&committed_changes, workspace, covering, &classified);
    let paths = &committed_changes.paths;
    let outside_head = uncommitted_paths(git).and_then(|uncommitted| {
        // Intent is read from disk, so a bump file in this listing is not a
        // change to the package it names — it is the other question's subject.
        let changes: Vec<String> = uncommitted
            .into_iter()
            .filter(|path| !is_intent_path(path))
            .collect();
        // Skipped where there is nothing to compare: `conventional-commits`
        // (no `branch`) reads intent from commits on both halves — running it
        // there names `.changeset/<commit hash>`, which is not a path anyone
        // can commit — and no intent on disk means no coverage that could rest
        // on a copy a pull request will not get. `HEAD`'s files are held to
        // the branch's own as the disk's are, or a file pending on the base
        // hides coverage that rests on disk alone.
        //
        // Keyed on the disk set rather than on `git status`, which answers a
        // different question than the one the disk reader asks: `read_dir`
        // ignores exclude rules and `skip-worktree`, so a bump file git does
        // not mention still feeds the plan (measured: `.changeset/*.md` in
        // `.git/info/exclude`, and a `skip-worktree` bit, each made the look
        // vanish while the file went on covering).
        let covered_off_disk = match (branch, covering) {
            (Some(branch), Covering::ChangeFiles { files, commits }) if !files.is_empty() => {
                intent_in_head(git, workspace).map(|head| {
                    resting_on_uncommitted_intent(
                        // Commits are in `HEAD` on both halves, so they cover
                        // alike in each.
                        &Covering::ChangeFiles {
                            files: branch.own_in_head(head),
                            commits: commits.clone(),
                        },
                        &committed_changes,
                        workspace,
                        files,
                        &classified,
                        &committed,
                    )
                })
            }
            _ => Ok(Vec::new()),
        };
        let mut everything = paths.clone();
        everything.extend(changes.iter().cloned());
        let mut listed = listed.clone();
        listed.extend(changes.iter().cloned());
        let root_touched = root_files::touched(workspace, &listed);
        let (root, verdicts) =
            if root_touched || dependency_updates::names_a_manifest(workspace, &everything) {
                let (fork, head) = (fork_point(git, &base)?, git.head()?);
                let root = if root_touched {
                    root_files::against_worktree(
                        git, workspace, &fork, &head, &listed, &changes, &read_disk,
                    )?
                } else {
                    RootReach::default()
                };
                let verdicts = dependency_updates::verdicts(
                    git,
                    workspace,
                    (&fork, HeadPackages::Worktree),
                    &everything,
                    &root,
                    &|wanted| {
                        let committed = dependency_updates::followed(git, &head, wanted)?;
                        wanted
                            .iter()
                            .zip(committed)
                            .map(|(path, committed)| {
                                if changes.iter().any(|listed| listed == path) {
                                    read_disk(path)
                                } else {
                                    Ok(committed)
                                }
                            })
                            .collect()
                    },
                )?;
                (root, verdicts)
            } else {
                (RootReach::default(), Verdicts::default())
            };
        let if_committed = answer(
            &Changes {
                paths: everything,
                root,
                verdicts,
            },
            workspace,
            covering,
            &classified,
        );
        let already: Vec<&oakum::state::PackageRef> =
            committed.uncovered().map(ChangedPackage::id).collect();
        Ok(Worktree {
            unseen: Unseen(
                if_committed
                    .uncovered()
                    .filter(|package| !already.contains(&package.id()))
                    .cloned()
                    .collect(),
            ),
            covered_off_disk,
        })
    });
    Ok(Uncovered {
        committed,
        outside_head,
    })
}

/// Classified once per package and read from the map thereafter: asking twice
/// would let an inconsistent answer report an excluded package as unmanaged,
/// which accuses someone of an omission they did not make.
fn classify(
    workspace: &Workspace,
    standing: impl Fn(&Package) -> Standing,
) -> BTreeMap<PackageId, Standing> {
    workspace
        .packages()
        .map(|package| (package.id().clone(), standing(package)))
        .collect()
}

/// An excluded package nothing managed ships stays silent, where an unmanaged
/// one is reported (ADR-0039). Both lists are sorted and disjoint.
fn answer(
    diff: &Changes,
    workspace: &Workspace,
    covering: &Covering,
    classified: &BTreeMap<PackageId, Standing>,
) -> Coverage {
    let managed = |package: &Package| classified.get(package.id()) == Some(&Standing::Managed);
    let asks =
        dependency_updates::asks(workspace, &diff.paths, &diff.root, &diff.verdicts, managed);
    let origins = |wanted: Ask| {
        asks.iter()
            .filter(move |(_, asked)| **asked == wanted)
            .map(|(id, _)| id)
    };
    let mut reached = oakum::plan::reach(workspace, origins(Ask::Intent), managed);
    let updated = oakum::plan::reach(workspace, origins(Ask::Update), managed);
    let crates = path_crate_changes(&diff.paths, workspace);
    let through_crates = oakum::plan::reach(workspace, crates.keys(), managed);
    for (id, mut via) in through_crates.managed {
        // The crate is the hop farthest from the package; a direct path of
        // equal length wins the tie.
        let origin = via.last().unwrap_or(&id);
        if let Some(name) = crates.get(origin).and_then(|names| names.first()) {
            via.push(PackageId::new(Ecosystem::Cargo, name.clone()));
        }
        if reached
            .managed
            .get(&id)
            .is_none_or(|direct| direct.len() > via.len())
        {
            reached.managed.insert(id, via);
        }
    }
    reached.stranded.extend(through_crates.stranded);
    let mut through = diff.root.through(workspace, managed);
    let mut changed = BTreeMap::new();
    for (id, via) in reached.managed {
        let covered_by = covering.sources(&id);
        let (released_by, fix) = if covered_by.is_empty() {
            let released_by = covering.released_by(&id);
            let fix = covering.fix(&id, &released_by);
            (released_by, fix)
        } else {
            (Vec::new(), None)
        };
        let through = through.remove(&id).unwrap_or_default();
        let package = ChangedPackage::new(id.clone(), via, covered_by, released_by, fix);
        changed.insert(id, package.with_through(through));
    }
    // A package also reached another way keeps that way's answer.
    for (id, via) in updated.managed {
        if changed.contains_key(&id) {
            continue;
        }
        let mut covered_by = covering.sources(&id);
        covered_by.push(CoverSource::DependencyUpdate);
        let through = through.remove(&id).unwrap_or_default();
        let package = ChangedPackage::new(id.clone(), via, covered_by, Vec::new(), None);
        changed.insert(id, package.with_through(through));
    }
    let changed = changed.into_values().collect();
    Coverage {
        unmanaged: reached
            .stranded
            .into_iter()
            .chain(updated.stranded)
            .filter(|id| classified.get(id) == Some(&Standing::Unmanaged))
            .collect(),
        changed,
    }
}

/// The base `from` resolves to, and the paths changed between it and `HEAD`
/// without intent files: all of them, then with a version commit's own writes
/// dropped.
fn changed_paths(
    git: &Git,
    workspace: &Workspace,
    from: Option<&str>,
) -> Result<(String, Vec<String>, Vec<String>), CliError> {
    // At depth 1 the default base resolves to HEAD itself, so the diff comes
    // back empty and every changed package looks covered. `actions/checkout`
    // clones that way by default, which makes this the common CI shape rather
    // than an edge one.
    refuse_shallow(git)?;
    let base = resolve_from_ref(git, from)?;
    let dirs: BTreeSet<&str> = workspace.packages().map(Package::manifest_dir).collect();
    let released = written_only_by_version_commits(git, &base, &dirs, |commit, dir| {
        released_in(git, workspace, commit, dir)
    })?;
    let listed: Vec<String> = git
        .paths(Op::ChangedPaths { from: &base })?
        .into_iter()
        .filter(|path| !is_intent_path(path))
        .collect();
    let paths = listed
        .iter()
        .filter(|path| !released.contains(*path))
        .cloned()
        .collect();
    Ok((base, listed, paths))
}

pub(super) fn refuse_shallow(git: &Git) -> Result<(), CliError> {
    if super::tags::is_shallow(git)? {
        return Err(CliError::unverified(
            "unverified: shallow clone; changed files cannot be listed against a base that was not fetched — use `fetch-depth: 0`, or `git fetch --unshallow`",
        ));
    }
    Ok(())
}

/// Files `version` writes in a package's directory beside its changelog.
/// `extra-files` are left out, so a version commit's writes there still count.
const VERSION_WRITES: [&str; 7] = [
    "Cargo.toml",
    "package.json",
    "CHANGELOG.md",
    "Cargo.lock",
    "pnpm-lock.yaml",
    "pnpm-workspace.yaml",
    ".yarnrc.yml",
];

/// The manifests among [`VERSION_WRITES`], excused only for the package a
/// version commit released.
const MANIFESTS: [&str; 2] = ["Cargo.toml", "package.json"];

/// Paths in `from..HEAD` that only version commits touched, among the files
/// `version` writes for a package it released.
///
/// A version commit is told by what it does, not by its subject, which
/// `commit-message` sets, nor by a consumed bump file, which a release made
/// only of dependency updates does not have: `released(commit, dir)` names
/// the manifests in `dir` whose package the commit released: it moved the
/// version and the changelog gained that version's section. Only files in
/// such a directory are excused, and of its manifests only the released
/// packages', so a hand edit to another package's manifest riding along still
/// counts. A merge is never one.
fn written_only_by_version_commits(
    git: &Git,
    base: &str,
    dirs: &BTreeSet<&str>,
    released: impl Fn(&RangeCommit, &str) -> Result<BTreeSet<String>, CliError>,
) -> Result<BTreeSet<String>, CliError> {
    let mut excused = BTreeSet::new();
    let mut ordinary = BTreeSet::new();
    for commit in range_commits(git, base)? {
        // `version` adds and rewrites; a deletion is never one of its writes.
        let written = |status: &str| status != "D";
        let wrote: BTreeSet<&str> = commit
            .changes
            .iter()
            .filter(|(status, _)| written(status))
            .map(|(_, path)| path.as_str())
            .collect();
        let mut by_dir: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
        for (status, path) in &commit.changes {
            let (dir, name) = path.rsplit_once('/').unwrap_or(("", path));
            let changelog = if dir.is_empty() {
                String::from("CHANGELOG.md")
            } else {
                format!("{dir}/CHANGELOG.md")
            };
            let candidate = !commit.merge
                && written(status)
                && VERSION_WRITES.contains(&name)
                && dirs.contains(dir)
                && wrote.contains(changelog.as_str());
            if candidate && !by_dir.contains_key(dir) {
                by_dir.insert(dir, released(&commit, dir)?);
            }
            // A manifest is excused only for the package released; the
            // directory's changelog and lockfiles for any package in it.
            let released_here = candidate
                && by_dir.get(dir).is_some_and(|manifests| {
                    !manifests.is_empty()
                        && (!MANIFESTS.contains(&name) || manifests.contains(path))
                });
            if released_here {
                excused.insert(path.clone());
            } else {
                ordinary.insert(path.clone());
            }
        }
    }
    Ok(excused.difference(&ordinary).cloned().collect())
}

/// The manifests in `dir` whose package `commit` released: it moved the
/// version and the package's changelog gained that version's section, under
/// its bare heading or its `name@version` one. A file a side holds that
/// cannot be read, including a link that dangles or leaves the repository,
/// releases nothing, so the commit's writes still count.
fn released_in(
    git: &Git,
    workspace: &Workspace,
    commit: &RangeCommit,
    dir: &str,
) -> Result<BTreeSet<String>, CliError> {
    let head = Commit::from_log(&commit.hash)?;
    let parent = git.first_parent_or_empty(&head)?;
    // `Err(())` is a file the side holds but that cannot be read.
    let read = |at: &Commit, path: &str| -> Result<Result<Option<String>, ()>, CliError> {
        Ok(match git.followed_blob(at, path)? {
            Followed::File(bytes) => Ok(Some(String::from_utf8_lossy(&bytes).into_owned())),
            Followed::Absent => Ok(None),
            Followed::Dangling | Followed::Unfollowed(_) => Err(()),
        })
    };
    let mut released = BTreeSet::new();
    for package in workspace
        .packages()
        .filter(|package| package.manifest_dir() == dir)
    {
        let manifest = package.manifest_path();
        let root = match package.id().ecosystem {
            Ecosystem::Cargo => workspace
                .cargo_root_manifest()
                .filter(|root| *root != manifest),
            Ecosystem::Npm => None,
        };
        let declared = |at: &Commit| -> Result<Declared, CliError> {
            let text = match read(at, &manifest)? {
                Ok(Some(text)) => text,
                Ok(None) => return Ok(Declared::Absent),
                Err(()) => return Ok(Declared::Unreadable),
            };
            // A root that cannot be read leaves an inheriting member's
            // version unreadable.
            oakum::tags::declared(package.id().ecosystem, &text, || match &root {
                Some(root) => read(at, root).map(|side| side.unwrap_or(Some(String::new()))),
                None => Ok(Some(text.clone())),
            })
        };
        let Declared::Version(version) = declared(&head)? else {
            continue;
        };
        match declared(&parent)? {
            Declared::Version(before) if before == version => continue,
            Declared::Unreadable => continue,
            Declared::Version(_) | Declared::Absent => {}
        }
        let path = changelog::changelog_repo_path(package);
        let section = |at: &Commit| -> Result<Option<bool>, CliError> {
            Ok(match read(at, &path)? {
                // An unshared owner reads the `name@version` heading as well.
                Ok(Some(text)) => Some(changelog::holds_version_section(
                    &text,
                    changelog::Owner::new(&package.id().name, false),
                    &version,
                )),
                Ok(None) => Some(false),
                Err(()) => None,
            })
        };
        if section(&head)? == Some(true) && section(&parent)? == Some(false) {
            released.insert(manifest);
        }
    }
    Ok(released)
}

struct RangeCommit {
    hash: String,
    merge: bool,
    changes: Vec<(String, String)>,
}

/// Parses [`Op::RangeChanges`] field by field: a path is read only as the
/// second half of a pair, so a path holding `\x01` cannot pose as a header.
/// Anything else out of place, or fewer records than [`Op::RangeCount`]
/// counts, is a listing cut short, so it is `unverified`.
fn range_commits(git: &Git, base: &str) -> Result<Vec<RangeCommit>, CliError> {
    let cut_short = || {
        CliError::unverified(
            "unverified: `git log --name-status` ended mid-record, so version commits could not be told from the rest",
        )
    };
    let is_hash =
        |id: &str| matches!(id.len(), 40 | 64) && id.bytes().all(|b| b.is_ascii_hexdigit());
    let raw = git.text(Op::RangeChanges { from: base })?;
    let mut fields = raw.split('\0');
    let mut commits: Vec<RangeCommit> = Vec::new();
    while let Some(field) = fields.next() {
        let field = field.strip_prefix('\n').unwrap_or(field);
        if field.is_empty() {
            continue;
        }
        if let Some(header) = field.strip_prefix('\u{1}') {
            // A root commit has no parents, so its header ends in a space.
            let ids: Vec<&str> = header.split_ascii_whitespace().collect();
            if ids.is_empty() || !ids.iter().all(|id| is_hash(id)) {
                return Err(cut_short());
            }
            commits.push(RangeCommit {
                hash: ids[0].to_owned(),
                merge: ids.len() > 2,
                changes: Vec::new(),
            });
            continue;
        }
        let status_letters = field.bytes().all(|b| b.is_ascii_uppercase());
        let path = fields.next().filter(|path| !path.is_empty());
        let (Some(commit), Some(path), true) = (commits.last_mut(), path, status_letters) else {
            return Err(cut_short());
        };
        commit.changes.push((field.to_owned(), path.to_owned()));
    }
    let counted = git.text(Op::RangeCount { from: base })?;
    if counted.trim().parse::<usize>().ok() != Some(commits.len()) {
        return Err(cut_short());
    }
    Ok(commits)
}

/// Repository-relative paths the index or the worktree holds that `HEAD` does
/// not — staged, edited and untracked alike, intent files included: which side
/// of the listing one of those falls on is the caller's question, not this
/// one's.
///
/// Porcelain v1 under `-z` writes each entry as its two status letters, a
/// space and the path; a rename or a copy then writes the origin path as its
/// own field (measured, git 2.55: `R  src/renamed.rs\0src/main.rs\0`). Both
/// names are kept, because a file moved out of a package changed that package
/// as much as the one it landed in.
fn uncommitted_paths(git: &Git) -> Result<Vec<String>, CliError> {
    let mut paths = Vec::new();
    let mut origin_follows = false;
    for record in git.paths(Op::UncommittedPaths)? {
        if std::mem::take(&mut origin_follows) {
            paths.push(record);
            continue;
        }
        // A record git wrote in a shape this does not know is a working tree
        // nothing here can compare with `HEAD`; saying so beats attributing a
        // path that was never listed, or passing over one that was.
        let Some((status, path)) = record
            .split_at_checked(3)
            .filter(|(_, path)| !path.is_empty())
        else {
            return Err(CliError::unverified(format!(
                "unverified: `git status --porcelain -z` wrote `{record}`, which is not a status pair and a path, so this tree could not be compared with `HEAD`"
            )));
        };
        origin_follows = status.contains(['R', 'C']);
        paths.push(path.to_owned());
    }
    // A rename whose origin never arrived means the listing stopped early — a
    // child killed mid-write, a full disk. Returning what was read would drop
    // the rest of the tree at exit 0, which is the silence this look exists to
    // break.
    if origin_follows {
        return Err(CliError::unverified(
            "unverified: `git status --porcelain -z` ended after a rename with no origin path, so this tree could not be compared with `HEAD`",
        ));
    }
    Ok(paths)
}

/// The intent `HEAD` carries, read from its tree rather than from disk.
///
/// Presence of a path is the wrong question and was measured wrong: a bump file
/// that is committed and then edited to name a second package covers that
/// package here while `HEAD` does not cover it, which is the false green this
/// look exists to close. What a pull request gets is the file's *content* at
/// `HEAD`, so that is what this reads.
fn intent_in_head(git: &Git, workspace: &Workspace) -> Result<Vec<BumpFile>, CliError> {
    let head = git.head()?;
    let listed = git.paths(Op::TreePaths {
        commit: &head,
        dir: BUMP_DIR,
    })?;
    let named: Vec<(&str, &str)> = listed
        .iter()
        .filter_map(|path| {
            bump_file_name(path)
                .filter(|name| is_bump_file_name(name))
                .map(|name| (name, path.as_str()))
        })
        .collect();
    let framed: Vec<&str> = named
        .iter()
        .map(|(_, path)| *path)
        .filter(|path| !path.contains('\n'))
        .collect();
    // A failed batch is read again one file at a time, so the failure is worded
    // as the per-file read words it.
    let mut batched = git.blobs(&head, &framed).ok().map(Vec::into_iter);
    let mut pairs: Vec<(String, String)> = Vec::new();
    for (name, path) in named {
        let body = match batched.as_mut() {
            Some(bodies) if !path.contains('\n') => bodies
                .next()
                .expect("one batched body per framed path, in order"),
            _ => git.blob(Op::BlobText {
                commit: &head,
                path,
            })?,
        };
        pairs.push((name.to_owned(), body));
    }
    // One file at a time, because `load_bump_files` aborts the whole set on a
    // name the workspace does not have — and a pull request that removes a
    // package is exactly that: `HEAD` still carries the bump file naming it.
    // Such a file covers nothing in this workspace, which is an answer rather
    // than a failure to look, so it is dropped and the rest still answers.
    let mut files = Vec::new();
    let mut malformed = Vec::new();
    for (name, body) in &pairs {
        let Ok(loaded) = load_bump_files([(name.as_str(), body.as_str())], workspace) else {
            continue;
        };
        files.extend(loaded.files);
        malformed.extend(loaded.malformed);
    }
    let loaded = oakum::changeset::LoadedBumpFiles { files, malformed };
    // Dropping a file `HEAD` cannot parse is not the quiet-but-safe direction
    // it looks like: where another file already covers the package, the loss
    // shows up as no difference at all, and the run reports nothing while the
    // pull request refuses. What could not be read is said instead.
    if !loaded.malformed.is_empty() {
        let reports: Vec<String> = loaded.malformed.iter().map(ToString::to_string).collect();
        return Err(CliError::unverified(format!(
            "unverified: `HEAD` carries intent oakum cannot parse ({}), so what a pull request \
             would be covered by could not be worked out",
            reports.join("; also ")
        )));
    }
    Ok(loaded.files)
}

/// The bump files this branch touched. Coverage counts only the intent a
/// branch adds or changes: a file pending on the base covers whatever it names
/// on every branch until the release consumes it, so counting it passes a
/// change that brought none of its own. Told by path, not content, so a base
/// copy oakum cannot read (a symlink, a file a repair is fixing) never decides.
#[derive(Default)]
pub(super) struct BranchBumpFiles {
    /// Changed between the merge-base and `HEAD`.
    committed: BTreeSet<String>,
    /// Changed, staged or untracked in the working tree.
    uncommitted: BTreeSet<String>,
}

impl BranchBumpFiles {
    /// # Errors
    ///
    /// Unverified when there is no merge-base or the committed listing cannot
    /// be read.
    pub(super) fn read(git: &Git, base: &str) -> Result<Self, CliError> {
        // A shallow base finds no merge-base, which would read as unrelated
        // history rather than the fetch depth that caused it.
        refuse_shallow(git)?;
        // `merge-base` and `rev-parse HEAD` are act-class reads, which fail as
        // exit 1; here each is a look that did not happen.
        let unread = |err: CliError| match err.exit_code() {
            2 => err,
            _ => CliError::unverified(format!("unverified: {}", err.detail())),
        };
        let fork = git.merge_base(base).map_err(unread)?;
        let Some(fork) = fork else {
            return Err(CliError::unverified(format!(
                "unverified: `{base}` and `HEAD` share no history, so the bump files pending \
                 there cannot be told from this branch's"
            )));
        };
        let names = |paths: Vec<String>| -> BTreeSet<String> {
            paths
                .iter()
                .filter_map(|path| bump_file_name(path))
                .map(str::to_owned)
                .collect()
        };
        // A path the branch deleted is not intent it carries, even with a copy
        // left on disk: only names `HEAD` still holds count.
        let in_head = names(git.paths(Op::TreePaths {
            commit: &git.head().map_err(unread)?,
            dir: BUMP_DIR,
        })?);
        let changed = names(git.paths(Op::ChangedPaths {
            from: fork.as_str(),
        })?);
        Ok(Self {
            committed: changed.intersection(&in_head).cloned().collect(),
            // Unread, it adds nothing, leaving `HEAD`'s answer; `check`'s
            // worktree half runs the same listing and reports the failure.
            uncommitted: uncommitted_paths(git).map(names).unwrap_or_default(),
        })
    }

    /// The files on disk the branch touched, committed or not.
    pub(super) fn own(&self, files: &[BumpFile]) -> Vec<BumpFile> {
        files
            .iter()
            .filter(|file| self.committed.contains(&file.id) || self.uncommitted.contains(&file.id))
            .cloned()
            .collect()
    }

    /// The files `HEAD` carries that the branch's commits touched.
    fn own_in_head(&self, files: Vec<BumpFile>) -> Vec<BumpFile> {
        files
            .into_iter()
            .filter(|file| self.committed.contains(&file.id))
            .collect()
    }
}

/// Which packages the working tree covers that `HEAD` does not.
///
/// Those packages pass here and fail on the pull request, because the file
/// holding them up never leaves the machine.
fn resting_on_uncommitted_intent(
    in_head: &Covering,
    changes: &Changes,
    workspace: &Workspace,
    files: &[BumpFile],
    classified: &BTreeMap<PackageId, Standing>,
    committed: &Coverage,
) -> Vec<OffDisk> {
    let already: BTreeSet<PackageId> = committed
        .uncovered()
        .map(|package| package.id().package_id())
        .collect();
    answer(changes, workspace, in_head, classified)
        .uncovered()
        .map(|package| package.id().package_id())
        .filter(|id| !already.contains(id))
        .map(|id| OffDisk {
            // Every disk file covering this package is load-bearing: `id` came
            // out of the answer computed from `in_head`, so none of those
            // covers it. An edited file appears here as readily as one `HEAD`
            // has never seen — both are coverage a pull request will not get.
            files: files
                .iter()
                .filter(|file| covers(file, &id))
                .map(|file| format!("{BUMP_DIR}/{}", file.id))
                .collect(),
            package: id,
        })
        .collect()
}

/// Whether a bump file's own content covers `id`: named outright, or by the
/// empty frontmatter that covers whatever changed.
fn covers(file: &BumpFile, id: &PackageId) -> bool {
    file.entries.is_empty() || file.entries.iter().any(|(covered, _)| covered == id)
}

const BUMP_DIR: &str = ".changeset";

fn is_intent_path(path: &str) -> bool {
    let path = path.trim_start_matches("./");
    path == BUMP_DIR
        || path
            .strip_prefix(BUMP_DIR)
            .is_some_and(|rest| rest.starts_with('/'))
}

/// A bump file's identity is its bare name, so a listed path becomes one by
/// dropping the directory. `None` for anything nested deeper, which is not a
/// bump file the plan could have read.
fn bump_file_name(path: &str) -> Option<&str> {
    let rest = path.trim_start_matches("./").strip_prefix(BUMP_DIR)?;
    let name = rest.strip_prefix('/')?;
    (!name.contains('/')).then_some(name)
}

#[cfg(test)]
mod tests {
    use oakum::plan::{BumpLevel, Ecosystem, ResolvesDependenciesAt};
    use semver::Version;

    use super::super::git::Reply;
    use super::*;

    const STATUS: &str = "status --porcelain -z";
    const DIFF: &str = "diff --name-only";
    const SHALLOW: &str = "rev-parse --is-shallow-repository";
    const RESOLVE: &str = "rev-parse --verify";
    const COMMITS: &str = "log --name-status";
    const COUNT: &str = "rev-list --count";

    fn heard(stdout: &'static str) -> Result<Vec<String>, CliError> {
        uncommitted_paths(&Git::answering([(STATUS, Reply::said(stdout))]))
    }

    /// `log` names commits `c1`, `c2`, `m`, `p1` and `p2`, spelled out here as
    /// the 40-digit hashes git writes.
    fn released(log: &str) -> Result<BTreeSet<String>, CliError> {
        // The one `\x01` inside a path in these logs follows an `x`.
        let headers = log.matches('\u{1}').count() - log.matches("x\u{1}").count();
        released_counting(log, headers)
    }

    fn released_counting(log: &str, count: usize) -> Result<BTreeSet<String>, CliError> {
        released_by(log, count, true)
    }

    /// As [`released`], `c1` alone moving a version, and only when `moved`.
    fn released_by(log: &str, count: usize, moved: bool) -> Result<BTreeSet<String>, CliError> {
        let mut spelled = log.replace("\u{1}m ", &format!("\u{1}{} ", "e".repeat(40)));
        for (name, digit) in [("c1", "1"), ("c2", "2"), ("p1", "a"), ("p2", "b")] {
            spelled = spelled.replace(name, &digit.repeat(40));
        }
        let git = Git::answering([
            (COMMITS, Reply::said(spelled)),
            (COUNT, Reply::said(format!("{count}\n"))),
        ]);
        written_only_by_version_commits(
            &git,
            "v0.1.0",
            &BTreeSet::from(["", "alpha", "beta"]),
            |commit, dir| {
                Ok(if moved && commit.hash == "1".repeat(40) {
                    let manifest = |name: &str| {
                        if dir.is_empty() {
                            name.to_owned()
                        } else {
                            format!("{dir}/{name}")
                        }
                    };
                    BTreeSet::from([manifest("Cargo.toml"), manifest("package.json")])
                } else {
                    BTreeSet::new()
                })
            },
        )
    }

    const VERSION: &str =
        "\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0alpha/Cargo.toml\0M\0alpha/CHANGELOG.md\0";

    #[test]
    fn a_version_commit_excuses_only_what_it_wrote_for_a_package_it_released() {
        let both = BTreeSet::from([
            String::from("alpha/CHANGELOG.md"),
            String::from("alpha/Cargo.toml"),
        ]);
        assert_eq!(released(VERSION).expect("read"), both);
        for (log, why) in [
            (
                "\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0alpha/Cargo.toml\0M\0alpha/src/lib.rs\0",
                "no changelog written: alpha was not released",
            ),
            (
                "\u{1}m p1 p2\0\nD\0.changeset/a.md\0M\0alpha/Cargo.toml\0M\0alpha/CHANGELOG.md\0",
                "a merge is never a version commit",
            ),
            (
                "\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0alpha/fixtures/package.json\0M\0alpha/fixtures/CHANGELOG.md\0",
                "a directory that is no package's",
            ),
            (
                "\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0alpha/Cargo.toml\0D\0alpha/CHANGELOG.md\0",
                "deleting the changelog is not writing it",
            ),
            (
                "\u{1}m p1 p2\0\nM\0alpha/x\u{1}y\0D\0.changeset/a.md\0M\0alpha/Cargo.toml\0M\0alpha/CHANGELOG.md\0",
                "a path holding \\x01 does not split the merge into a commit of its own",
            ),
        ] {
            assert!(released(log).expect("read").is_empty(), "{why}");
        }

        assert!(
            released_by(VERSION, 1, false).expect("read").is_empty(),
            "a commit that moved no version released nothing"
        );
        let no_bump_file = "\u{1}c1 p1\0\nM\0alpha/Cargo.toml\0M\0alpha/CHANGELOG.md\0";
        assert_eq!(
            released(no_bump_file).expect("read"),
            both,
            "a release made only of dependency updates consumes no bump file"
        );

        let root = "\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0Cargo.toml\0M\0CHANGELOG.md\0";
        assert_eq!(
            released(root).expect("root package"),
            BTreeSet::from([String::from("CHANGELOG.md"), String::from("Cargo.toml")])
        );
        assert!(released("\u{1}c1 \0\nA\0alpha/src/lib.rs\0")
            .expect("a root commit has no parents")
            .is_empty());

        let beta_by_hand ="\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0alpha/Cargo.toml\0M\0alpha/CHANGELOG.md\0M\0beta/Cargo.toml\0";
        assert_eq!(released(beta_by_hand).expect("read"), both);

        let edited_after =
            "\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0alpha/Cargo.toml\0M\0alpha/CHANGELOG.md\0\u{1}c2 c1\0\nM\0alpha/CHANGELOG.md\0";
        assert_eq!(
            released(edited_after).expect("read"),
            BTreeSet::from([String::from("alpha/Cargo.toml")])
        );
    }

    /// A look that could not run is `unverified`, never "no version commit".
    #[test]
    fn a_commit_listing_that_fails_or_stops_short_is_unverified() {
        let failed = Git::answering([(COMMITS, Reply::failed(128, "fatal: bad revision"))]);
        let err = written_only_by_version_commits(&failed, "v0.1.0", &BTreeSet::new(), |_, _| {
            Ok(BTreeSet::new())
        })
        .expect_err("failed");
        assert_eq!(err.exit_code(), 2, "{err}");
        for log in [
            "\u{1}c1 p1\0\nD\0.changeset/a.md\0M\0",
            "\u{1}not-a-hash\0\nM\0alpha/Cargo.toml\0",
            "M\0alpha/Cargo.toml\0",
            "\u{1}c1 p1\0\nnot a status\0alpha/Cargo.toml\0",
        ] {
            let err = released(log).expect_err(log);
            assert_eq!(err.exit_code(), 2, "{log:?}: {err}");
        }
        // Cut on a record boundary: it parses, but holds fewer commits than
        // the range does.
        let err = released_counting(VERSION, 2).expect_err("short");
        assert_eq!(err.exit_code(), 2, "{err}");
    }

    /// Reading `HEAD`'s intent can fail on its own — an unreadable blob, a name
    /// the workspace no longer has — and that failure belongs to this half
    /// alone. Folding it into the worktree's outcome said the working tree
    /// could not be read, which was false, and took the packages changed
    /// outside `HEAD` down with it: a finding the previous release printed
    /// simply vanished.
    #[test]
    fn a_head_intent_that_cannot_be_read_keeps_the_rest_of_the_answer() {
        let git = Git::answering([
            (SHALLOW, Reply::said("false")),
            (RESOLVE, Reply::said("v0.1.0")),
            (COMMITS, Reply::said("")),
            (COUNT, Reply::said("0\n")),
            (DIFF, Reply::said("")),
            (
                STATUS,
                Reply::said("?? .changeset/cover.md\0 M demo/src/lib.rs\0"),
            ),
            (
                "rev-parse HEAD",
                Reply::said("cafebabecafebabecafebabecafebabecafebabe"),
            ),
            ("ls-tree", Reply::said(".changeset/cover.md\0")),
            ("cat-file --batch", Reply::failed(128, "fatal: bad object")),
            ("cat-file blob", Reply::failed(128, "fatal: bad object")),
        ]);
        // Two packages so the two halves are about different ones: `demo` is
        // changed outside `HEAD` with nothing covering it, and the disk intent
        // that triggers the `HEAD` read names `other`.
        let workspace = Workspace::new([member("demo"), member("other")]).expect("workspace");
        // Disk intent, because that is what makes the `HEAD` comparison worth
        // asking for; with none there is nothing a pull request could be
        // missing, and the look is correctly skipped.
        let files = Vec::from([BumpFile {
            id: String::from("cover.md"),
            entries: Vec::from([(PackageId::new(Ecosystem::Cargo, "other"), BumpLevel::Patch)]),
            note: String::from("note"),
        }]);
        let uncovered = changed_by_standing_and_unseen(
            &git,
            &workspace,
            &Covering::ChangeFiles {
                files,
                commits: BranchCommits::default(),
            },
            Some("v0.1.0"),
            Some(&BranchBumpFiles::default()),
            |_| Standing::Managed,
            |_| Ok(None),
        )
        .expect("the committed half still answers");
        let worktree = uncovered
            .outside_head
            .expect("the worktree itself read fine");

        let err = worktree
            .covered_off_disk
            .as_ref()
            .expect_err("`HEAD`'s intent could not be read");
        assert!(err.to_string().contains("bad object"), "{err}");
        let lines = worktree.lines(|_| String::from("add a bump file"));
        assert!(
            lines
                .iter()
                .any(|line| line.contains("intent `HEAD` carries could not be read")),
            "it names what actually failed: {lines:?}"
        );
        assert!(
            lines
                .iter()
                .any(|line| line.contains("demo (cargo): changed outside `HEAD`")),
            "and the half that did answer still says so: {lines:?}"
        );
    }

    /// A blob is read exactly as git stored it. `Git::text` trims, which is
    /// right for a hash and wrong here: a bump file whose frontmatter does not
    /// start at byte zero is malformed to the loader that reads the disk copy,
    /// and trimming would let `HEAD`'s copy parse under a different rule than
    /// the copy it is being compared against.
    ///
    /// Malformed travels as a refusal rather than as an empty answer. Dropping
    /// it looks safe and is not: where another file already covers the package,
    /// the loss shows up as no difference at all, so the run says nothing while
    /// the pull request refuses.
    #[test]
    fn head_intent_is_judged_by_the_same_rules_as_the_disk_copy() {
        for body in [
            "\n---\ndemo: patch\n---\nnote\n",
            "not frontmatter at all\n",
        ] {
            let git = Git::answering([
                (
                    "rev-parse HEAD",
                    Reply::said("cafebabecafebabecafebabecafebabecafebabe"),
                ),
                ("ls-tree", Reply::said(".changeset/cover.md\0")),
                (
                    "cat-file --batch",
                    Reply::said(format!("o1 blob {}\n{body}\n", body.len())),
                ),
            ]);
            let err = intent_in_head(&git, &one_package())
                .expect_err("a body the disk loader would refuse is refused here");
            // The class, which is what travels; the caller reports it without
            // gating, so no process ever exits on it.
            assert_eq!(err.exit_code(), 2, "{body:?}: {err}");
            assert!(err.to_string().contains("cannot parse"), "{body:?}: {err}");
        }
    }

    /// stdin cannot frame a name holding a newline, so that one is read on its
    /// own and the rest in one batch, in the listing's order.
    #[test]
    fn a_bump_file_named_with_a_newline_is_read_on_its_own() {
        let body = |level: &str| format!("---\ndemo: {level}\n---\n\nnote\n");
        let patch = body("patch");
        let git = Git::answering([
            (
                "rev-parse HEAD",
                Reply::said("cafebabecafebabecafebabecafebabecafebabe"),
            ),
            (
                "ls-tree",
                Reply::said(".changeset/a\nb.md\0.changeset/c.md\0"),
            ),
            (
                "cat-file --batch",
                Reply::said(format!("o1 blob {}\n{patch}\n", patch.len())),
            ),
            ("cat-file blob", Reply::said(body("minor"))),
        ]);
        let files = intent_in_head(&git, &one_package()).expect("both read");
        let read: Vec<(&str, BumpLevel)> = files
            .iter()
            .map(|file| (file.id.as_str(), file.entries[0].1))
            .collect();
        assert_eq!(
            read,
            [("a\nb.md", BumpLevel::Minor), ("c.md", BumpLevel::Patch)]
        );
    }

    /// A bump file is named by its bare filename, so only a direct child of the
    /// directory can be one.
    #[test]
    fn only_a_direct_child_of_the_bump_directory_is_a_bump_file() {
        assert_eq!(bump_file_name(".changeset/demo.md"), Some("demo.md"));
        assert_eq!(bump_file_name("./.changeset/demo.md"), Some("demo.md"));
        assert_eq!(bump_file_name(".changeset/nested/demo.md"), None);
        assert_eq!(bump_file_name(".changesetish/demo.md"), None);
        assert_eq!(bump_file_name("src/lib.rs"), None);
    }

    fn member(name: &str) -> Package {
        Package::new(
            PackageId::new(Ecosystem::Cargo, name),
            Version::new(0, 1, 0),
            ResolvesDependenciesAt::Install,
            true,
            Vec::new(),
        )
        .with_manifest_dir(name)
    }

    fn one_package() -> Workspace {
        Workspace::new([member("demo")]).expect("workspace")
    }

    fn releasing(
        hash: &str,
        subject: &str,
        kind: Option<&str>,
        level: BumpLevel,
    ) -> ReleasingCommit {
        ReleasingCommit::new(
            hash.to_owned(),
            subject.to_owned(),
            kind.map(str::to_owned),
            level,
        )
        .expect("releases")
    }

    /// The fix asks for the highest level among the commits asking for one.
    #[test]
    fn the_fix_asks_for_the_highest_level_a_commit_asks_for() {
        let commits = vec![
            releasing("aaaaaaa111", "tweak demo", None, BumpLevel::Patch),
            releasing(
                "bbbbbbb222",
                "feat!: drop x",
                Some("feat"),
                BumpLevel::Major,
            ),
            releasing("ccccccc333", "fix: a bug", Some("fix"), BumpLevel::Patch),
        ];
        let id = PackageId::new(Ecosystem::Cargo, "demo");
        let files = Covering::ChangeFiles {
            files: Vec::new(),
            commits: BranchCommits::default(),
        };
        assert_eq!(
            files.fix(&id, &commits).as_deref(),
            Some("oakum add --packages demo:major")
        );
        assert_eq!(
            files.fix(&id, &commits[2..]).as_deref(),
            Some("oakum add --packages demo:patch")
        );
        assert_eq!(
            files.fix(&id, &[]).as_deref(),
            Some("oakum add --packages demo:<level>")
        );
        let commits_only = Covering::CommitsOnly {
            commits: Vec::new(),
            types: CommitTypes::new(),
        };
        assert_eq!(
            commits_only.fix(&id, &commits),
            None,
            "only a commit covers"
        );
    }

    /// Each listing that fails is a look that did not happen, not a branch
    /// that touched no bump file.
    #[test]
    fn a_branch_whose_bump_files_cannot_be_listed_is_unverified() {
        let fork = "cafebabecafebabecafebabecafebabecafebabe";
        let cases = [
            Git::answering([
                (SHALLOW, Reply::said("false")),
                ("merge-base", Reply::failed(128, "fatal: bad object")),
            ]),
            Git::answering([
                (SHALLOW, Reply::said("false")),
                ("merge-base", Reply::said(fork)),
                ("rev-parse HEAD", Reply::failed(128, "fatal: bad head")),
            ]),
            Git::answering([
                (SHALLOW, Reply::said("false")),
                ("merge-base", Reply::said(fork)),
                ("rev-parse HEAD", Reply::said(fork)),
                ("ls-tree", Reply::failed(128, "fatal: bad tree")),
            ]),
            Git::answering([
                (SHALLOW, Reply::said("false")),
                ("merge-base", Reply::said(fork)),
                ("rev-parse HEAD", Reply::said(fork)),
                ("ls-tree", Reply::said("")),
                (DIFF, Reply::failed(128, "fatal: bad revision")),
            ]),
        ];
        for git in cases {
            let Err(err) = BranchBumpFiles::read(&git, "main") else {
                panic!("an unread listing read as nothing touched");
            };
            assert_eq!(err.exit_code(), 2, "{err}");
            assert!(err.to_string().contains("fatal: bad"), "{err}");
        }
    }

    /// Path decides, so a file the branch touched counts whatever its content
    /// and one it left alone never does, committed or not.
    #[test]
    fn only_bump_files_the_branch_touched_are_its_own() {
        let sha = "cafebabecafebabecafebabecafebabecafebabe";
        // `deleted.md` left the tree on this branch; `pending.md` is only named
        // outside `.changeset`, which is not touching it.
        let git = Git::answering([
            (SHALLOW, Reply::said("false")),
            ("merge-base", Reply::said(sha)),
            ("rev-parse HEAD", Reply::said(sha)),
            (
                "ls-tree",
                Reply::said(".changeset/committed.md\0.changeset/pending.md\0"),
            ),
            (
                DIFF,
                Reply::said(
                    ".changeset/committed.md\0.changeset/deleted.md\0demo/src/lib.rs\0\
                     docs/pending.md\0.changeset/nested/pending.md\0",
                ),
            ),
            (STATUS, Reply::said("?? .changeset/new.md\0")),
        ]);
        let branch = BranchBumpFiles::read(&git, "main").expect("listed");
        let file = |id: &str| BumpFile {
            id: String::from(id),
            entries: Vec::from([(PackageId::new(Ecosystem::Cargo, "demo"), BumpLevel::Patch)]),
            note: String::from("note"),
        };
        let disk = [
            file("committed.md"),
            file("new.md"),
            file("pending.md"),
            file("deleted.md"),
        ];

        let own: Vec<String> = branch.own(&disk).into_iter().map(|f| f.id).collect();
        assert_eq!(own, ["committed.md", "new.md"]);
        let in_head: Vec<String> = branch
            .own_in_head(disk.to_vec())
            .into_iter()
            .map(|f| f.id)
            .collect();
        assert_eq!(in_head, ["committed.md"]);

        let unreadable_tree = Git::answering([
            (SHALLOW, Reply::said("false")),
            ("merge-base", Reply::said(sha)),
            ("rev-parse HEAD", Reply::said(sha)),
            ("ls-tree", Reply::said(".changeset/committed.md\0")),
            (
                DIFF,
                Reply::said(".changeset/committed.md\0.changeset/deleted.md\0"),
            ),
            (STATUS, Reply::failed(128, "fatal: bad index")),
        ]);
        let branch = BranchBumpFiles::read(&unreadable_tree, "main")
            .expect("an unreadable worktree leaves the committed answer");
        let own: Vec<String> = branch.own(&disk).into_iter().map(|f| f.id).collect();
        assert_eq!(own, ["committed.md"]);
    }

    /// The committed half is already answered by the time the worktree is
    /// read, so a `git status` that cannot run must not take it down. Measured
    /// before this held: exit 1 naming the package became exit 2 naming
    /// nothing.
    ///
    /// Here rather than only in `tests/it/check/`, where the same claim needs a
    /// PATH shim and so is `#[cfg(unix)]` — this is the half that runs on the
    /// Windows job.
    #[test]
    fn a_worktree_that_cannot_be_read_keeps_the_committed_answer() {
        let git = Git::answering([
            (SHALLOW, Reply::said("false")),
            (RESOLVE, Reply::said("v0.1.0")),
            (COMMITS, Reply::said("")),
            (COUNT, Reply::said("0\n")),
            (DIFF, Reply::said("demo/src/lib.rs\0")),
            (STATUS, Reply::failed(128, "fatal: status is not available")),
        ]);
        let workspace = one_package();
        let uncovered = changed_by_standing_and_unseen(
            &git,
            &workspace,
            &Covering::ChangeFiles {
                files: Vec::new(),
                commits: BranchCommits::default(),
            },
            Some("v0.1.0"),
            Some(&BranchBumpFiles::default()),
            |_| Standing::Managed,
            |_| Ok(None),
        )
        .expect("the committed half still answers");

        assert_eq!(
            uncovered
                .committed
                .uncovered()
                .map(|package| package.id().package_id())
                .collect::<Vec<_>>(),
            [PackageId::new(Ecosystem::Cargo, "demo")],
            "the commits established this before the worktree was read"
        );
        let err = uncovered
            .outside_head
            .expect_err("the worktree could not be read");
        assert_eq!(err.exit_code(), 2, "{err}");
        // The wording too: a child that failed and one that listed only part of
        // the tree are both exit 2, so the class alone cannot tell them apart.
        assert!(err.to_string().contains("failed: exit 128"), "{err}");
    }

    /// Every state that is not a commit reaches the caller the same way: the
    /// look reads commits, so staged, edited and untracked are one class.
    #[test]
    fn each_status_pair_yields_its_path() {
        assert_eq!(
            heard("M  staged.rs\0 M edited.rs\0?? new.rs\0A  added.rs\0").expect("parsed"),
            ["staged.rs", "edited.rs", "new.rs", "added.rs"]
        );
    }

    /// A rename writes the origin path as its own field with no status pair of
    /// its own (measured, git 2.55). Read as an entry it would be attributed by
    /// the characters after its third, which for `src/main.rs` is `/main.rs`.
    ///
    /// Copies travel the same way. `status` does not detect them unless someone
    /// configures it to, so the `C` arm is defence — but narrowing the set to
    /// `R` alone passes every other test, which makes this the only thing
    /// holding it.
    #[test]
    fn a_rename_or_copy_contributes_both_of_its_names() {
        assert_eq!(
            heard("R  beta/moved.rs\0alpha/origin.rs\0 M other.rs\0").expect("parsed"),
            ["beta/moved.rs", "alpha/origin.rs", "other.rs"]
        );
        assert_eq!(
            heard("C  beta/copy.rs\0alpha/origin.rs\0").expect("parsed"),
            ["beta/copy.rs", "alpha/origin.rs"]
        );
    }

    /// The listing stopped after a rename and its origin never arrived — a
    /// child killed mid-write, a full disk. Returning the names that did arrive
    /// would report a partial tree as the whole one at exit 0.
    #[test]
    fn a_rename_with_no_origin_field_is_unverified() {
        let err = heard("R  beta/moved.rs\0").expect_err("refused");
        assert_eq!(err.exit_code(), 2, "{err}");
        assert!(err.to_string().contains("no origin path"), "{err}");
    }

    /// Which side of the listing a path falls on. Intent is read off disk by
    /// the half this one compares against, so a bump file is never a change to
    /// the package it names; it is the other question's evidence, which is why
    /// the parser hands it through instead of dropping it.
    #[test]
    fn intent_is_told_from_change() {
        for path in [".changeset/demo.md", "./.changeset/demo.md", ".changeset"] {
            assert!(is_intent_path(path), "{path}");
        }
        for path in [
            "src/lib.rs",
            ".changesetish/demo.md",
            "a/.changeset/demo.md",
        ] {
            assert!(!is_intent_path(path), "{path}");
        }
    }

    #[test]
    fn a_clean_tree_lists_nothing() {
        assert_eq!(heard("").expect("parsed"), Vec::<String>::new());
    }

    /// A shape this cannot read is a tree it cannot compare with `HEAD`, which
    /// is `unverified` and not an empty answer: silently dropping the record
    /// would report a clean tree for one it never parsed.
    ///
    /// Both shapes, because they fail different guards: `??` is too short to
    /// split, and `?? ` splits into a status pair and an empty path. Without
    /// the second, the emptiness check is unreachable from any input and reads
    /// as load-bearing while holding nothing.
    #[test]
    fn a_record_without_a_path_is_unverified() {
        for record in ["??\0", "?? \0"] {
            let err = heard(record).expect_err("refused");
            assert_eq!(err.exit_code(), 2, "{record:?}: {err}");
            assert!(
                err.to_string().contains("not a status pair and a path"),
                "{err}"
            );
        }
    }
}