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
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
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
//! Every git operation oakum performs, and the axes that describe one.
//!
//! [`Op`] is closed so the set of git operations in the crate is a list one can
//! read, and [`Op::shape`] is one table with a row per operation, so no
//! operation can state its argv and leave its outcome class, name, remote, or
//! operand to a default. The runner in the parent module reads a shape; it
//! never asks an operation a question one axis at a time.

use super::env::TransportUnknown;
use super::{CliError, Commit};

/// A path as a regex literal. `.` is the character that matters here — an
/// unescaped one matches `xbumpy` as readily as `.bumpy`.
fn regex_literal(path: &str) -> String {
    let mut escaped = String::with_capacity(path.len() * 2);
    for ch in path.chars() {
        if !ch.is_alphanumeric() && ch != '_' {
            escaped.push('\\');
        }
        escaped.push(ch);
    }
    escaped
}

/// Where a failed child lands in the three-outcome vocabulary (AGENTS.md).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Outcome {
    /// Informs a verification, so a failure to look is `unverified` — never
    /// silently "nothing to report".
    Verification,
    /// Does work, so a failure is a plain error.
    Action,
}

/// Which way a remote operation talks to its remote. A push and a fetch can go
/// to different places, so an operation judged by the wrong URL gets a note
/// naming a transport it never uses. Whether a remote is contacted at all is
/// the `Option` around this, decided in [`Op::shape`].
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub(super) enum Direction {
    Fetch,
    Push,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) struct Contact<'a> {
    pub(super) remote: &'a str,
    pub(super) direction: Direction,
}

impl Contact<'_> {
    /// Keyed by both: a remote can fetch over one transport and push over
    /// another, so by name alone the fetch note swallows the push one.
    pub(super) fn key(self) -> (String, Direction) {
        (self.remote.to_owned(), self.direction)
    }
}

/// What a successful child writes to stdout, which is what decides the meaning
/// of one that wrote nothing.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Answer {
    /// Always. Silence from a child that exited 0 means it never answered.
    Always,
    /// Sometimes: no tags, no remotes, nothing changed, a clean worktree. The
    /// emptiness is a real answer, but not one a diagnostic leaves standing.
    Sometimes,
    /// Never — no refusal rule is drawn from silence, so a child that exited 0
    /// having written nothing stands. A successful `git push` writes its whole
    /// report to stderr; a clean `status` listing is simply empty.
    Never,
}

/// What a listing that must be whole is listing, which decides the diagnostic
/// that says git skipped part of it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Whole {
    Tree,
    Refs,
}

impl Whole {
    pub(super) fn skipped(self, said: &str) -> bool {
        match self {
            Self::Tree => super::hides_part_of_the_tree(said),
            Self::Refs => super::skips_a_ref(said),
        }
    }

    pub(super) const fn part(self) -> &'static str {
        match self {
            Self::Tree => "part of the tree",
            Self::Refs => "some of the refs",
        }
    }
}

/// What the runner needs about an operation beyond its remote, which
/// [`OpShape::contact`] carries.
pub(super) struct Spec {
    outcome: Outcome,
    /// The silence rule. Private, with the rest: a consumer owns its
    /// `OpShape` by value, so a public field lets one flip a rule in place —
    /// measured turning the partial-listing refusal into an accepted answer.
    answer: Answer,
    /// Whether the listing has to be whole: on a child that exited 0, a
    /// diagnostic naming tree git could not walk disqualifies what it listed,
    /// stdout or no stdout.
    ///
    /// Orthogonal to [`Self::answer`], which keys on emptiness and so answers
    /// "is anything there" and cannot express "is this all of it". `git status`
    /// warns and continues on a directory it cannot open — measured: exit 0,
    /// one record on stdout, `warning: could not open directory
    /// 'beta/hidden/': Permission denied` on stderr, and everything beneath
    /// that directory missing. Judged by emptiness that reads as a complete
    /// tree, and the package whose only change lived there is passed over in
    /// silence.
    whole: Option<Whole>,
    /// Free-form commit text, which git does not promise is UTF-8: a commit
    /// object written verbatim by another tool carries raw bytes that `git log`
    /// passes straight through. Replacing one with U+FFFD beats refusing to read
    /// the message at all.
    lossy: bool,
    /// Run with `GIT_NO_LAZY_FETCH=1`: a partial clone missing an object fails
    /// the read rather than fetch it into `.git`. Older git ignores the
    /// variable and fetches.
    offline: bool,
}

impl Spec {
    pub(super) fn answer(&self) -> Answer {
        self.answer
    }

    pub(super) fn whole(&self) -> Option<Whole> {
        self.whole
    }

    pub(super) fn lossy(&self) -> bool {
        self.lossy
    }

    pub(super) fn offline(&self) -> bool {
        self.offline
    }

    const LOOK: Self = Self {
        outcome: Outcome::Verification,
        answer: Answer::Sometimes,
        whole: None,
        lossy: false,
        offline: false,
    };
    const OFFLINE_LOOK: Self = Self {
        offline: true,
        ..Self::LOOK
    };
    const ANSWERING_LOOK: Self = Self {
        answer: Answer::Always,
        ..Self::LOOK
    };
    /// [`Op::UncommittedPaths`]'s one diagnostic rule is wholeness, so silence
    /// draws none of its own: a clean tree answered while stderr carried a
    /// warning the wholeness rule passed over is still a clean tree.
    const WHOLE_LOOK: Self = Self {
        answer: Answer::Never,
        whole: Some(Whole::Tree),
        ..Self::LOOK
    };
    /// A check whose answer is what it writes, not what it prints.
    const QUIET_LOOK: Self = Self {
        answer: Answer::Never,
        ..Self::LOOK
    };
    /// A tag listing short by one ref changes which version oakum believes
    /// was last released.
    const REFS_LOOK: Self = Self {
        whole: Some(Whole::Refs),
        ..Self::LOOK
    };
    const ACT: Self = Self {
        outcome: Outcome::Action,
        answer: Answer::Sometimes,
        whole: None,
        lossy: false,
        offline: false,
    };
    const ANSWERING_ACT: Self = Self {
        answer: Answer::Always,
        ..Self::ACT
    };
    const LOSSY_ACT: Self = Self {
        lossy: true,
        ..Self::ACT
    };
    /// Work that answers through its exit code alone.
    const PERFORM: Self = Self {
        answer: Answer::Never,
        ..Self::ACT
    };
}

/// The trailer half of [`Op::CommitMessage`]'s format. A git too old to know
/// it echoes the specifier verbatim at exit 0 (measured on 2.55 with an
/// unknown option), which is what `commit_text`'s guard catches: the whole
/// trailers half equals the atom while the message itself does not carry it.
/// A genuine trailer value quoting the specifier appears in both halves, so
/// it stays a value.
pub(super) const SKIP_CHECKS_ATOM: &str = "%(trailers:key=skip-checks,valueonly,unfold)";

