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
//! Git children built so they do not stop at a prompt.
//!
//! Oakum spawns git with piped standard handles and waits for it, but the child
//! still inherits the controlling terminal. A prompt on `/dev/tty` is an
//! indefinite hang rather than a failure — measured at over 20s against both an
//! https remote without cached credentials and an ssh remote whose host key is
//! unknown. Without a controlling terminal, git already fails on its own.
//!
//! Five sources can prompt. Three are answered here:
//!
//! - Git's terminal prompt: `GIT_TERMINAL_PROMPT=0`.
//! - Git's askpass chain (`GIT_ASKPASS`, `core.askPass`, `SSH_ASKPASS`):
//!   `GIT_ASKPASS=""`. The terminal-prompt variable does not reach it — with
//!   prompts disabled, git still invoked an askpass helper twice for an https
//!   credential.
//! - Ssh, which reads `/dev/tty` directly: `BatchMode=yes`.
//!
//! The fourth is a `credential.helper`, which runs with this environment applied
//! and can still block — measured at 8.7s against a helper that sleeps, and
//! unbounded for one that reads `/dev/tty`. Suppressing helpers is not an option
//! because they are what makes stored credentials authenticate.
//!
//! The fifth is signing. `git tag` with `tag.gpgSign` runs `gpg.program`, and
//! `gpg.format = ssh` runs `ssh-keygen -Y sign`. Every variable above reaches
//! the signing child — measured, it logged `GIT_TERMINAL_PROMPT=[0]
//! GIT_ASKPASS=[] GIT_SSH_COMMAND=[ssh -o BatchMode=yes]` — and none stops it:
//! a `gpg.program` that opens `/dev/tty` was invoked and never returned. It is
//! not a remote operation either, so the ssh transport handling never applies.
//!
//! Only a deadline on the child covers these, along with an interactive
//! `ProxyCommand`, which `BatchMode=yes` does not stop either.
//! [`DeadlinedGit::output`] carries that deadline for every git child oakum
//! spawns — signing included, since a signing child is local-classed and git
//! dials sockets from local-classed children too.

use std::fmt;
use std::io::{self, Write};
use std::path::Path;
use std::process::{Command, Output};
use std::time::Duration;

use oakum::discover::child::{output_within_reading, ChildFailure, Reach};

use super::Reply;

/// A git child carrying the no-prompt environment and the wall-clock
/// deadline. Opaque so neither can be stripped back off between construction
/// and the run. Every child rides it: git opens sockets — and spawns signing
/// programs — on its own schedule, so bounding only the remote-classed
/// children leaves a partial clone's lazy fetch, or a `gpg` that reads
/// `/dev/tty`, unbounded.
pub(super) struct DeadlinedGit(Command);

/// Why a git child produced no `Output`.
pub(super) enum RemoteFailure {
    Spawn(io::Error),
    /// `OAKUM_REMOTE_DEADLINE` was set to something that is not a positive
    /// whole number of seconds. Its own variant so a config mistake is never
    /// reported as "could not run git": git was never run.
    BadDeadline(String),
    /// The wall-clock deadline expired and oakum killed the child and what it
    /// started. The prompt
    /// sources no environment variable suppresses — a credential helper, an
    /// interactive `ProxyCommand`, a signing program that reads `/dev/tty` —
    /// block exactly here, and the deadline is the only mechanism that covers
    /// them and any future one.
    Deadline {
        limit: Duration,
        reach: Reach,
    },
    /// The child exited, but something it spawned still held its pipes open
    /// when the deadline ran out, so the output could not be collected. Its
    /// own variant because nothing was killed and the child's status is in
    /// hand — reporting this as a kill would misdescribe both.
    DrainStalled {
        limit: Duration,
        status: std::process::ExitStatus,
    },
    /// Waiting on a spawned child failed. Distinct from `Spawn`: git ran, and
    /// oakum killed it and what it started on the way out.
    Wait(io::Error, Reach),
    /// Reading a pipe failed partway. Its own variant so a truncated reply is
    /// never handed to a caller as git's whole answer.
    Read(io::Error),
}

impl fmt::Display for RemoteFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Spawn(err) => write!(f, "could not run git: {err}"),
            Self::BadDeadline(reason) => f.write_str(reason),
            Self::Wait(err, reach) => write!(
                f,
                "git started but waiting on it failed ({err}); oakum {}",
                reach.describe("it")
            ),
            Self::Read(err) => {
                write!(f, "git ran but its output could not be read: {err}")
            }
            Self::DrainStalled { limit, status } => write!(
                f,
                "git exited ({status}) but something it spawned still held its \
                 output open {}s later, so the answer could not be collected; a \
                 credential helper or an ssh control master is the likely cause. \
                 Set OAKUM_REMOTE_DEADLINE (seconds) to wait longer",
                limit.as_secs()
            ),
            Self::Deadline { limit, reach } => write!(
                f,
                "gave up after {}s with no answer and {}; a credential helper, an interactive \
                 ProxyCommand, or a signing program that prompts can \
                 block past every prompt oakum \
                 suppresses. Set OAKUM_REMOTE_DEADLINE (seconds) \
                 if this remote is legitimately slow",
                limit.as_secs(),
                reach.describe("git")
            ),
        }
    }
}

impl RemoteFailure {
    /// Every failure but `Spawn` leaves no complete answer. `BadDeadline` is
    /// counted too, so a malformed deadline reads as discovery reads it.
    pub(super) const fn left_no_answer(&self) -> bool {
        !matches!(self, Self::Spawn(_))
    }
}

impl From<ChildFailure> for RemoteFailure {
    fn from(failure: ChildFailure) -> Self {
        match failure {
            ChildFailure::Spawn(err) => Self::Spawn(err),
            ChildFailure::Deadline { limit, reach } => Self::Deadline { limit, reach },
            ChildFailure::DrainStalled { limit, status } => Self::DrainStalled { limit, status },
            ChildFailure::Wait(err, reach) => Self::Wait(err, reach),
            ChildFailure::Read(err) => Self::Read(err),
        }
    }
}

