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
//! 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 — the operation reports through its exit code, and a successful
/// `git push` writes its whole report to stderr. Silence proves nothing
/// either way, so no rule can be drawn from it.
Never,
/// Whatever the child listed, the listing is the answer and it has to be
/// whole: any stderr disqualifies, stdout or no stdout.
///
/// [`Self::Sometimes`] keys on emptiness, which 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,
}
/// What the runner needs about an operation beyond its remote, which
/// [`OpShape::contact`] carries.
pub(super) struct Spec {
outcome: Outcome,
pub(super) answer: Answer,
/// 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.
pub(super) lossy: bool,
}
impl Spec {
const LOOK: Self = Self {
outcome: Outcome::Verification,
answer: Answer::Sometimes,
lossy: false,
};
const ANSWERING_LOOK: Self = Self {
answer: Answer::Always,
..Self::LOOK
};
const WHOLE_LOOK: Self = Self {
answer: Answer::Whole,
..Self::LOOK
};
const ACT: Self = Self {
outcome: Outcome::Action,
answer: Answer::Sometimes,
lossy: 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,
IsShallow,
/// Remotes configured with `tagOpt = --no-tags`.
TagOptRemotes,
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.
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,
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 subject NUL body NUL` per commit, oldest first.
Commits {
from: &'a str,
},
/// Paths in one commit, NUL-separated.
CommitPaths {
hash: &'a str,
},
CommitParents {
hash: &'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,
},
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,
},
/// 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,
},
/// 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>,
}
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::LOOK,
name: "for-each-ref --merged HEAD",
contact: None,
operand: 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::LOOK,
name: "for-each-ref refs/tags",
contact: None,
operand: 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,
},
Self::TagOptRemotes => OpShape {
argv: owned(&["config", "--get-regexp", r"^remote\..*\.tagopt$"]),
spec: Spec::ANSWERING_LOOK,
name: "config --get-regexp tagopt",
contact: None,
operand: None,
},
Self::RemoteNames => OpShape {
argv: owned(&["remote"]),
spec: Spec::LOOK,
name: "remote",
contact: None,
operand: 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),
},
Self::ChangedPaths { from } => OpShape {
argv: vec![
String::from("diff"),
String::from("-z"),
String::from("--name-only"),
format!("{from}...HEAD"),
],
spec: Spec::LOOK,
name: "diff --name-only",
contact: None,
operand: Some(format!("{from}...HEAD")),
},
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,
},
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"),
],
spec: Spec::LOOK,
name: "grep --name-only",
contact: None,
operand: Some(dir.to_owned()),
},
Self::TrackedFiles => OpShape {
argv: owned(&["ls-files", "-z"]),
spec: Spec::LOOK,
name: "ls-files",
contact: None,
operand: None,
},
Self::Head => OpShape {
argv: owned(&["rev-parse", "HEAD"]),
spec: Spec::ANSWERING_ACT,
name: "rev-parse HEAD",
contact: None,
operand: None,
},
Self::RemoteUrl { remote } => OpShape {
argv: owned(&["remote", "get-url", "--", remote]),
spec: Spec::ANSWERING_ACT,
name: "remote get-url",
contact: None,
operand: named(remote),
},
Self::RemoteUrls => OpShape {
argv: owned(&["remote", "-v"]),
spec: Spec::ACT,
name: "remote -v",
contact: None,
operand: None,
},
Self::MergeBase { tip } => OpShape {
argv: owned(&["merge-base", tip, "HEAD"]),
spec: Spec::ANSWERING_ACT,
name: "merge-base",
contact: None,
operand: named(tip),
},
Self::Commits { from } => OpShape {
argv: vec![
String::from("log"),
format!("{from}..HEAD"),
String::from("--reverse"),
String::from("--format=%H%x00%s%x00%b%x00"),
],
spec: Spec::LOSSY_ACT,
name: "log",
contact: None,
operand: Some(format!("{from}..HEAD")),
},
Self::CommitPaths { 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),
},
Self::CommitParents { hash } => OpShape {
argv: owned(&["rev-list", "--parents", "-n", "1", hash]),
spec: Spec::ANSWERING_ACT,
name: "rev-list --parents",
contact: None,
operand: named(hash),
},
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),
},
// 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,
},
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),
},
// 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),
},
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),
},
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())),
},
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())),
},
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())),
},
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),
},
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),
},
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}")),
},
}
}
}
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}"))
}
/// 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)",
)
}
/// Routed through [`OpShape::phrase`] like every other git failure, so it
/// names the operation and its remote and takes the operation's own
/// outcome class: a `push` that never ran is a plain failure, not a
/// verification that could not look.
///
/// 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 {
self.phrase(|what| 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) => 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"
),
})
}
/// One place decides `unverified` versus a plain error, so a new message
/// cannot pick the wrong one.
pub(super) fn phrase(&self, message: impl FnOnce(&str) -> String) -> CliError {
let what = match &self.operand {
Some(operand) => format!("{} {operand}", self.name),
None => self.name.to_owned(),
};
let message = message(&what);
match self.spec.outcome {
Outcome::Verification => CliError::unverified(format!("unverified: {message}")),
Outcome::Action => CliError::new(message),
}
}
}
#[cfg(test)]
mod tests {
use super::Answer::{Always, Never, Sometimes, Whole};
use super::Outcome::{Action, Verification};
use super::{fixture_commit, Answer, Contact, Direction, Op, Outcome};
/// 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 of git writing to stderr while answering
/// correctly: 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, because the override is load-bearing for
/// [`Op::UncommittedPaths`] in a way it is not for [`Op::WorktreeStatus`]:
/// `Answer::Whole` turns any stderr on that child into a refusal, so
/// without this a broken hook would make `check` refuse on every run while
/// git was answering correctly (measured: exit 0, the full listing, two
/// `fatal: cannot exec` lines).
#[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 = 28;
/// 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.
#[expect(
clippy::too_many_lines,
reason = "a table, one row per operation; it grows with the enum"
)]
fn operations() -> [(Op<'static>, Outcome, Option<Direction>, Answer, bool); OPERATIONS] {
[
(Op::ReachableTags, Verification, None, Sometimes, false),
(Op::AllTags, Verification, None, Sometimes, false),
(Op::IsShallow, Verification, None, Always, false),
(Op::TagOptRemotes, Verification, None, Always, false),
(Op::RemoteNames, Verification, None, Sometimes, false),
(
Op::AdvertisedTags { remote: "origin" },
Verification,
Some(Direction::Fetch),
Sometimes,
false,
),
(
Op::ChangedPaths { from: "v1.0.0" },
Verification,
None,
Sometimes,
false,
),
(Op::UncommittedPaths, Verification, None, Whole, false),
(
Op::FilesMentioning { dir: ".bumpy" },
Verification,
None,
Sometimes,
false,
),
(Op::TrackedFiles, Verification, None, Sometimes, false),
(Op::Head, Action, None, Always, false),
(
Op::RemoteUrl { remote: "origin" },
Action,
None,
Always,
false,
),
(Op::RemoteUrls, Action, None, Sometimes, false),
(Op::MergeBase { tip: "main" }, Action, None, Always, false),
(
Op::Commits { from: "v1.0.0" },
Action,
None,
Sometimes,
true,
),
(
Op::CommitPaths { hash: "cafebabe" },
Action,
None,
Sometimes,
false,
),
(
Op::CommitParents { hash: "cafebabe" },
Action,
None,
Always,
false,
),
(
Op::LocalTagCommit { tag: "v1.0.0" },
Action,
None,
Always,
false,
),
(Op::WorktreeStatus, Action, None, Sometimes, false),
(
Op::CommitMessage { commit: "HEAD" },
Action,
None,
Sometimes,
true,
),
(
Op::RefExists {
reference: "refs/tags/v1.0.0",
},
Action,
None,
Always,
false,
),
(
Op::ValidRefName {
reference: "v1.0.0",
},
Action,
None,
Never,
false,
),
(
Op::TreePaths {
commit: fixture_commit(),
dir: ".github/workflows",
},
Verification,
None,
Sometimes,
false,
),
(
Op::BlobText {
commit: fixture_commit(),
path: ".github/workflows/release.yml",
},
Verification,
None,
Sometimes,
false,
),
(
Op::TreeEntry {
commit: fixture_commit(),
path: "CHANGELOG.md",
},
Verification,
None,
Sometimes,
false,
),
(
Op::FileAddedBy {
path: ".changeset/one.md",
},
Verification,
None,
Sometimes,
false,
),
(
Op::AnnotatedTag {
name: "v1.0.0",
commit: fixture_commit(),
},
Action,
None,
Never,
false,
),
(
Op::PushTag {
remote: "origin",
tag: "v1.0.0",
},
Action,
Some(Direction::Push),
Never,
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, 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.lossy, lossy, "{op:?} lossy");
}
}
/// 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);
}
}