/// Every git operation oakum performs.
#[derive(Clone, Copy, Debug)]
pub(in crate::cli) enum Op<'a> {
    /// Tags reachable from HEAD with their peeled identity (ADR-0014).
    ReachableTags,
    /// Every ref under `refs/tags` with its recorded object: a `--merged`
    /// walk silently drops a ref whose object is missing or unreachable
    /// (measured, git 2.55), so only this listing sees those tags.
    AllTags,
    /// The ref store's own consistency check, git 2.47 and later. An
    /// unreadable `refs/tags` makes a tag listing empty and silent (measured,
    /// git 2.56); this is what says so.
    VerifyRefs,
    /// The ref backend and the common git dir, one per line. A git before
    /// 2.45 echoes `--show-ref-format` back, and cannot open a reftable
    /// repository at all.
    RefStore,
    /// This worktree's own git dir, which holds its own reftable stack when
    /// it is a linked worktree.
    GitDir,
    IsShallow,
    /// Each remote's url, `tagOpt` and fetch refspecs: what decides which
    /// tags a fetch brings.
    RemoteTagConfig,
    /// Each remote's `partialclonefilter`: what a partial clone left out.
    PartialCloneFilters,
    /// Whether any remote may supply objects this repository lacks.
    Promisors,
    RemoteNames,
    AdvertisedTags {
        remote: &'a str,
    },
    /// Paths changed since `from`, NUL-separated.
    ///
    /// Reads commits: `from...HEAD`. A change that is only staged or only
    /// edited is not in this listing, which is what [`Self::UncommittedPaths`]
    /// exists to say out loud. Rename detection would drop a move's old path
    /// and read blobs a partial clone lacks.
    ChangedPaths {
        from: &'a str,
    },
    /// Every path the worktree and the index hold that `HEAD` does not, each
    /// preceded by its two porcelain status letters and NUL-separated,
    /// untracked files included.
    ///
    /// The companion to [`Self::ChangedPaths`]: `check` reads changed packages
    /// from commits and intent from the working tree, so only this listing can
    /// tell a reader which half of their work the run could not see.
    ///
    /// Separate from [`Self::WorktreeStatus`], which asks whether the tree is
    /// dirty at all before `release` acts. This one is read by a verification,
    /// so a failure to run it is `unverified` rather than an error, and it
    /// carries `-z` because it is parsed for paths rather than emptiness.
    UncommittedPaths,
    /// Tracked files whose content mentions `dir`, NUL-separated, skipping
    /// `dir` itself and oakum's own directory.
    ///
    /// Reads the index, not the worktree. Without `--cached` a tracked file
    /// that is not materialized — a sparse checkout's `skip-worktree` entry, or
    /// one `git` cannot stat — is passed over at exit 0 with an incomplete
    /// list, which is the one failure shape no exit code or stderr byte
    /// reports. The cost is that a gate existing only as an unstaged edit is
    /// not seen; for "will this reject oakum's bump files in CI", the indexed
    /// content is the one that answers.
    ///
    /// `dir` is a repository-relative directory path, matched at a token
    /// boundary: the bare name would also match `.bumpyrc` and
    /// `my-app.bumpysomething`, which no reader calls a gate, while the
    /// trailing-slash form misses a gate spelled `grep '^\.bumpy'`. The
    /// trailing-slash form is what the pathspec excludes.
    ///
    /// A `dir` carrying pathspec magic is taken literally by git rather than
    /// rejected, so the exclusion would silently stop excluding — measured, not
    /// inferred. The only caller passes a module constant.
    ///
    /// Exits 1 with nothing written when nothing matches — and also when it
    /// searched nothing at all, which is why the caller asks what there was to
    /// search rather than reading the silence as an answer.
    FilesMentioning {
        dir: &'a str,
    },
    /// Every tracked path, NUL-separated. Exits 0 even when there are none, so
    /// an empty answer is a fact rather than an ambiguous exit code.
    TrackedFiles,
    /// The unmerged entries [`Self::FilesMentioning`] skips in silence
    /// (measured, git 2.56.0), as `mode sha stage<TAB>path` records per stage.
    UnmergedFiles {
        dir: &'a str,
    },
    /// The directory git runs hooks from, root-relative or absolute. Applies
    /// `core.hooksPath` and a linked worktree's common dir (measured, 2.56.0).
    HooksDir,
    GitCommonDir,
    /// [`Self::HooksDir`] under the config of the worktree owning `git_dir`.
    /// `--git-dir`, not `-C`, so a relative `GIT_COMMON_DIR` keeps its base.
    HooksDirOf {
        git_dir: &'a str,
    },
    /// Only the exit status tells set empty (0, a blank line) from unset (1);
    /// a git dir git cannot open is skipped, leaving global and system config
    /// to answer (measured, 2.56.1).
    HooksPathOf {
        git_dir: &'a str,
    },
    Head,
    RemoteUrl {
        remote: &'a str,
    },
    /// Every remote's fetch and push URLs in one child. `remote.<name>.pushurl`
    /// can point somewhere else entirely and can be set more than once —
    /// measured, `remote -v` lists every one, and applies `insteadOf` rewrites
    /// exactly as `get-url` does.
    RemoteUrls,
    MergeBase {
        tip: &'a str,
    },
    /// `hash NUL parents NUL subject NUL body NUL` per commit in `from..HEAD`,
    /// oldest first; every commit `HEAD` reaches when `from` is `None`.
    Commits {
        from: Option<&'a str>,
    },
    /// The paths each listed commit changed, from one child reading the hashes
    /// on stdin: per commit, `\x01<hash>` NUL, a newline, then its paths, each
    /// NUL-terminated. A commit that changed nothing is not listed.
    CommitPaths {
        hashes: &'a [&'a str],
    },
    /// One commit's paths, read when the batch fails so each failure is worded
    /// per commit.
    CommitPath {
        hash: &'a str,
    },
    /// One commit's patch against its first parent with no context lines,
    /// reversed when `reverse` is set, so a revert can be checked against
    /// the commit it names.
    CommitPatch {
        hash: &'a str,
        reverse: bool,
    },
    /// Each commit in `from..HEAD` as `\x01hash parents NUL \n` and its
    /// `status NUL path NUL` pairs, a merge against its first parent. A
    /// verification's read, unlike [`Self::Commits`].
    RangeChanges {
        from: &'a str,
    },
    /// How many commits `from..HEAD` holds, against which [`Self::RangeChanges`]
    /// is checked: output cut on a record boundary parses cleanly.
    RangeCount {
        from: &'a str,
    },
    /// The commit a local tag points at, peeled.
    LocalTagCommit {
        tag: &'a str,
    },
    WorktreeStatus,
    /// The full message of one commit, a NUL, then the values of its
    /// `skip-checks` trailers as git parses them — one child answers both the
    /// bracketed-annotation scan and the trailer question, with git's own
    /// parser as the trailer authority rather than an approximation of it.
    CommitMessage {
        commit: &'a str,
    },
    RefExists {
        reference: &'a str,
    },
    /// Read from the commit itself, so a parent the repository lacks is
    /// still listed; a root lists none.
    Parents {
        commit: &'a Commit,
    },
    EmptyTree,
    ValidRefName {
        reference: &'a str,
    },
    /// Every path under `dir` in one commit's tree, NUL-separated. Exits 0
    /// with nothing written when the directory is absent there (measured, git
    /// 2.55): "nothing there at that commit" is a completed look, not a
    /// failure.
    TreePaths {
        commit: &'a Commit,
        dir: &'a str,
    },
    BlobText {
        commit: &'a Commit,
        path: &'a str,
    },
    /// Each of `paths` at `commit`, from one child: per path, `<oid> <type>
    /// <size>` and a newline, the bytes, and a newline. A path holding a
    /// newline cannot be framed on stdin; [`Self::BlobText`] reads that one.
    Blobs {
        commit: &'a Commit,
        paths: &'a [&'a str],
    },
    /// `package.json` and `Cargo.toml` files in one commit that mention
    /// `name`, each as `<commit>:<path>`, NUL-separated. No match exits 1 in
    /// silence, like [`Self::FilesMentioning`].
    ManifestsNaming {
        commit: &'a Commit,
        name: &'a str,
    },
    /// Each `path` in its `commit`, symlinks followed in that tree, one reply
    /// per stdin query: `<object> blob <size>` and the bytes, or a kind line
    /// (`missing`, `dangling`, `loop`, `notdir`, `symlink` for a link leaving
    /// the repository; measured, git 2.55).
    FollowedBlob {
        queries: &'a [(&'a Commit, &'a str)],
    },
    /// Every entry in `commit`'s tree as `<mode> <type> <object>\t<path>`,
    /// NUL-terminated.
    TreeFiles {
        commit: &'a Commit,
    },
    /// Per object id: `<oid> <type> <size>`, a newline, the bytes and a
    /// newline; or `<oid> missing`.
    Objects {
        objects: &'a [&'a str],
    },
    /// The tree entry for `path` in `commit` as `<mode> <type> <object>\t<path>`:
    /// empty output when absent, a diagnostic and exit 128 when the commit
    /// itself is unknown. The pathspec is literal, so `[` in a path is not a
    /// glob.
    TreeEntry {
        commit: &'a Commit,
        path: &'a str,
    },
    /// The commit that added `path`, as `hash NUL author NUL email NUL
    /// subject`; empty when the file was never committed. `--ignore-missing`
    /// makes an unborn HEAD empty output too rather than exit 128 (measured,
    /// git 2.55). The pathspec is literal.
    FileAddedBy {
        path: &'a str,
    },
    /// Commits along `HEAD`'s first parents that changed any of `paths`,
    /// newest first, one hash per line. A merge counts against its first
    /// parent, so a version a merge brought in names the merge. Pathspecs are
    /// literal.
    FirstParentWriters {
        paths: &'a [&'a str],
    },
    /// The commit slot takes a [`Commit`], not a committish: only an id a git
    /// read produced can name where the one operation that writes a ref points
    /// it, so a tag name cannot compile into the slot.
    AnnotatedTag {
        name: &'a str,
        commit: &'a Commit,
    },
    PushTag {
        remote: &'a str,
        tag: &'a str,
    },
}