impl DeadlinedGit {
    pub(super) fn without_lazy_fetch(mut self) -> Self {
        self.0.env("GIT_NO_LAZY_FETCH", "1");
        self
    }

    /// Runs the child under the wall-clock deadline ([`oakum::discover::child`]),
    /// with `input` on its stdin.
    ///
    /// # Errors
    ///
    /// The spawn failure, a rejected `OAKUM_REMOTE_DEADLINE`, or the expired
    /// deadline.
    pub(super) fn output(mut self, input: Option<&[u8]>) -> Result<Output, RemoteFailure> {
        let limit = oakum::discover::child::deadline().map_err(RemoteFailure::BadDeadline)?;
        Ok(output_within_reading(&mut self.0, limit, input)?)
    }
}

/// The base of every git child oakum spawns.
///
/// Sets the working directory and the no-prompt environment together so the
/// transport cannot be resolved against one repository and applied to another.
///
/// Written per site instead, this drifts: `config_probe` below is spawned
/// before `remote_command` and had neither the askpass suppression nor the
/// trace removal until each was noticed separately, and the second cost every
/// remote operation for anyone with tracing on.
///
/// `LC_ALL=C` because git translates its diagnostics and oakum reads them.
/// Measured on 2.55: the warning that says part of the worktree went unread is
/// `could not open directory` under `C`, `konnte Verzeichnis ... nicht öffnen`
/// under `de_DE`, and `impossible d'ouvrir le répertoire` under `fr_FR`. A
/// matcher written against the English is not a narrower matcher on the other
/// two — it is no matcher at all, so the look reports on a tree it did not
/// finish reading. The rule this pins belongs to every read that classifies
/// git's words, not only that one.
pub(super) fn local_command(repo: &Path, args: &[&str]) -> Command {
    let mut command = Command::new("git");
    command
        .args(args)
        .current_dir(repo)
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_ASKPASS", "")
        .env("LC_ALL", "C");
    for name in PATHSPEC_SEMANTICS {
        command.env_remove(name);
    }
    super::untrace(&mut command);
    command
}

/// Variables that change what every pathspec in an argv means. Oakum writes
/// its pathspecs for git's defaults: under `GIT_LITERAL_PATHSPECS=1`,
/// `:(exclude).changeset` names a file rather than excluding a directory.
const PATHSPEC_SEMANTICS: [&str; 4] = [
    "GIT_LITERAL_PATHSPECS",
    "GIT_GLOB_PATHSPECS",
    "GIT_NOGLOB_PATHSPECS",
    "GIT_ICASE_PATHSPECS",
];

#[cfg(test)]
mod child_environment {
    use super::local_command;

    /// Every read that classifies git's words depends on git writing them in
    /// one language. Measured on 2.55, the same warning is `could not open
    /// directory` under `C`, `konnte Verzeichnis ... nicht öffnen` under
    /// `de_DE` and `impossible d'ouvrir le répertoire` under `fr_FR`, so a
    /// matcher written against the English does not narrow on the others — it
    /// stops matching, and the look reports on a tree it never finished
    /// reading.
    #[test]
    fn every_child_is_spawned_in_one_language() {
        let command = local_command(std::path::Path::new("."), &["status"]);
        let pinned = command
            .get_envs()
            .find(|(name, _)| *name == std::ffi::OsStr::new("LC_ALL"))
            .map(|(_, value)| value.map(std::ffi::OsStr::to_os_string));
        assert_eq!(
            pinned,
            Some(Some(std::ffi::OsString::from("C"))),
            "git's diagnostics are read, so the child cannot inherit a locale"
        );
    }

    #[test]
    fn every_child_drops_the_variables_that_reinterpret_pathspecs() {
        let command = local_command(std::path::Path::new("."), &["status"]);
        for name in [
            "GIT_LITERAL_PATHSPECS",
            "GIT_GLOB_PATHSPECS",
            "GIT_NOGLOB_PATHSPECS",
            "GIT_ICASE_PATHSPECS",
        ] {
            let removed = command
                .get_envs()
                .any(|(key, value)| key == std::ffi::OsStr::new(name) && value.is_none());
            assert!(removed, "{name} must not reach the child");
        }
    }
}

/// The transport applied to a child typed as local: git decides for itself
/// when to open a socket — a partial clone's `diff` lazily fetches from the
/// promisor remote — so `BatchMode` must ride every child, not only the ones
/// whose argv names a remote. `local_command` itself stays bare because the
/// transport probe below spawns through it.
pub(super) fn protected_command(repo: &Path, args: &[&str], batch: &BatchSsh) -> Command {
    let mut command = local_command(repo, args);
    if let Some(ssh) = batch.ssh_command() {
        command.env("GIT_SSH_COMMAND", ssh);
    }
    command
}

pub(super) fn deadlined_command(repo: &Path, args: &[&str], batch: &BatchSsh) -> DeadlinedGit {
    DeadlinedGit(protected_command(repo, args, batch))
}

/// Resolves what ssh transport a remote child would use, which is a property of
/// the process environment and the repository config and so cannot change while
/// oakum runs. [`super::Git`] calls this once and reuses the answer; resolving
/// it per child costs an extra `git config` spawn every time — 1 + 2N of them
/// in an N-tag release.
///
/// # Errors
///
/// Ssh configuration oakum cannot read is a failure, never "unset" — but only
/// when the configuration would still be consulted. `GIT_SSH_COMMAND` and
/// `GIT_SSH_VARIANT` outrank every other source; when both are set the config
/// probe is skipped. Guessing a bare `ssh` when the probe fails would replace
/// a key or proxy the user configured. The reason travels as a
/// [`TransportUnknown`] so the caller decides whether it is fatal and which
/// remedy applies; see [`super::OpShape::unreadable_transport`].
pub(super) fn batch_transport(repo: &Path) -> Result<BatchSsh, TransportUnknown> {
    transport(repo).map(batch_ssh)
}

/// Why the transport could not be resolved. One string used to carry all three,
/// and every failure was therefore reported as an ssh problem — including a
/// repository git refuses to open, and a git that could not be run at all.
#[derive(Debug)]
pub(super) enum TransportUnknown {
    /// Git read the repository and would not give up the ssh configuration.
    /// Skipping the probe is a real remedy here.
    SshConfig(String),
    /// Git would not open the repository at all, established by a second bare
    /// probe rather than inferred from the first one's wording.
    Repository(String),
    /// Neither question reached git: the child could not be spawned or died
    /// without a word. Both remedies would be diagnoses nobody made, so this
    /// arm offers neither.
    Unasked(String),
    /// The config probe gave no answer, so it is `unverified` whatever the
    /// operation, like every other child that gave none.
    Unanswered(String),
    /// An ssh variable oakum could not read. Separate from [`Self::SshConfig`]
    /// because that arm's remedy is to *set* these variables, which is circular
    /// advice when one of them is the failure — measured: an invalid-UTF-8
    /// `GIT_SSH_COMMAND` was answered by advising that both it and
    /// `GIT_SSH_VARIANT` be set.
    SshVariable(String),
}

impl TransportUnknown {
    /// The reason alone, for a caller comparing what was cached rather than
    /// how it will read.
    #[cfg(test)]
    pub(super) fn detail(&self) -> &str {
        match self {
            Self::SshConfig(detail)
            | Self::Repository(detail)
            | Self::Unasked(detail)
            | Self::Unanswered(detail)
            | Self::SshVariable(detail) => detail,
        }
    }
}

/// Why a bare probe did not answer. The distinction is the whole point: a child
/// that ran and refused is evidence about what it was asked, and a child that
/// never ran is evidence about nothing.
#[derive(Debug)]
enum ProbeFailure {
    /// Exited nonzero and said why.
    Refused(String),
    /// Could not be spawned, or was killed before it could exit. A signal says
    /// nothing about what the child was asked.
    Unasked(String),
    /// Ran, or was meant to, and gave no answer.
    Unanswered(String),
}

impl ProbeFailure {
    fn unreplied(failure: &RemoteFailure) -> Self {
        if failure.left_no_answer() {
            Self::Unanswered(failure.to_string())
        } else {
            Self::Unasked(failure.to_string())
        }
    }

    /// Keyed on whether the child exited at all, not on whether it wrote to
    /// stderr: a wrapper that exits nonzero after explaining itself on *stdout*
    /// has run and refused, and reading only stderr reported it as a child git
    /// was never asked. A signal leaves no exit code and says nothing about
    /// what the child was asked.
    fn from(reply: &Reply) -> Self {
        match reply.code {
            Some(_) => Self::Refused(reply.detail()),
            None => Self::Unasked(reply.detail()),
        }
    }
}

/// Whether git can open this repository at all. Asked only when the config
/// probe *ran* and refused: a probe that never ran has already established that
/// no git child can answer here, and asking a second one would add another full
/// deadline to a hung run without discriminating anything.
fn repository_probe(probe: Probe<'_>) -> Result<(), ProbeFailure> {
    let reply =
        probe(&["rev-parse", "--git-dir"]).map_err(|failure| ProbeFailure::unreplied(&failure))?;
    if reply.succeeded() {
        return Ok(());
    }
    Err(ProbeFailure::from(&reply))
}

/// Says a line on stderr, reporting whether it landed. A refused write — a
/// broken pipe, a full disk — reports `false`; a *closed* stderr does not,
/// because `writeln!` to [`io::stderr`] returns `Ok` on `EBADF` (measured on
/// rustc 1.97.1, where the raw `write(2, ..)` beneath it returns -1).
///
/// Whether this has already been said for a remote is [`super::Git`]'s to track:
/// a process-wide `Once` here lets whichever remote resolves first consume the
/// only line, so a mistyped remote silences the warning for a real one.
#[must_use = "a discarded refusal records an unsaid note as said"]
pub(super) fn warn(note: &str) -> bool {
    say(io::stderr(), note)
}

/// The note quotes a remote's name and why its transport is unknown, so it is
/// escaped as `say_err` escapes.
fn say(out: impl Write, note: &str) -> bool {
    crate::cli::printable::say(out, note).is_ok()
}

/// What git would use for ssh, in git's own precedence order.
#[derive(Debug)]
enum SshTransport {
    /// Shell-parsed by git, so options can be appended.
    Composable(String),
    /// Cannot take appended options; the string says why.
    Opaque(String),
    /// Nothing configured; git runs plain `ssh`.
    Default,
}

/// Whether `BatchMode=yes` reached the transport.
#[derive(Debug)]
pub(super) enum BatchSsh {
    Composed(String),
    /// Appended, but the transport already chose `BatchMode` and ssh takes the
    /// first value, so oakum's has no effect.
    Inert {
        ssh: String,
        reason: String,
    },
    /// Nothing could be appended.
    Unprotected(String),
}

impl BatchSsh {
    /// What to put in `GIT_SSH_COMMAND`, when there is anything to put there.
    fn ssh_command(&self) -> Option<&str> {
        match self {
            Self::Composed(ssh) | Self::Inert { ssh, .. } => Some(ssh),
            Self::Unprotected(_) => None,
        }
    }

    /// Why a prompt could still block, when it could. `Composed` is the case
    /// where it cannot, so it has nothing to say.
    pub(super) fn unprotected_reason(&self) -> Option<&str> {
        match self {
            Self::Composed(_) => None,
            Self::Inert { reason, .. } | Self::Unprotected(reason) => Some(reason),
        }
    }
}