/// `Commit` holds a `String`, so no fixture can be `const`; the operation
/// tables are functions for this one slot.
#[cfg(test)]
pub(super) fn fixture_commit() -> &'static Commit {
    static FIXTURE: std::sync::OnceLock<Commit> = std::sync::OnceLock::new();
    FIXTURE.get_or_init(|| Commit(String::from("cafebabe")))
}

/// Every axis of one operation in one row, so a variant cannot state its
/// argv and leave its class, name, contact, or operand to a default.
pub(super) struct OpShape<'a> {
    pub(super) argv: Vec<String>,
    pub(super) spec: Spec,
    /// The subcommand, for diagnostics. Paired with `operand` rather than
    /// rendering the whole argv, which would repeat the flags in every message.
    pub(super) name: &'static str,
    /// The remote this operation contacts and which way. An operation that
    /// contacts a remote but says `None` here spawns a child with no
    /// `BatchMode` and hangs on a prompt.
    pub(super) contact: Option<Contact<'a>>,
    /// What the operation was pointed at, so a failure names which remote or
    /// ref it was. Every value here is oakum's own — a remote name, a ref, a
    /// range — not text git produced.
    pub(super) operand: Option<String>,
    /// What the child reads on stdin; `None` gives it a closed one.
    pub(super) input: Option<String>,
}