/// One bare probe child's reply, or why it never ran. The seam the git fake
/// has at the spawn, here at the probe: [`resolve_transport`] asks whatever
/// answers this, so every arm below it is reachable from a script.
type Probe<'a> = &'a dyn Fn(&[&str]) -> Result<Reply, RemoteFailure>;

/// One environment variable, or why it could not be read. Injected beside
/// the probe so a test never sets process environment.
type Env<'a> = &'a dyn Fn(&str) -> Result<Option<String>, String>;

fn transport(repo: &Path) -> Result<SshTransport, TransportUnknown> {
    resolve_transport(&env_value, &|args| run_probe(repo, args))
}

/// Through the deadline like every other child: the config probe is the
/// first spawn of every command, and a `PATH` wrapper or a config include on
/// a hung mount would otherwise block oakum before any operation is named.
fn run_probe(repo: &Path, args: &[&str]) -> Result<Reply, RemoteFailure> {
    DeadlinedGit(local_command(repo, args))
        .output(None)
        .map(Reply::from)
}

fn resolve_transport(env: Env<'_>, probe: Probe<'_>) -> Result<SshTransport, TransportUnknown> {
    // Environment before config: GIT_SSH_COMMAND / GIT_SSH_VARIANT outrank
    // core.sshCommand / ssh.variant, so an unreadable config must not fail a
    // remote when both env vars already decide the transport (okm-7za.7).
    let ssh_variable = TransportUnknown::SshVariable;
    let env_command = env("GIT_SSH_COMMAND").map_err(ssh_variable)?;
    let env_variant = env("GIT_SSH_VARIANT").map_err(ssh_variable)?;
    let (command, variant) = if let (Some(command), Some(variant)) = (&env_command, &env_variant) {
        (Some(command.clone()), Some(variant.clone()))
    } else {
        let config = config_probe(probe).map_err(|failure| match failure {
            ProbeFailure::Unasked(why) => TransportUnknown::Unasked(why),
            ProbeFailure::Unanswered(why) => TransportUnknown::Unanswered(why),
            ProbeFailure::Refused(why) => match repository_probe(probe) {
                Ok(()) => TransportUnknown::SshConfig(why),
                Err(ProbeFailure::Refused(refusal)) => TransportUnknown::Repository(refusal),
                // The config child *did* run and refuse, so `Unasked` would say
                // git was never asked about something it answered. What could
                // not be established is whether the repository itself opens —
                // both facts travel rather than one replacing the other.
                Err(ProbeFailure::Unasked(second) | ProbeFailure::Unanswered(second)) => {
                    TransportUnknown::SshConfig(format!(
                        "{why}; whether git can open this repository could not be \
                     established either ({second})"
                    ))
                }
            },
        })?;
        (
            env_command.or(config.ssh_command),
            env_variant.or(config.ssh_variant),
        )
    };
    // Checked before the command itself: a `plink` transport is opaque however
    // git was pointed at it.
    if let Some(reason) = opaque_variant(variant.as_deref(), command.as_deref()) {
        return Ok(SshTransport::Opaque(reason));
    }
    if let Some(command) = command {
        return Ok(SshTransport::Composable(command));
    }
    if let Some(program) = env("GIT_SSH").map_err(ssh_variable)? {
        return Ok(SshTransport::Opaque(format!(
            "GIT_SSH names `{program}`, which takes its arguments from git, not from oakum"
        )));
    }
    Ok(SshTransport::Default)
}

/// Git picks a transport's argument style from `ssh.variant`, falling back to
/// the command's basename. Only the OpenSSH styles accept `-o`; injecting it
/// into the others turns a working push into a hard failure, and git drops its
/// own `-o SendEnv=GIT_PROTOCOL` for exactly that reason.
fn opaque_variant(variant: Option<&str>, command: Option<&str>) -> Option<String> {
    const OPAQUE_PROGRAMS: [&str; 3] = ["plink", "putty", "tortoiseplink"];
    if let Some(variant) = variant {
        return (!matches!(variant, "auto" | "ssh"))
            .then(|| format!("ssh.variant is `{variant}`, which does not take `-o` options"));
    }
    let program = command?.split_whitespace().next()?;
    let name = Path::new(program)
        .file_stem()
        .and_then(|stem| stem.to_str())?
        .to_ascii_lowercase();
    OPAQUE_PROGRAMS.contains(&name.as_str()).then(|| {
        format!("`{program}` does not take `-o` options; git treats it as the `{name}` variant")
    })
}

/// Appends unconditionally. Ssh takes the first value of a repeated option, so a
/// user's own `-o BatchMode=no` still wins and a `BatchMode no` in `ssh_config`
/// is still overridden. Deciding by reading the command line would mean parsing
/// it, and a nested `ProxyCommand` carrying `BatchMode=no` reads identically to
/// an outer one while meaning the opposite.
fn batch_ssh(transport: SshTransport) -> BatchSsh {
    match transport {
        SshTransport::Composable(command) => {
            let ssh = format!("{command} -o BatchMode=yes");
            if may_already_set_batch_mode(&command) {
                return BatchSsh::Inert {
                    ssh,
                    reason: format!("`{command}` already sets BatchMode, which ssh reads first"),
                };
            }
            BatchSsh::Composed(ssh)
        }
        SshTransport::Default => BatchSsh::Composed(String::from("ssh -o BatchMode=yes")),
        SshTransport::Opaque(reason) => BatchSsh::Unprotected(reason),
    }
}

/// Deliberately imprecise, and only ever used to decide whether to warn. The
/// same substring test would be unsafe for deciding whether to append — a nested
/// `ProxyCommand` would cancel the option for the outer connection — but a false
/// positive here costs one spurious line while a false negative costs a silent
/// hang.
fn may_already_set_batch_mode(command: &str) -> bool {
    command.to_ascii_lowercase().contains("batchmode")
}

/// # Errors
///
/// A value git would use but oakum cannot read is an error, never "unset".
fn env_value(key: &str) -> Result<Option<String>, String> {
    match std::env::var_os(key) {
        None => Ok(None),
        Some(raw) => raw
            .into_string()
            .map(non_blank)
            .map_err(|_| format!("{key} is not valid UTF-8")),
    }
}

/// Empty is unset. Git runs an empty `GIT_SSH_COMMAND` rather than falling
/// through to `core.sshCommand`, failing with `cannot run : No such file or
/// directory`, and CI templates export unset variables as empty routinely.
fn non_blank(value: String) -> Option<String> {
    (!value.trim().is_empty()).then_some(value)
}

/// Both keys in one child, so adding the variant check costs no extra spawn.
struct GitConfig {
    ssh_command: Option<String>,
    ssh_variant: Option<String>,
}

/// An absent key is `None`. A probe that could not run is an error.
fn config_probe(probe: Probe<'_>) -> Result<GitConfig, ProbeFailure> {
    let reply = probe(&[
        "config",
        "--get-regexp",
        r"^(core\.sshcommand|ssh\.variant)$",
    ])
    .map_err(|failure| ProbeFailure::unreplied(&failure))?;
    // git config exits 1 and says nothing when no key matches. A wrapper that
    // exits 1 with a diagnostic failed to look, which is not the same thing.
    if reply.said_no() {
        return Ok(GitConfig {
            ssh_command: None,
            ssh_variant: None,
        });
    }
    if !reply.succeeded() {
        // `detail` rather than stderr alone: a signal leaves both streams empty,
        // and this rendered it as an empty pair of parentheses. Shared with the
        // `Op` path so the two cannot drift apart again.
        return Err(ProbeFailure::from(&reply));
    }
    let listed = String::from_utf8(reply.stdout)
        .map_err(|_| ProbeFailure::Refused(String::from("a value is not valid UTF-8")))?;
    Ok(GitConfig {
        ssh_command: config_value(&listed, "core.sshcommand"),
        ssh_variant: config_value(&listed, "ssh.variant"),
    })
}

/// `--get-regexp` prints `key value` per line. Git resolves a repeated key to
/// the last one, so the last line wins here too.
fn config_value(listed: &str, key: &str) -> Option<String> {
    listed
        .lines()
        .filter_map(|line| line.strip_prefix(key)?.strip_prefix(' '))
        .next_back()
        .and_then(|value| non_blank(value.trim().to_owned()))
}