impl<'a> Op<'a> {
    /// The whole of one operation. No axis may default silently: a remote
    /// operation that reads as local loses `BatchMode` and hangs, and a read
    /// that reads as an action turns "we could not look" into a plain error.
    // One arm per variant, never a `|` group: an operation appended to a group
    // compiles while stating nothing and inherits whatever its neighbour
    // happened to be.
    #[expect(
        clippy::too_many_lines,
        reason = "a table, one row per operation; it grows with the enum"
    )]
    pub(super) fn shape(&self) -> OpShape<'a> {
        let owned = |parts: &[&str]| parts.iter().map(|part| (*part).to_owned()).collect();
        let named = |value: &str| Some(value.to_owned());
        match *self {
            Self::ReachableTags => OpShape {
                argv: owned(&[
                    "for-each-ref",
                    "--merged=HEAD",
                    "--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objecttype)%00%(*objectname)",
                    "refs/tags",
                ]),
                spec: Spec::REFS_LOOK,
                name: "for-each-ref --merged HEAD",
                contact: None,
                operand: None,
                input: None,
            },
            // Never `%(refname:short)`: a tag shadowed by a same-named branch
            // shortens to `tags/v1` and stops matching (measured, git 2.55).
            Self::AllTags => OpShape {
                argv: owned(&[
                    "for-each-ref",
                    "--format=%(refname)%00%(objectname)",
                    "refs/tags",
                ]),
                spec: Spec::REFS_LOOK,
                name: "for-each-ref refs/tags",
                contact: None,
                operand: None,
                input: None,
            },
            Self::VerifyRefs => OpShape {
                argv: owned(&["refs", "verify"]),
                spec: Spec::QUIET_LOOK,
                name: "refs verify",
                contact: None,
                operand: None,
                input: None,
            },
            Self::RefStore => OpShape {
                argv: owned(&[
                    "rev-parse",
                    "--show-ref-format",
                    "--path-format=absolute",
                    "--git-common-dir",
                ]),
                spec: Spec::ANSWERING_LOOK,
                name: "rev-parse --show-ref-format",
                contact: None,
                operand: None,
                input: None,
            },
            Self::GitDir => OpShape {
                argv: owned(&["rev-parse", "--path-format=absolute", "--git-dir"]),
                spec: Spec::ANSWERING_LOOK,
                name: "rev-parse --git-dir",
                contact: None,
                operand: None,
                input: None,
            },
            Self::IsShallow => OpShape {
                argv: owned(&["rev-parse", "--is-shallow-repository"]),
                spec: Spec::ANSWERING_LOOK,
                name: "rev-parse --is-shallow-repository",
                contact: None,
                operand: None,
                input: None,
            },
            Self::RemoteTagConfig => OpShape {
                argv: owned(&[
                    "config",
                    "-z",
                    "--get-regexp",
                    r"^remote\..*\.(url|tagopt|fetch)$",
                ]),
                spec: Spec::ANSWERING_LOOK,
                name: "config --get-regexp url|tagopt|fetch",
                contact: None,
                operand: None,
                input: None,
            },
            Self::PartialCloneFilters => OpShape {
                argv: owned(&[
                    "config",
                    "-z",
                    "--get-regexp",
                    r"^remote\..*\.partialclonefilter$",
                ]),
                spec: Spec::ANSWERING_LOOK,
                name: "config --get-regexp partialclonefilter",
                contact: None,
                operand: None,
                input: None,
            },
            Self::Promisors => OpShape {
                argv: owned(&[
                    "config",
                    "-z",
                    "--get-regexp",
                    r"^(remote\..*\.promisor|extensions\.partialclone)$",
                ]),
                spec: Spec::ANSWERING_LOOK,
                name: "config --get-regexp promisor",
                contact: None,
                operand: None,
                input: None,
            },
            Self::RemoteNames => OpShape {
                argv: owned(&["remote"]),
                spec: Spec::LOOK,
                name: "remote",
                contact: None,
                operand: None,
                input: None,
            },
            Self::AdvertisedTags { remote } => OpShape {
                argv: owned(&["ls-remote", "--tags", "--", remote]),
                spec: Spec::LOOK,
                name: "ls-remote --tags",
                contact: Some(Contact {
                    remote,
                    direction: Direction::Fetch,
                }),
                operand: named(remote),
                input: None,
            },
            Self::ChangedPaths { from } => OpShape {
                argv: vec![
                    String::from("diff"),
                    String::from("-z"),
                    String::from("--name-only"),
                    String::from("--no-renames"),
                    format!("{from}...HEAD"),
                ],
                spec: Spec::LOOK,
                name: "diff --name-only",
                contact: None,
                operand: Some(format!("{from}...HEAD")),
                input: None,
            },
            Self::UncommittedPaths => OpShape {
                // `--no-optional-locks`: a plain `status` refreshes stale stat
                // information and rewrites `.git/index`, which `check` must not
                // do (measured: one run moved the index, and the flag holds it
                // still while leaving stdout byte-identical).
                //
                // `--ignore-submodules=dirty`: uncommitted content inside a
                // submodule is not something the parent repository can commit,
                // so naming its package would be a line no one can act on. A
                // moved gitlink is a real change and still arrives (measured
                // both ways).
                argv: owned(&[
                    "--no-optional-locks",
                    "-c",
                    "core.fsmonitor=false",
                    "status",
                    "--porcelain",
                    "-z",
                    "--untracked-files=all",
                    "--ignore-submodules=dirty",
                ]),
                spec: Spec::WHOLE_LOOK,
                name: "status --porcelain -z",
                contact: None,
                operand: None,
                input: None,
            },
            Self::FilesMentioning { dir } => OpShape {
                argv: vec![
                    String::from("grep"),
                    String::from("--cached"),
                    String::from("-z"),
                    String::from("--name-only"),
                    String::from("-E"),
                    String::from("-e"),
                    format!("{}([^A-Za-z0-9_]|$)", regex_literal(dir)),
                    String::from("--"),
                    format!(":(exclude){dir}/"),
                    String::from(":(exclude).changeset"),
                ],
                // A match prints the path; no-match and an empty index both
                // exit 1 in silence (measured, git 2.55.0). Exit 0 with
                // nothing on stdout is therefore a wrapper, not a find.
                spec: Spec::ANSWERING_LOOK,
                name: "grep --name-only",
                contact: None,
                operand: Some(dir.to_owned()),
                input: None,
            },
            Self::TrackedFiles => OpShape {
                argv: owned(&["ls-files", "-z"]),
                spec: Spec::LOOK,
                name: "ls-files",
                contact: None,
                operand: None,
                input: None,
            },
            Self::UnmergedFiles { dir } => OpShape {
                argv: vec![
                    String::from("ls-files"),
                    String::from("--unmerged"),
                    String::from("-z"),
                    String::from("--"),
                    format!(":(exclude){dir}/"),
                    String::from(":(exclude).changeset"),
                ],
                spec: Spec::LOOK,
                name: "ls-files --unmerged",
                contact: None,
                operand: Some(dir.to_owned()),
                input: None,
            },
            Self::HooksDir => OpShape {
                argv: owned(&["rev-parse", "--git-path", "hooks"]),
                spec: Spec::ANSWERING_LOOK,
                name: "rev-parse --git-path hooks",
                contact: None,
                operand: None,
                input: None,
            },
            Self::GitCommonDir => OpShape {
                argv: owned(&["rev-parse", "--path-format=absolute", "--git-common-dir"]),
                spec: Spec::ANSWERING_LOOK,
                name: "rev-parse --git-common-dir",
                contact: None,
                operand: None,
                input: None,
            },
            Self::HooksDirOf { git_dir } => OpShape {
                argv: owned(&["--git-dir", git_dir, "rev-parse", "--git-path", "hooks"]),
                spec: Spec::ANSWERING_LOOK,
                name: "rev-parse --git-path hooks of a git dir",
                contact: None,
                operand: None,
                input: None,
            },
            Self::HooksPathOf { git_dir } => OpShape {
                argv: owned(&["--git-dir", git_dir, "config", "--get", "core.hooksPath"]),
                spec: Spec::LOOK,
                name: "config --get core.hooksPath of a git dir",
                contact: None,
                operand: None,
                input: None,
            },
            Self::Head => OpShape {
                argv: owned(&["rev-parse", "HEAD"]),
                spec: Spec::ANSWERING_ACT,
                name: "rev-parse HEAD",
                contact: None,
                operand: None,
                input: None,
            },
            Self::RemoteUrl { remote } => OpShape {
                argv: owned(&["remote", "get-url", "--", remote]),
                spec: Spec::ANSWERING_ACT,
                name: "remote get-url",
                contact: None,
                operand: named(remote),
                input: None,
            },
            Self::RemoteUrls => OpShape {
                argv: owned(&["remote", "-v"]),
                spec: Spec::ACT,
                name: "remote -v",
                contact: None,
                operand: None,
                input: None,
            },
            Self::MergeBase { tip } => OpShape {
                argv: owned(&["merge-base", tip, "HEAD"]),
                spec: Spec::ANSWERING_ACT,
                name: "merge-base",
                contact: None,
                operand: named(tip),
                input: None,
            },
            Self::Commits { from } => {
                let range = from.map_or_else(|| String::from("HEAD"), |from| format!("{from}..HEAD"));
                OpShape {
                    argv: vec![
                        String::from("log"),
                        range.clone(),
                        String::from("--reverse"),
                        String::from("--format=%H%x00%P%x00%s%x00%b%x00"),
                    ],
                    spec: Spec::LOSSY_ACT,
                    name: "log",
                    contact: None,
                    operand: Some(range),
                    input: None,
                }
            }
            Self::CommitPaths { hashes } => OpShape {
                argv: owned(&[
                    "diff-tree",
                    "--stdin",
                    "--name-only",
                    "-z",
                    "-r",
                    "--root",
                    "--format=%x01%H",
                ]),
                spec: Spec::ACT,
                name: "diff-tree --stdin",
                contact: None,
                operand: None,
                input: Some(hashes.iter().flat_map(|hash| [*hash, "\n"]).collect()),
            },
            Self::CommitPath { hash } => OpShape {
                argv: owned(&[
                    "diff-tree",
                    "--no-commit-id",
                    "--name-only",
                    "-z",
                    "-r",
                    "--root",
                    hash,
                ]),
                spec: Spec::ACT,
                name: "diff-tree",
                contact: None,
                operand: named(hash),
                input: None,
            },
            Self::CommitPatch { hash, reverse } => OpShape {
                argv: [
                    "diff-tree",
                    "--no-commit-id",
                    "--no-color",
                    "--no-ext-diff",
                    "--no-prefix",
                    "-p",
                    "-U0",
                    "-r",
                    "--root",
                ]
                .into_iter()
                .chain(reverse.then_some("-R"))
                .chain([hash])
                .map(String::from)
                .collect(),
                spec: Spec::ACT,
                name: "diff-tree -p",
                contact: None,
                operand: named(hash),
                input: None,
            },
            // `--no-show-signature`: `log.showSignature` writes gpg's verdict
            // into stdout, between records.
            Self::RangeChanges { from } => OpShape {
                argv: vec![
                    String::from("log"),
                    String::from("--no-show-signature"),
                    String::from("--format=%x01%H %P"),
                    String::from("--name-status"),
                    String::from("--no-renames"),
                    String::from("--diff-merges=first-parent"),
                    String::from("-z"),
                    format!("{from}..HEAD"),
                ],
                spec: Spec::LOOK,
                name: "log --name-status",
                contact: None,
                operand: Some(format!("{from}..HEAD")),
                input: None,
            },
            Self::RangeCount { from } => OpShape {
                argv: vec![
                    String::from("rev-list"),
                    String::from("--count"),
                    format!("{from}..HEAD"),
                ],
                spec: Spec::ANSWERING_LOOK,
                name: "rev-list --count",
                contact: None,
                operand: Some(format!("{from}..HEAD")),
                input: None,
            },
            Self::LocalTagCommit { tag } => OpShape {
                argv: vec![
                    String::from("rev-parse"),
                    String::from("--verify"),
                    String::from("--quiet"),
                    format!("refs/tags/{tag}^{{}}"),
                ],
                spec: Spec::ANSWERING_ACT,
                name: "rev-parse --verify refs/tags",
                contact: None,
                operand: named(tag),
                input: None,
            },
            // A `core.fsmonitor` hook that cannot be executed makes git fall
            // back, answer correctly, and write `fatal: cannot exec ...` to
            // stderr while exiting 0 — indistinguishable from a status that
            // never ran. Overriding the setting removes the diagnostic and
            // leaves the answer byte-identical (measured both clean and dirty).
            Self::WorktreeStatus => OpShape {
                argv: owned(&[
                    "-c",
                    "core.fsmonitor=false",
                    "status",
                    "--porcelain",
                    "--untracked-files=all",
                ]),
                spec: Spec::ACT,
                name: "status --porcelain",
                contact: None,
                operand: None,
                input: None,
            },
            Self::CommitMessage { commit } => OpShape {
                argv: vec![
                    String::from("log"),
                    String::from("-1"),
                    format!("--format=%B%x00{SKIP_CHECKS_ATOM}"),
                    String::from(commit),
                ],
                spec: Spec::LOSSY_ACT,
                name: "log -1",
                contact: None,
                operand: named(commit),
                input: None,
            },
            // Without `--quiet`, an absent ref exits 128 with a diagnostic —
            // the same shape as an unreadable repository.
            Self::RefExists { reference } => OpShape {
                argv: owned(&["rev-parse", "--verify", "--quiet", reference]),
                spec: Spec::ANSWERING_ACT,
                name: "rev-parse --verify",
                contact: None,
                operand: named(reference),
                input: None,
            },
            Self::Parents { commit } => OpShape {
                argv: vec![String::from("rev-parse"), format!("{}^@", commit.as_str())],
                spec: Spec::LOOK,
                name: "rev-parse ^@",
                contact: None,
                operand: Some(commit.as_str().to_owned()),
                input: None,
            },
            Self::EmptyTree => OpShape {
                argv: owned(&["hash-object", "-t", "tree", "--stdin"]),
                spec: Spec::ANSWERING_LOOK,
                name: "hash-object -t tree",
                contact: None,
                operand: None,
                input: Some(String::new()),
            },
            Self::ValidRefName { reference } => OpShape {
                argv: vec![
                    String::from("check-ref-format"),
                    format!("refs/tags/{reference}"),
                ],
                spec: Spec::PERFORM,
                name: "check-ref-format",
                contact: None,
                operand: named(reference),
                input: None,
            },
            Self::TreePaths { commit, dir } => OpShape {
                argv: vec![
                    String::from("ls-tree"),
                    String::from("--name-only"),
                    String::from("-r"),
                    String::from("-z"),
                    commit.as_str().to_owned(),
                    String::from("--"),
                    format!("{dir}/"),
                ],
                spec: Spec::LOOK,
                name: "ls-tree",
                contact: None,
                operand: Some(format!("{}:{dir}", commit.as_str())),
                input: None,
            },
            Self::ManifestsNaming { commit, name } => OpShape {
                argv: vec![
                    String::from("grep"),
                    String::from("-z"),
                    String::from("-l"),
                    String::from("-F"),
                    String::from("-e"),
                    (*name).to_owned(),
                    commit.as_str().to_owned(),
                    String::from("--"),
                    String::from(":(glob)**/package.json"),
                    String::from(":(glob)**/Cargo.toml"),
                ],
                spec: Spec::ANSWERING_LOOK,
                name: "grep -l -F",
                contact: None,
                operand: Some(format!("{} {name}", commit.as_str())),
                input: None,
            },
            Self::BlobText { commit, path } => OpShape {
                argv: vec![
                    String::from("cat-file"),
                    String::from("blob"),
                    format!("{}:{path}", commit.as_str()),
                ],
                spec: Spec::LOOK,
                name: "cat-file blob",
                contact: None,
                operand: Some(format!("{}:{path}", commit.as_str())),
                input: None,
            },
            Self::Blobs { commit, paths } => OpShape {
                argv: owned(&["cat-file", "--batch"]),
                spec: Spec::LOOK,
                name: "cat-file --batch",
                contact: None,
                operand: Some(commit.as_str().to_owned()),
                input: Some(
                    paths
                        .iter()
                        .flat_map(|path| [commit.as_str(), ":", path, "\n"])
                        .collect(),
                ),
            },
            Self::FollowedBlob { queries } => {
                let named: Vec<String> = queries
                    .iter()
                    .map(|(commit, path)| format!("{}:{path}", commit.as_str()))
                    .collect();
                OpShape {
                    argv: owned(&["cat-file", "--batch", "--follow-symlinks"]),
                    spec: Spec::LOOK,
                    name: "cat-file --follow-symlinks",
                    contact: None,
                    operand: Some(named.join(" ")),
                    input: Some(named.iter().flat_map(|query| [query, "\n"]).collect()),
                }
            }
            Self::TreeFiles { commit } => OpShape {
                argv: vec![
                    String::from("ls-tree"),
                    String::from("-r"),
                    String::from("-z"),
                    String::from("--full-tree"),
                    commit.as_str().to_owned(),
                ],
                spec: Spec::OFFLINE_LOOK,
                name: "ls-tree -r",
                contact: None,
                operand: Some(commit.as_str().to_owned()),
                input: None,
            },
            Self::Objects { objects } => OpShape {
                argv: owned(&["cat-file", "--batch"]),
                spec: Spec::OFFLINE_LOOK,
                name: "cat-file --batch (by id)",
                contact: None,
                operand: None,
                input: Some(objects.iter().flat_map(|oid| [*oid, "\n"]).collect()),
            },
            Self::TreeEntry { commit, path } => OpShape {
                argv: vec![
                    String::from("ls-tree"),
                    String::from("-z"),
                    commit.as_str().to_owned(),
                    String::from("--"),
                    format!(":(literal){path}"),
                ],
                spec: Spec::LOOK,
                name: "ls-tree --",
                contact: None,
                operand: Some(format!("{} -- {path}", commit.as_str())),
                input: None,
            },
            Self::FirstParentWriters { paths } => OpShape {
                argv: [
                    "log",
                    "--no-show-signature",
                    "--first-parent",
                    "--format=%H",
                    "HEAD",
                    "--",
                ]
                .into_iter()
                .map(String::from)
                .chain(paths.iter().map(|path| format!(":(literal){path}")))
                .collect(),
                spec: Spec::LOOK,
                name: "log --first-parent",
                contact: None,
                operand: Some(paths.join(" ")),
                input: None,
            },
            Self::FileAddedBy { path } => OpShape {
                argv: vec![
                    String::from("log"),
                    String::from("--ignore-missing"),
                    String::from("--diff-filter=A"),
                    String::from("-n"),
                    String::from("1"),
                    String::from("--format=%H%x00%an%x00%ae%x00%s"),
                    String::from("HEAD"),
                    String::from("--"),
                    format!(":(literal){path}"),
                ],
                spec: Spec::LOOK,
                name: "log --diff-filter=A",
                contact: None,
                operand: named(path),
                input: None,
            },
            Self::AnnotatedTag { name, commit } => OpShape {
                argv: vec![
                    String::from("tag"),
                    String::from("-m"),
                    name.to_owned(),
                    String::from("--"),
                    name.to_owned(),
                    commit.as_str().to_owned(),
                ],
                spec: Spec::PERFORM,
                name: "tag",
                contact: None,
                operand: named(name),
                input: None,
            },
            Self::PushTag { remote, tag } => OpShape {
                argv: vec![
                    String::from("push"),
                    String::from("--"),
                    remote.to_owned(),
                    format!("refs/tags/{tag}"),
                ],
                spec: Spec::PERFORM,
                name: "push",
                contact: Some(Contact {
                    remote,
                    direction: Direction::Push,
                }),
                operand: Some(format!("{remote} {tag}")),
                input: None,
            },
        }
    }
}

impl OpShape<'_> {
    /// The operation's own failure: its name, what it was pointed at, and
    /// its outcome class.
    pub(super) fn fail(&self, detail: &str) -> CliError {
        let note = self.credentials_note(detail).unwrap_or("");
        self.phrase(|what| format!("git {what} failed: {detail}{note}"))
    }

    /// A child that gave no answer settles nothing, not even whether a tag or
    /// push happened, so it is `unverified` whatever the operation's class.
    pub(super) fn no_answer(&self, detail: &str) -> CliError {
        self.phrase_unanswered(|what| format!("git {what} failed: {detail}"))
    }

    /// oakum empties the askpass chain so a credential prompt cannot hang a
    /// release, which makes a credential-starved remote child a state oakum
    /// caused; the note names the way out.
    fn credentials_note(&self, detail: &str) -> Option<&'static str> {
        self.contact?;
        let starved = detail.contains("terminal prompts disabled")
            || detail.contains("could not read Username")
            || detail.contains("could not read Password")
            || detail.contains("Authentication failed");
        starved.then_some(
            " (oakum disables git's credential prompts so a release cannot \
             hang on one; configure or refresh a git credential helper for \
             this remote — with the GitHub CLI, `gh auth setup-git` sets one \
             up)",
        )
    }

    /// Names the operation and its remote and takes the operation's own
    /// outcome class — a `push` that never ran is a plain failure — except
    /// when the probe never answered, which is `unverified` whatever the op.
    ///
    /// States the cause the probe actually established. An ssh configuration
    /// git would not read is skippable: set both `GIT_SSH_COMMAND` and
    /// `GIT_SSH_VARIANT` (they outrank config and skip that probe), or repair
    /// the configuration; oakum will not guess a transport. A repository git
    /// will not open is neither, so it is reported as itself and offered no
    /// ssh remedy — measured, that remedy moves the failure without fixing it.
    /// A probe that never reached git establishes neither, and gets no remedy
    /// of either kind: offering one would be a diagnosis nobody made.
    pub(super) fn unreadable_transport(&self, unknown: &TransportUnknown) -> CliError {
        let message = |what: &str| match unknown {
            TransportUnknown::Repository(detail) => {
                format!("git {what} could not read this repository: {detail}")
            }
            TransportUnknown::SshVariable(detail) => format!(
                "git {what} stopped: {detail}; repair or unset that variable \
                 — oakum will not guess a transport, because that variable is \
                 what would have decided this one and guessing would replace a \
                 key or proxy the user configured"
            ),
            TransportUnknown::Unasked(detail) | TransportUnknown::Unanswered(detail) => format!(
                "git {what} did not run: oakum could not ask git for this \
                 repository's configuration ({detail}), so the ssh transport \
                 every child carries is unknown"
            ),
            TransportUnknown::SshConfig(detail) => format!(
                "git {what} needs an ssh configuration oakum could not read \
                 ({detail}); to skip an unreadable repository ssh config, set \
                 both GIT_SSH_COMMAND and GIT_SSH_VARIANT — oakum will not \
                 guess a transport, because those variables outrank every other \
                 source and guessing would replace a key or proxy the user \
                 configured"
            ),
        };
        if matches!(unknown, TransportUnknown::Unanswered(_)) {
            self.phrase_unanswered(message)
        } else {
            self.phrase(message)
        }
    }

    /// One place decides `unverified` versus a plain error for an answered
    /// failure, so a new message cannot pick the wrong one.
    pub(super) fn phrase(&self, message: impl FnOnce(&str) -> String) -> CliError {
        let message = message(&self.what());
        match self.spec.outcome {
            Outcome::Verification => CliError::unverified(format!("unverified: {message}")),
            Outcome::Action => CliError::new(message),
        }
    }

    fn phrase_unanswered(&self, message: impl FnOnce(&str) -> String) -> CliError {
        CliError::unanswered(format!("unverified: {}", message(&self.what())))
    }

    fn what(&self) -> String {
        match &self.operand {
            Some(operand) => format!("{} {operand}", self.name),
            None => self.name.to_owned(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Answer::{Always, Never, Sometimes};
    use super::Outcome::{Action, Verification};
    use super::{fixture_commit, Answer, Contact, Direction, Op, Outcome, Whole};

    /// The remote an operation contacts and which way, which decides which URL
    /// the note is asked about. Only the two operations that reach a remote
    /// have one.
    #[test]
    fn only_the_remote_operations_contact_one() {
        assert_eq!(
            Op::AdvertisedTags { remote: "upstream" }.shape().contact,
            Some(Contact {
                remote: "upstream",
                direction: Direction::Fetch
            })
        );
        assert_eq!(
            Op::PushTag {
                remote: "upstream",
                tag: "v1.0.0"
            }
            .shape()
            .contact,
            Some(Contact {
                remote: "upstream",
                direction: Direction::Push
            })
        );
        // The operations that answer the reach question must contact nothing
        // themselves. Classed otherwise, asking one recurses into asking it
        // again — measured as a stack overflow, exit 134, with the unit suite
        // still green and only the integration suites failing.
        for op in [Op::RemoteUrl { remote: "origin" }, Op::RemoteUrls] {
            assert!(
                op.shape().contact.is_none(),
                "{op:?} answers the reach question and must not ask it"
            );
        }
    }

    /// The fake keys on these, and it matches them exactly, so the only thing
    /// keying needs from them is that no two collide. `rev-parse --verify` and
    /// `rev-parse --verify refs/tags` are the close pair — one is a character
    /// prefix of the other, which is what made an argv-prefix key need rules
    /// about how much of a command line counts.
    #[test]
    fn every_operation_has_its_own_name() {
        let every = every();
        let mut names: Vec<&str> = every.iter().map(|op| op.shape().name).collect();
        let listed = names.len();
        names.sort_unstable();
        names.dedup();
        assert_eq!(
            names.len(),
            listed,
            "two operations share a name: {names:?}"
        );
    }

    /// The one measured case where a setting removes git's diagnostic without
    /// removing the check with it: a `core.fsmonitor` hook it cannot execute
    /// makes it fall back, print `fatal: cannot exec ...`, and exit 0.
    /// Overriding the setting on the child removes the diagnostic and leaves
    /// the answer byte-identical, which is what lets the rule above stay
    /// fail-closed.
    ///
    /// Both worktree reads, though for different reasons.
    /// [`Op::WorktreeStatus`] refuses a clean tree that warned at all, so the
    /// override is what keeps a broken hook from failing the gate (measured:
    /// exit 0, nothing on stdout, two `fatal: cannot exec` lines; the same
    /// hook on a dirty tree answers and is kept).
    /// [`Op::UncommittedPaths`] returns either reply as `Ok` — `cannot exec` is
    /// none of the forms `hides_part_of_the_tree` matches — so the override is
    /// defense in depth there, keeping a known-benign diagnostic off the one
    /// child whose stderr is read for unread tree.
    #[test]
    fn the_worktree_reads_override_a_broken_fsmonitor_rather_than_tolerating_it() {
        for op in [Op::WorktreeStatus, Op::UncommittedPaths] {
            let argv = op.shape().argv;
            let at = argv
                .iter()
                .position(|arg| arg == "-c")
                .unwrap_or_else(|| panic!("{op:?} passes no `-c` override: {argv:?}"));
            assert_eq!(
                &argv[at..=at + 1],
                ["-c", "core.fsmonitor=false"],
                "{op:?}: {argv:?}"
            );
        }
    }

    /// An operation whose argv contacts a remote while `contact` answers
    /// `None` skips the ssh note — the deadline rides every child regardless.
    /// Exhaustive matching forces an answer, not a right one.
    #[test]
    fn a_network_verb_and_a_contact_agree() {
        for op in every() {
            let shape = op.shape();
            let argv = shape.argv;
            assert_eq!(
                reaches_the_network(&argv),
                shape.contact.is_some(),
                "{op:?} runs `git {}` but disagrees about contacting a remote",
                argv.join(" ")
            );
        }
    }

    /// Read past any `-c <value>` pair: `Op::WorktreeStatus` already ships one,
    /// so a remote operation acquiring one is the established habit here, and
    /// reading `argv[0]` alone would stop seeing the verb. `remote` needs its
    /// subcommand — `remote update` reaches the network where `remote get-url`
    /// does not.
    fn reaches_the_network(argv: &[String]) -> bool {
        let mut rest = argv.iter().map(String::as_str);
        let mut verb = rest.next().unwrap_or_default();
        while verb == "-c" {
            rest.next();
            verb = rest.next().unwrap_or_default();
        }
        match verb {
            "fetch" | "push" | "ls-remote" | "clone" | "pull" => true,
            "remote" => rest.next() == Some("update"),
            _ => false,
        }
    }

    /// The shapes no shipping operation has yet, so walking the operation
    /// table cannot reach them.
    #[test]
    fn the_network_check_reads_past_config_and_subcommands() {
        let argv = |args: &[&str]| {
            args.iter()
                .copied()
                .map(String::from)
                .collect::<Vec<String>>()
        };
        for reaching in [
            &["fetch", "--tags", "--", "origin"][..],
            &["-c", "protocol.version=2", "fetch", "origin"][..],
            &["-c", "a=b", "-c", "c=d", "push", "origin"][..],
            &["remote", "update", "origin"][..],
        ] {
            assert!(
                reaches_the_network(&argv(reaching)),
                "`git {}` reaches the network",
                reaching.join(" ")
            );
        }
        for local in [
            &["remote", "get-url", "--", "origin"][..],
            &["remote"][..],
            &["-c", "core.fsmonitor=false", "status", "--porcelain"][..],
            &["-c", "a=b"][..],
            &[][..],
        ] {
            assert!(
                !reaches_the_network(&argv(local)),
                "`git {}` does not",
                local.join(" ")
            );
        }
    }

    /// `a_network_verb_and_a_contact_agree` and `every_operation_states_every_axis`
    /// both walk the operation table, so an operation missing from it is invisible to
    /// the tests written to catch it — measured: a remote variant listed in
    /// neither table passed the whole suite.
    #[test]
    fn every_variant_is_listed_in_every() {
        let source = include_str!("op.rs");
        // Two pieces, so the needle does not appear in this line at all.
        // Whole, it would match here too, and the search would depend on the
        // declaration staying above this test in the file.
        let opener = concat!("pub(in crate::cli) ", "enum Op<'a> {");
        let body = source
            .split_once(opener)
            .expect("the Op enum")
            .1
            .split_once("\n}\n")
            .expect("the end of the Op enum")
            .0;
        let declared = body
            .lines()
            .filter(|line| {
                let trimmed = line.trim_start();
                line.len() - trimmed.len() == 4
                    && trimmed.starts_with(|c: char| c.is_ascii_uppercase())
            })
            .count();
        assert_eq!(
            declared,
            every().len(),
            "`Op` declares {declared} variants and the operation table lists {}",
            every().len()
        );
    }

    /// How many operations `Op` declares. The table below states one row for
    /// each, so a new variant cannot compile into the table without its axes,
    /// and `every_variant_is_listed_in_every` ties the count back to the enum.
    const OPERATIONS: usize = 49;

    type Row = (
        Op<'static>,
        Outcome,
        Option<Direction>,
        Answer,
        Option<Whole>,
        bool,
    );

    /// Every operation with the axes that describe it, stated rather than
    /// sampled. One table: an operation names its own class instead of
    /// matching a second list by position. Columns after the operation:
    /// outcome, contact direction, silence rule, wholeness, lossy.
    #[expect(
        clippy::too_many_lines,
        reason = "a table, one row per operation; it grows with the enum"
    )]
    fn operations() -> [Row; OPERATIONS] {
        [
            (
                Op::ReachableTags,
                Verification,
                None,
                Sometimes,
                Some(Whole::Refs),
                false,
            ),
            (
                Op::AllTags,
                Verification,
                None,
                Sometimes,
                Some(Whole::Refs),
                false,
            ),
            (Op::VerifyRefs, Verification, None, Never, None, false),
            (Op::RefStore, Verification, None, Always, None, false),
            (Op::GitDir, Verification, None, Always, None, false),
            (Op::IsShallow, Verification, None, Always, None, false),
            (Op::RemoteTagConfig, Verification, None, Always, None, false),
            (
                Op::PartialCloneFilters,
                Verification,
                None,
                Always,
                None,
                false,
            ),
            (Op::Promisors, Verification, None, Always, None, false),
            (Op::RemoteNames, Verification, None, Sometimes, None, false),
            (
                Op::AdvertisedTags { remote: "origin" },
                Verification,
                Some(Direction::Fetch),
                Sometimes,
                None,
                false,
            ),
            (
                Op::ChangedPaths { from: "v1.0.0" },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::UncommittedPaths,
                Verification,
                None,
                Never,
                Some(Whole::Tree),
                false,
            ),
            (
                Op::FilesMentioning { dir: ".bumpy" },
                Verification,
                None,
                Always,
                None,
                false,
            ),
            (Op::TrackedFiles, Verification, None, Sometimes, None, false),
            (
                Op::UnmergedFiles { dir: ".bumpy" },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (Op::HooksDir, Verification, None, Always, None, false),
            (Op::GitCommonDir, Verification, None, Always, None, false),
            (
                Op::HooksDirOf {
                    git_dir: "/repo/.git",
                },
                Verification,
                None,
                Always,
                None,
                false,
            ),
            (
                Op::HooksPathOf {
                    git_dir: "/repo/.git",
                },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (Op::Head, Action, None, Always, None, false),
            (
                Op::RemoteUrl { remote: "origin" },
                Action,
                None,
                Always,
                None,
                false,
            ),
            (Op::RemoteUrls, Action, None, Sometimes, None, false),
            (
                Op::MergeBase { tip: "main" },
                Action,
                None,
                Always,
                None,
                false,
            ),
            (
                Op::Commits {
                    from: Some("v1.0.0"),
                },
                Action,
                None,
                Sometimes,
                None,
                true,
            ),
            (
                Op::CommitPaths {
                    hashes: &["cafebabe"],
                },
                Action,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::CommitPath { hash: "cafebabe" },
                Action,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::CommitPatch {
                    hash: "cafebabe",
                    reverse: true,
                },
                Action,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::RangeChanges { from: "v1.0.0" },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::RangeCount { from: "v1.0.0" },
                Verification,
                None,
                Always,
                None,
                false,
            ),
            (
                Op::LocalTagCommit { tag: "v1.0.0" },
                Action,
                None,
                Always,
                None,
                false,
            ),
            (Op::WorktreeStatus, Action, None, Sometimes, None, false),
            (
                Op::CommitMessage { commit: "HEAD" },
                Action,
                None,
                Sometimes,
                None,
                true,
            ),
            (
                Op::RefExists {
                    reference: "refs/tags/v1.0.0",
                },
                Action,
                None,
                Always,
                None,
                false,
            ),
            (
                Op::Parents {
                    commit: fixture_commit(),
                },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (Op::EmptyTree, Verification, None, Always, None, false),
            (
                Op::ValidRefName {
                    reference: "v1.0.0",
                },
                Action,
                None,
                Never,
                None,
                false,
            ),
            (
                Op::TreePaths {
                    commit: fixture_commit(),
                    dir: ".github/workflows",
                },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::ManifestsNaming {
                    commit: fixture_commit(),
                    name: "prose",
                },
                Verification,
                None,
                Always,
                None,
                false,
            ),
            (
                Op::BlobText {
                    commit: fixture_commit(),
                    path: ".github/workflows/release.yml",
                },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::Blobs {
                    commit: fixture_commit(),
                    paths: &[".changeset/a.md"],
                },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::FollowedBlob {
                    queries: Box::leak(Box::new([(fixture_commit(), "CHANGELOG.md")])),
                },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::TreeFiles {
                    commit: fixture_commit(),
                },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::Objects {
                    objects: &["cafebabe"],
                },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::TreeEntry {
                    commit: fixture_commit(),
                    path: "CHANGELOG.md",
                },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::FileAddedBy {
                    path: ".changeset/one.md",
                },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::FirstParentWriters {
                    paths: &["alpha/Cargo.toml"],
                },
                Verification,
                None,
                Sometimes,
                None,
                false,
            ),
            (
                Op::AnnotatedTag {
                    name: "v1.0.0",
                    commit: fixture_commit(),
                },
                Action,
                None,
                Never,
                None,
                false,
            ),
            (
                Op::PushTag {
                    remote: "origin",
                    tag: "v1.0.0",
                },
                Action,
                Some(Direction::Push),
                Never,
                None,
                false,
            ),
        ]
    }

    /// One of each variant, for the tests that ask something of every
    /// operation without caring about its axes.
    fn every() -> [Op<'static>; OPERATIONS] {
        operations().map(|(op, ..)| op)
    }

    #[test]
    fn every_operation_states_every_axis() {
        for (op, outcome, contacts, answer, whole, lossy) in operations() {
            let shape = op.shape();
            assert_eq!(shape.spec.outcome, outcome, "{op:?} outcome");
            assert_eq!(
                shape.contact.map(|contact| contact.direction),
                contacts,
                "{op:?} contacts"
            );
            assert_eq!(shape.spec.answer(), answer, "{op:?} answer");
            assert_eq!(shape.spec.whole(), whole, "{op:?} whole");
            assert_eq!(shape.spec.lossy(), lossy, "{op:?} lossy");
        }
    }

    /// A tree warning on a tag listing, or the reverse, says nothing.
    #[test]
    fn a_whole_listing_is_judged_by_what_it_lists() {
        let broken = "warning: ignoring broken ref refs/tags/v2.0.0";
        let unopened = "warning: could not open directory 'beta/': Permission denied";
        assert!(Whole::Refs.skipped(broken) && !Whole::Refs.skipped(unopened));
        assert!(Whole::Tree.skipped(unopened) && !Whole::Tree.skipped(broken));
    }

    /// A failure has to say which remote or ref it was about; the subcommand
    /// alone cannot distinguish two configured remotes.
    #[test]
    fn a_failure_names_what_it_was_pointed_at() {
        assert_eq!(
            Op::AdvertisedTags { remote: "upstream" }
                .shape()
                .operand
                .as_deref(),
            Some("upstream")
        );
        assert_eq!(
            Op::ChangedPaths { from: "v1.0.0" }
                .shape()
                .operand
                .as_deref(),
            Some("v1.0.0...HEAD")
        );
        // `ls-tree` has two call sites, so the subcommand alone cannot say
        // which read failed; the directory is what tells them apart.
        for dir in [".changeset", ".github/workflows"] {
            let shape = Op::TreePaths {
                commit: fixture_commit(),
                dir,
            }
            .shape();
            assert_eq!(
                shape.operand,
                Some(format!("{}:{dir}", fixture_commit().as_str())),
                "{dir}"
            );
        }
        assert_eq!(Op::ReachableTags.shape().operand, None);
    }
}