#[cfg(test)]
mod tests {
    /// A writer that refuses reports failure rather than panicking, so the
    /// caller can decline to record the note as said. Covers the seam, not the
    /// descriptor: [`super::warn`]'s own doc records which `io::stderr`
    /// failures reach it.
    #[test]
    fn a_refused_write_is_reported() {
        struct Full;
        impl std::io::Write for Full {
            fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
                Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
            }
            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }
        let mut wrote = Vec::new();
        assert!(super::say(&mut wrote, "a note"));
        assert_eq!(wrote, b"a note\n");
        assert!(!super::say(Full, "a note"));
        let mut wrote = Vec::new();
        assert!(super::say(&mut wrote, "a \u{1b}[2Jnote"));
        assert_eq!(wrote, b"a \\u{1b}[2Jnote\n");
    }

    use super::super::Reply;
    use super::{
        batch_ssh, config_value, non_blank, opaque_variant, resolve_transport, BatchSsh,
        RemoteFailure, SshTransport, TransportUnknown,
    };
    use oakum::discover::child::Reach;
    use std::sync::Mutex;
    use std::time::Duration;

    /// The two probes, answered by name and claimed once, and what was asked.
    struct Probes {
        config: Mutex<Option<Result<Reply, RemoteFailure>>>,
        repository: Mutex<Option<Result<Reply, RemoteFailure>>>,
        asked: Mutex<Vec<String>>,
    }

    fn unran(why: &str) -> RemoteFailure {
        RemoteFailure::Spawn(std::io::Error::other(why))
    }

    impl Probes {
        fn new(
            config: Result<Reply, RemoteFailure>,
            repository: Result<Reply, RemoteFailure>,
        ) -> Self {
            Self {
                config: Mutex::new(Some(config)),
                repository: Mutex::new(Some(repository)),
                asked: Mutex::new(Vec::new()),
            }
        }

        fn answer(&self, args: &[&str]) -> Result<Reply, RemoteFailure> {
            self.asked.lock().expect("lock").push(args[0].to_owned());
            let slot = match args[0] {
                "config" => &self.config,
                "rev-parse" => &self.repository,
                other => panic!("no probe scripted for `git {other}`"),
            };
            slot.lock()
                .expect("lock")
                .take()
                .unwrap_or_else(|| panic!("`git {}` probed twice", args[0]))
        }

        fn asked(&self) -> Vec<String> {
            self.asked.lock().expect("lock").clone()
        }
    }

    /// The [`Env`] seam's shape for a test that reads no variable. A closure
    /// rather than a function, so its always-`Ok` body needs no suppression.
    const NO_ENV: fn(&str) -> Result<Option<String>, String> = |_| Ok(None);

    const CONFIG_REFUSED: &str =
        "fatal: unable to read config file '.git/config': Permission denied";

    /// A fork that fails between the two probes is evidence about nothing:
    /// reporting it as `Repository` made a positive claim about the repository
    /// from a child that never ran. The config refusal still travels, with
    /// the second probe's failure beside it.
    #[test]
    fn a_repository_probe_that_could_not_run_is_not_a_verdict_about_the_repository() {
        let probes = Probes::new(
            Ok(Reply::failed(128, CONFIG_REFUSED)),
            Err(unran("Resource temporarily unavailable (os error 35)")),
        );
        let unknown = resolve_transport(&NO_ENV, &|args| probes.answer(args))
            .expect_err("an unreadable config over an unprobed repository");
        let TransportUnknown::SshConfig(detail) = &unknown else {
            panic!("a probe that never ran must not decide the repository: {unknown:?}");
        };
        assert!(detail.contains("unable to read config file"), "{detail}");
        assert!(
            detail.contains(
                "could not be established either (could not run git: Resource temporarily unavailable"
            ),
            "{detail}"
        );
        assert_eq!(probes.asked(), ["config", "rev-parse"]);
    }

    /// The other two answers the second probe can give, each pinned beside
    /// the one above so the three arms cannot be collapsed into two.
    #[test]
    fn a_config_refusal_is_classed_by_what_the_repository_probe_established() {
        let opens = Probes::new(
            Ok(Reply::failed(128, CONFIG_REFUSED)),
            Ok(Reply::said(".git\n")),
        );
        let unknown = resolve_transport(&NO_ENV, &|args| opens.answer(args))
            .expect_err("config refused over an openable repository");
        assert!(
            matches!(&unknown, TransportUnknown::SshConfig(detail) if detail.contains("unable to read config file") && !detail.contains("either")),
            "{unknown:?}"
        );

        let closed = Probes::new(
            Ok(Reply::failed(128, CONFIG_REFUSED)),
            Ok(Reply::failed(
                128,
                "fatal: not a git repository (or any of the parent directories): .git",
            )),
        );
        let unknown = resolve_transport(&NO_ENV, &|args| closed.answer(args))
            .expect_err("config refused over a repository git will not open");
        assert!(
            matches!(&unknown, TransportUnknown::Repository(detail) if detail.contains("not a git repository")),
            "{unknown:?}"
        );
        assert_eq!(closed.asked(), ["config", "rev-parse"]);
    }

    /// A second probe after one that never ran would add a full deadline to a
    /// hung run and discriminate nothing.
    #[test]
    fn a_config_probe_that_never_ran_asks_nothing_more() {
        let probes = Probes::new(
            Err(unran("No such file or directory (os error 2)")),
            Ok(Reply::said(".git\n")),
        );
        let unknown = resolve_transport(&NO_ENV, &|args| probes.answer(args))
            .expect_err("git could not be run");
        assert!(
            matches!(&unknown, TransportUnknown::Unasked(detail) if detail.contains("No such file or directory")),
            "{unknown:?}"
        );
        assert_eq!(probes.asked(), ["config"]);
    }

    /// The config probe answered, so the stop rests on its refusal and keeps
    /// the operation's class; a repository probe that then never answered
    /// only leaves the diagnosis open, and travels as the second fact.
    #[test]
    fn a_hung_repository_probe_after_a_config_refusal_stays_ssh_config() {
        let probes = Probes::new(
            Ok(Reply::failed(128, CONFIG_REFUSED)),
            Err(RemoteFailure::Deadline {
                limit: Duration::from_secs(2),
                reach: Reach::Killed(Vec::new()),
            }),
        );
        let unknown = resolve_transport(&NO_ENV, &|args| probes.answer(args))
            .expect_err("an unreadable config");
        assert!(
            matches!(&unknown, TransportUnknown::SshConfig(detail) if detail.contains("could not be established either (gave up after 2s")),
            "{unknown:?}"
        );
    }

    /// okm-3cbq: the config probe is every command's first child, so one that
    /// never answers must reach the operation as no answer, not as a git that
    /// could not be started.
    #[test]
    fn a_config_probe_that_never_answered_is_unanswered() {
        let probes = Probes::new(
            Err(RemoteFailure::Deadline {
                limit: Duration::from_secs(2),
                reach: Reach::Killed(Vec::new()),
            }),
            Ok(Reply::said(".git\n")),
        );
        let unknown = resolve_transport(&NO_ENV, &|args| probes.answer(args))
            .expect_err("the probe never answered");
        assert!(
            matches!(&unknown, TransportUnknown::Unanswered(detail) if detail.contains("gave up after 2s")),
            "{unknown:?}"
        );
        assert_eq!(probes.asked(), ["config"]);
    }

    /// Only a git that could not be started is known to have done nothing;
    /// every other failure leaves no answer.
    #[test]
    fn every_failure_but_spawn_left_no_answer() {
        let limit = Duration::from_secs(2);
        assert!(!unran("No such file or directory").left_no_answer());
        for failure in [
            RemoteFailure::Deadline {
                limit,
                reach: Reach::Killed(Vec::new()),
            },
            RemoteFailure::DrainStalled {
                limit,
                status: std::process::ExitStatus::default(),
            },
            RemoteFailure::Wait(
                std::io::Error::other("interrupted"),
                Reach::Killed(Vec::new()),
            ),
            RemoteFailure::Read(std::io::Error::other("broken pipe")),
            RemoteFailure::BadDeadline(String::from("not a number")),
        ] {
            assert!(failure.left_no_answer(), "{failure}");
        }
    }

    /// Both variables set means the config is never consulted, so an
    /// unreadable one cannot fail the remote (okm-7za.7).
    #[test]
    fn both_ssh_variables_set_skip_both_probes() {
        let probes = Probes::new(
            Err(unran("the config probe must not run")),
            Err(unran("the repository probe must not run")),
        );
        let env = |key: &str| -> Result<Option<String>, String> {
            Ok(match key {
                "GIT_SSH_COMMAND" => Some(String::from("ssh -i /dev/null")),
                "GIT_SSH_VARIANT" => Some(String::from("ssh")),
                _ => None,
            })
        };
        let transport = resolve_transport(&env, &|args| probes.answer(args))
            .expect("the variables decide the transport");
        assert!(
            matches!(&transport, SshTransport::Composable(command) if command == "ssh -i /dev/null"),
            "{transport:?}"
        );
        assert!(probes.asked().is_empty(), "{:?}", probes.asked());
    }

    /// The variable outranks every other source, so an unreadable one leaves
    /// the transport unknown rather than defaulted: read as unset it falls
    /// through to the config probe and can answer `Default`, which collapses
    /// "we could not look" into "nothing is set".
    #[test]
    fn an_unreadable_ssh_variable_is_not_an_unset_one() {
        let probes = Probes::new(
            Err(unran("no probe may run")),
            Err(unran("no probe may run")),
        );
        let env = |key: &str| -> Result<Option<String>, String> {
            if key == "GIT_SSH_COMMAND" {
                Err(String::from("GIT_SSH_COMMAND is not valid UTF-8"))
            } else {
                Ok(None)
            }
        };
        let unknown = resolve_transport(&env, &|args| probes.answer(args))
            .expect_err("an unreadable variable decides nothing");
        assert!(
            matches!(&unknown, TransportUnknown::SshVariable(detail) if detail.contains("not valid UTF-8")),
            "{unknown:?}"
        );
        assert!(probes.asked().is_empty(), "{:?}", probes.asked());
    }

    #[test]
    fn a_config_ssh_command_is_read_through_the_probe() {
        let probes = Probes::new(
            Ok(Reply::said("core.sshcommand ssh -i ~/.ssh/deploy\n")),
            Err(unran("the repository probe must not run")),
        );
        let transport =
            resolve_transport(&NO_ENV, &|args| probes.answer(args)).expect("a readable config");
        assert!(
            matches!(&transport, SshTransport::Composable(command) if command == "ssh -i ~/.ssh/deploy"),
            "{transport:?}"
        );
        assert_eq!(probes.asked(), ["config"]);
    }

    fn composed(transport: SshTransport) -> Option<String> {
        match batch_ssh(transport) {
            BatchSsh::Composed(ssh) | BatchSsh::Inert { ssh, .. } => Some(ssh),
            BatchSsh::Unprotected(_) => None,
        }
    }

    #[test]
    fn a_composable_command_keeps_its_own_arguments() {
        assert_eq!(
            composed(SshTransport::Composable(String::from(
                "ssh -i ~/.ssh/deploy"
            )))
            .as_deref(),
            Some("ssh -i ~/.ssh/deploy -o BatchMode=yes")
        );
    }

    #[test]
    fn nothing_configured_still_gets_batch_mode() {
        assert_eq!(
            composed(SshTransport::Default).as_deref(),
            Some("ssh -o BatchMode=yes")
        );
    }

    /// Ssh resolves the conflict, so oakum appends anyway — but says so, because
    /// this is a case where it knows its own option will not take effect.
    #[test]
    fn an_existing_batchmode_choice_is_appended_past_and_reported() {
        match batch_ssh(SshTransport::Composable(String::from(
            "ssh -o BatchMode=no",
        ))) {
            BatchSsh::Inert { ssh, reason } => {
                assert_eq!(ssh, "ssh -o BatchMode=no -o BatchMode=yes");
                assert!(reason.contains("BatchMode"), "{reason}");
            }
            BatchSsh::Composed(ssh) => panic!("an inert append must be reported, got {ssh}"),
            BatchSsh::Unprotected(reason) => panic!("must still append, got {reason}"),
        }
    }

    /// A nested `ProxyCommand` reads like an outer choice but means the
    /// opposite, so the option is still appended and still takes effect.
    #[test]
    fn a_nested_batchmode_does_not_suppress_the_option() {
        let nested = String::from("ssh -o ProxyCommand='ssh -o BatchMode=no bastion nc %h %p'");
        assert_eq!(
            composed(SshTransport::Composable(nested)).as_deref(),
            Some("ssh -o ProxyCommand='ssh -o BatchMode=no bastion nc %h %p' -o BatchMode=yes")
        );
    }

    /// `Git::child` reads this to decide whether a note is owed, and therefore
    /// whether the remote's URL is worth a child. `Composed` is the one case
    /// that owes nothing.
    #[test]
    fn only_a_transport_that_cannot_take_batch_mode_owes_a_reason() {
        assert_eq!(
            BatchSsh::Composed(String::from("ssh -o BatchMode=yes")).unprotected_reason(),
            None
        );
        assert_eq!(
            BatchSsh::Inert {
                ssh: String::from("ssh -o BatchMode=no"),
                reason: String::from("the transport already chose BatchMode"),
            }
            .unprotected_reason(),
            Some("the transport already chose BatchMode")
        );
        assert_eq!(
            BatchSsh::Unprotected(String::from("ssh.variant is opaque")).unprotected_reason(),
            Some("ssh.variant is opaque")
        );
    }

    #[test]
    fn an_opaque_transport_is_unprotected_and_says_why() {
        match batch_ssh(SshTransport::Opaque(String::from(
            "GIT_SSH names `/x/my-ssh`",
        ))) {
            BatchSsh::Unprotected(reason) => {
                assert!(reason.contains("/x/my-ssh"), "{reason}");
            }
            BatchSsh::Composed(ssh) | BatchSsh::Inert { ssh, .. } => {
                panic!("GIT_SSH cannot take appended options, got {ssh}")
            }
        }
    }

    #[test]
    fn an_explicit_non_ssh_variant_is_opaque() {
        let reason = opaque_variant(Some("simple"), Some("/x/wrapper")).expect("opaque");
        assert!(reason.contains("simple"), "{reason}");
        assert!(opaque_variant(Some("putty"), None).is_some());
    }

    #[test]
    fn the_openssh_variants_still_take_options() {
        assert_eq!(opaque_variant(Some("ssh"), Some("plink")), None);
        assert_eq!(opaque_variant(Some("auto"), Some("plink")), None);
    }

    /// Under `auto` git picks the style from the basename, so oakum must too.
    #[test]
    fn a_plink_basename_is_opaque_under_auto() {
        assert!(opaque_variant(None, Some("C:/PuTTY/plink.exe -batch")).is_some());
        assert!(opaque_variant(None, Some("/usr/bin/tortoiseplink")).is_some());
        assert_eq!(opaque_variant(None, Some("/usr/bin/ssh -i /k")), None);
        assert_eq!(opaque_variant(None, None), None);
    }

    #[test]
    fn config_values_are_read_per_key_and_last_wins() {
        let listed =
            "core.sshcommand ssh -i /first\nssh.variant simple\ncore.sshcommand ssh -i /last\n";
        assert_eq!(
            config_value(listed, "core.sshcommand").as_deref(),
            Some("ssh -i /last")
        );
        assert_eq!(
            config_value(listed, "ssh.variant").as_deref(),
            Some("simple")
        );
        assert_eq!(config_value(listed, "core.askpass"), None);
    }

    #[test]
    fn blank_and_whitespace_values_are_unset() {
        assert_eq!(non_blank(String::new()), None);
        assert_eq!(non_blank(String::from("   ")), None);
        assert_eq!(non_blank(String::from("ssh")).as_deref(), Some("ssh"));
    }

    fn exit_status(code: i32) -> std::process::ExitStatus {
        #[cfg(unix)]
        {
            use std::os::unix::process::ExitStatusExt;
            std::process::ExitStatus::from_raw(code)
        }
        #[cfg(windows)]
        {
            use std::os::windows::process::ExitStatusExt;
            std::process::ExitStatus::from_raw(code.cast_unsigned())
        }
    }

    #[test]
    fn a_stalled_drain_names_the_lever() {
        let err = RemoteFailure::from(oakum::discover::child::ChildFailure::DrainStalled {
            limit: Duration::from_secs(5),
            status: exit_status(0),
        });
        let text = err.to_string();
        assert!(text.contains("still held its output open"), "{text}");
        assert!(text.contains("OAKUM_REMOTE_DEADLINE"), "{text}");
    }

    #[test]
    fn a_failed_read_names_the_read() {
        let err = RemoteFailure::from(oakum::discover::child::ChildFailure::Read(
            std::io::Error::other("pipe broke"),
        ));
        let text = err.to_string();
        assert!(text.contains("could not be read"), "{text}");
        assert!(text.contains("pipe broke"), "{text}");
    }

    #[test]
    fn wait_failure_names_the_kill() {
        let err = RemoteFailure::Wait(
            std::io::Error::other("wait interrupted"),
            Reach::Unknown(String::from("could not list them: no ps")),
        );
        let text = err.to_string();
        assert!(text.contains("waiting on it failed"), "{text}");
        assert!(
            text.contains("oakum killed it, but what it started may still be running"),
            "{text}"
        );
        assert!(text.contains("wait interrupted"), "{text}");
    }

    #[test]
    fn deadline_failure_names_the_lever() {
        let err = RemoteFailure::Deadline {
            limit: Duration::from_secs(2),
            reach: Reach::Killed(Vec::from([String::from("gpg")])),
        };
        let text = err.to_string();
        assert!(text.contains("gave up after 2s"), "{text}");
        assert!(
            text.contains("killed git and what was still running under it (`gpg`)"),
            "{text}"
        );
        assert!(text.contains("OAKUM_REMOTE_DEADLINE"), "{text}");
    }

    /// A child that exited nonzero and said why refused; one that died without
    /// a word was never really asked. Folding the second into the first turned
    /// a signal into a confident claim about the repository (measured: a shim
    /// running `kill -TERM $$` was reported as `could not read this
    /// repository`).
    #[test]
    fn only_a_child_that_exited_counts_as_a_refusal() {
        use super::super::Reply;
        use super::ProbeFailure;
        let refused = ProbeFailure::from(&Reply::failed(128, "fatal: detected dubious ownership"));
        assert!(
            matches!(refused, ProbeFailure::Refused(_)),
            "a stated reason"
        );
        // Explaining itself on stdout is still running and refusing. Keying on
        // stderr alone reported such a child as one git was never asked.
        let on_stdout = ProbeFailure::from(&Reply::exactly(Some(128), b"fatal: refused", b""));
        let ProbeFailure::Refused(why) = &on_stdout else {
            panic!("a child that exited has run, whichever stream it wrote to: {on_stdout:?}");
        };
        // The arm alone is not enough: classifying it correctly while rendering
        // `exit 128 with no diagnostic` loses the reason and asserts there was
        // none.
        assert!(why.contains("fatal: refused"), "{why}");
        let signaled = ProbeFailure::from(&Reply::was_signalled());
        assert!(
            matches!(signaled, ProbeFailure::Unasked(_)),
            "a signal is not evidence about what was asked"
        );
    }

    /// A config probe that ran and refused stays a refusal even when the
    /// repository question cannot be put: reporting it as `Unasked` said git
    /// was never asked about the very thing it answered, and threw away the
    /// second probe's reason on the way.
    #[test]
    fn a_refused_config_probe_is_not_reported_as_never_asked() {
        let said = super::super::Op::AdvertisedTags { remote: "origin" }
            .shape()
            .unreadable_transport(&super::TransportUnknown::SshConfig(String::from(
                "exit 128: fatal: unable to read config file; whether git can open this \
                 repository could not be established either (terminated by a signal with no \
                 diagnostic)",
            )))
            .to_string();
        assert!(said.contains("unable to read config file"), "{said}");
        assert!(
            said.contains("could not be established either"),
            "both facts travel: {said}"
        );
        assert!(!said.contains("did not run"), "{said}");
    }
}