Skip to main content

greengate_runtime/
git.rs

1//! Thin wrappers over the `git` calls the hooks make.
2
3use std::process::{Command, Stdio};
4
5/// Run `cmd`, retrying the transient SPAWN failures a loaded machine
6/// produces: EINTR, EAGAIN (fork pressure), ETXTBSY (another thread's
7/// fork-to-exec window still holding a write descriptor on the executable).
8/// A NON-ZERO EXIT IS NEVER RETRIED — that is git answering; this covers
9/// only "git could not be asked".
10///
11/// The failure this ends: `gate_stamp`'s tests — and, invisibly, real
12/// hooks on a loaded machine — watched a single failed fork turn
13/// `bind_to_head` into "nothing to stamp". The hooks' fail-open reading of
14/// `None` is right for a git that is genuinely absent; three attempts over
15/// ~130ms is the difference between that and a scheduler hiccup.
16fn retrying<T>(mut attempt: impl FnMut() -> std::io::Result<T>) -> std::io::Result<T> {
17    let mut delay = std::time::Duration::from_millis(10);
18    for tries_left in [2u8, 1, 0] {
19        match attempt() {
20            Err(e) if tries_left > 0 && transient(&e) => {
21                std::thread::sleep(delay);
22                delay *= 3;
23            }
24            other => return other,
25        }
26    }
27    unreachable!("the zero-tries arm returns")
28}
29
30/// The retryable kinds, matched on raw OS codes because the precise
31/// `io::ErrorKind` variants (`ExecutableFileBusy`, `ResourceBusy`) are not
32/// stable at this crate's MSRV: EINTR(4), EAGAIN(11 linux / 35 mac),
33/// ETXTBSY(26).
34fn transient(e: &std::io::Error) -> bool {
35    if matches!(
36        e.kind(),
37        std::io::ErrorKind::Interrupted | std::io::ErrorKind::WouldBlock
38    ) {
39        return true;
40    }
41    matches!(e.raw_os_error(), Some(4 | 11 | 26 | 35))
42}
43
44/// stdout of a git command, trimmed. `None` when git itself failed — which the
45/// hooks treat as "cannot tell, do not block", never as "empty".
46pub fn stdout(args: &[&str]) -> Option<String> {
47    let mut cmd = Command::new("git");
48    cmd.args(args).stderr(Stdio::null());
49    let out = retrying(|| cmd.output()).ok()?;
50    if !out.status.success() {
51        return None;
52    }
53    Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
54}
55
56/// The same, run inside `dir`.
57///
58/// The dashboard asks about repositories it is not standing in, and must get
59/// the answer git would give THERE — config is per-repository, so asking from
60/// the wrong directory returns the wrong severity.
61pub fn stdout_in(dir: &std::path::Path, args: &[&str]) -> Option<String> {
62    let mut cmd = Command::new("git");
63    cmd.arg("-C").arg(dir).args(args).stderr(Stdio::null());
64    let out = retrying(|| cmd.output()).ok()?;
65    if !out.status.success() {
66        return None;
67    }
68    Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
69}
70
71/// [`succeeds`] for a repository this process is not standing in — the shape
72/// the fleet needs to UNDO something (delete a ref it wrote) rather than ask
73/// about it. Output discarded; `false` covers "git could not run" too.
74pub fn succeeds_in(dir: &std::path::Path, args: &[&str]) -> bool {
75    let mut cmd = Command::new("git");
76    cmd.arg("-C")
77        .arg(dir)
78        .args(args)
79        .stdin(Stdio::null())
80        .stdout(Stdio::null())
81        .stderr(Stdio::null());
82    retrying(|| cmd.status())
83        .map(|s| s.success())
84        .unwrap_or(false)
85}
86
87/// stdout of a git command that itself reads a list from stdin — `diff-tree
88/// --stdin`, fed a list of commits, is the only caller today. Lossy but
89/// untrimmed: every line is a path, and the caller trims those itself.
90pub fn stdout_piped(args: &[&str], stdin: &str) -> Option<String> {
91    use std::io::Write;
92    let mut cmd = Command::new("git");
93    cmd.args(args)
94        .stdin(Stdio::piped())
95        .stdout(Stdio::piped())
96        .stderr(Stdio::null());
97    let mut child = retrying(|| cmd.spawn()).ok()?;
98    child.stdin.take()?.write_all(stdin.as_bytes()).ok()?;
99    let out = child.wait_with_output().ok()?;
100    out.status
101        .success()
102        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
103}
104
105/// As `stdout_piped`, but returning the RAW bytes.
106///
107/// Needed by the one caller that must both feed git a list on stdin and read a
108/// `-z` path list back — `diff-tree --stdin -z`. `stdout_paths` cannot serve it
109/// (no stdin) and `stdout_piped` cannot either (lossy `String`, and the NUL
110/// separators are the whole point).
111pub fn stdout_piped_raw(args: &[&str], stdin: &str) -> Option<Vec<u8>> {
112    use std::io::Write;
113    let mut cmd = Command::new("git");
114    cmd.args(args)
115        .stdin(Stdio::piped())
116        .stdout(Stdio::piped())
117        .stderr(Stdio::null());
118    let mut child = retrying(|| cmd.spawn()).ok()?;
119    child.stdin.take()?.write_all(stdin.as_bytes()).ok()?;
120    let out = child.wait_with_output().ok()?;
121    out.status.success().then_some(out.stdout)
122}
123
124/// As `stdout_piped`, but inside `dir` and taking raw bytes.
125///
126/// `-C dir` matters for `hash-object`: a repository configured for SHA-256
127/// computes a different id than the default, so the identity has to be asked
128/// of THAT repository. Bytes rather than `&str` because the input is a file we
129/// have already read and must not re-encode.
130pub fn stdout_piped_in(dir: &std::path::Path, args: &[&str], stdin: &[u8]) -> Option<String> {
131    use std::io::Write;
132    let mut cmd = Command::new("git");
133    cmd.arg("-C")
134        .arg(dir)
135        .args(args)
136        .stdin(Stdio::piped())
137        .stdout(Stdio::piped())
138        .stderr(Stdio::null());
139    let mut child = retrying(|| cmd.spawn()).ok()?;
140    child.stdin.take()?.write_all(stdin).ok()?;
141    let out = child.wait_with_output().ok()?;
142    out.status
143        .success()
144        .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
145}
146
147/// Raw stdout, untrimmed and not lossy — for a patch, where a trailing newline
148/// and any byte in a binary hunk are load-bearing.
149pub fn stdout_raw(args: &[&str]) -> Option<Vec<u8>> {
150    let mut cmd = Command::new("git");
151    cmd.args(args).stderr(Stdio::null());
152    let out = retrying(|| cmd.output()).ok()?;
153    out.status.success().then_some(out.stdout)
154}
155
156/// As [`stdout_raw`], but a failure keeps git's own reason: its stderr,
157/// trimmed (`safe.directory`, "not a git repository"), or why it could not
158/// be started.
159pub fn stdout_raw_or_why(args: &[&str]) -> Result<Vec<u8>, String> {
160    let mut cmd = Command::new("git");
161    cmd.args(args);
162    let out = retrying(|| cmd.output()).map_err(|e| format!("cannot run git: {e}"))?;
163    if out.status.success() {
164        return Ok(out.stdout);
165    }
166    let said = String::from_utf8_lossy(&out.stderr).trim().to_string();
167    Err(if said.is_empty() {
168        format!("exit {}", out.status.code().unwrap_or(-1))
169    } else {
170        said
171    })
172}
173
174/// Everything a git command said: its exit code, its stdout and its stderr.
175pub struct Output {
176    pub code: i32,
177    pub stdout: String,
178    pub stderr: String,
179}
180
181/// A git command's full result, for the caller that must tell one kind of
182/// failure from another.
183///
184/// [`stdout`] collapses every non-zero exit to `None` and discards stderr,
185/// which is the right shape for "cannot tell, do not block". It is the wrong
186/// shape for reading configuration: `git config --get` exits **1** for a key
187/// nobody set and **128** for a key set to something git itself refuses to
188/// parse, and those two must not become the same answer — one is a default,
189/// the other is a mistake somebody needs to be told about. See `config`.
190pub fn output(args: &[&str]) -> Option<Output> {
191    let mut cmd = Command::new("git");
192    cmd.args(args);
193    full_output(cmd)
194}
195
196/// [`output`] run inside `dir` — for a caller that must ask about a
197/// repository without moving the whole process there (`set_current_dir` is
198/// process-global, and races every test in the binary).
199pub fn output_in(dir: &std::path::Path, args: &[&str]) -> Option<Output> {
200    let mut cmd = Command::new("git");
201    cmd.arg("-C").arg(dir).args(args);
202    full_output(cmd)
203}
204
205fn full_output(mut cmd: Command) -> Option<Output> {
206    cmd.stdin(Stdio::null());
207    let out = retrying(|| cmd.output()).ok()?;
208    Some(Output {
209        // A process killed by a signal has no code. Treat that as "git did not
210        // answer" rather than inventing one; the caller falls back.
211        code: out.status.code()?,
212        stdout: String::from_utf8_lossy(&out.stdout).trim().to_string(),
213        stderr: String::from_utf8_lossy(&out.stderr).trim().to_string(),
214    })
215}
216
217/// How a bounded network probe ended. Exit codes stay visible because the
218/// callers need to keep git's answers apart: `ls-remote --exit-code` exits
219/// **2** for "connected, no such ref" and **128** for "could not connect",
220/// and reading those as one boolean is how offline got reported as
221/// "upstream deleted".
222#[derive(Debug)]
223pub enum Probe {
224    /// Ran to completion with this exit code.
225    Exit(i32),
226    /// Killed at the deadline; carries the budget it exceeded, in seconds.
227    TimedOut(u64),
228    /// Could not spawn, or died to a signal — "git did not answer".
229    Failed,
230}
231
232/// A git command that TALKS TO THE NETWORK, killed at `budget_secs`.
233///
234/// Every other runner in this module waits forever, which is correct for
235/// local plumbing — a `rev-parse` that hangs means the machine is already
236/// lost. A network verb hanging is Tuesday: captive portal, VPN split
237/// brain, a remote that accepts the TCP connect and then says nothing.
238/// Unbounded, that held the push hostage inside the index hold with no
239/// deadline anywhere; the learned response is `--no-verify`, permanently.
240/// `budget_secs == 0` means no deadline (the same opt-out `amont.timeout`
241/// honours). Output is discarded — network callers decide on exit codes.
242pub fn probe(args: &[&str], budget_secs: u64) -> Probe {
243    probe_env(args, budget_secs, &[])
244}
245
246/// Whose ssh a remote call uses.
247#[derive(Clone, Copy, Debug, PartialEq)]
248pub enum Ssh {
249    /// The user configured their own (`GIT_SSH_COMMAND`, `GIT_SSH` or
250    /// `core.sshCommand`); it is left alone — replacing it could drop the
251    /// key selection it exists for. It may prompt; the deadline bounds that.
252    User,
253    /// Ours: batch mode, no prompt, a 10 s connect timeout.
254    Batch,
255}
256
257/// The configuration and environment every call that talks to a REMOTE for a
258/// verifier runs with, as data so both branches are testable without
259/// touching the process environment.
260///
261/// Never a prompt: `GIT_TERMINAL_PROMPT=0` alone is not enough, because git
262/// runs `GIT_ASKPASS` / `core.askPass` / `SSH_ASKPASS` BEFORE consulting it;
263/// a `GIT_ASKPASS` that is present and EMPTY makes git run none of them.
264/// `GCM_INTERACTIVE` and `credential.interactive` tell credential managers
265/// the same; the helpers themselves stay, so stored credentials still work.
266/// Never a stall: curl gives up after 10 s under 1 byte/s, ssh after a 10 s
267/// connect — and the caller's own deadline covers the rest.
268pub fn remote_env(ssh: Ssh) -> (Vec<&'static str>, Vec<(&'static str, &'static str)>) {
269    let args = vec![
270        "-c",
271        "http.lowSpeedLimit=1",
272        "-c",
273        "http.lowSpeedTime=10",
274        "-c",
275        "credential.interactive=never",
276    ];
277    let mut env = vec![
278        ("GIT_TERMINAL_PROMPT", "0"),
279        ("GIT_ASKPASS", ""),
280        ("GCM_INTERACTIVE", "never"),
281    ];
282    if ssh == Ssh::Batch {
283        env.push((
284            "GIT_SSH_COMMAND",
285            "ssh -o BatchMode=yes -o ConnectTimeout=10",
286        ));
287    }
288    (args, env)
289}
290
291/// Whose ssh this environment configures.
292pub fn configured_ssh() -> Ssh {
293    let set = |v: &str| std::env::var_os(v).is_some_and(|v| !v.is_empty());
294    if set("GIT_SSH_COMMAND") || set("GIT_SSH") || succeeds(&["config", "--get", "core.sshCommand"])
295    {
296        Ssh::User
297    } else {
298        Ssh::Batch
299    }
300}
301
302/// `git <args>` against a remote, with [`remote_env`] and a deadline.
303pub fn probe_remote(args: &[&str], budget_secs: u64) -> Probe {
304    let (pre, env) = remote_env(configured_ssh());
305    let mut all: Vec<&str> = pre;
306    all.extend_from_slice(args);
307    probe_env(&all, budget_secs, &env)
308}
309
310/// [`probe`], with extra environment for the child.
311pub fn probe_env(args: &[&str], budget_secs: u64, env: &[(&str, &str)]) -> Probe {
312    probe_run(args, budget_secs, env, false).0
313}
314
315/// [`probe_remote`], keeping what git printed on stdout.
316///
317/// For the callers that need the ANSWER and not only the exit code: `land`
318/// reads a remote tip with `ls-remote`, and a probe that discards stdout
319/// could say "connected" but never which commit. Same environment, same
320/// deadline, same separation of exit codes. The output is drained while the
321/// child runs, so a remote that advertises more than a pipe holds (64 KiB)
322/// does not block until the deadline.
323pub fn probe_remote_stdout(args: &[&str], budget_secs: u64) -> (Probe, String) {
324    let (pre, env) = remote_env(configured_ssh());
325    let mut all: Vec<&str> = pre;
326    all.extend_from_slice(args);
327    probe_run(&all, budget_secs, &env, true)
328}
329
330fn probe_run(
331    args: &[&str],
332    budget_secs: u64,
333    env: &[(&str, &str)],
334    capture: bool,
335) -> (Probe, String) {
336    let mut cmd = Command::new("git");
337    cmd.args(args)
338        .envs(env.iter().copied())
339        .stdin(Stdio::null())
340        .stdout(if capture {
341            Stdio::piped()
342        } else {
343            Stdio::null()
344        })
345        .stderr(Stdio::null());
346    if budget_secs == 0 && !capture {
347        return match retrying(|| cmd.status()) {
348            Ok(s) => (
349                s.code().map(Probe::Exit).unwrap_or(Probe::Failed),
350                String::new(),
351            ),
352            Err(_) => (Probe::Failed, String::new()),
353        };
354    }
355    let Ok(mut child) = retrying(|| cmd.spawn()) else {
356        return (Probe::Failed, String::new());
357    };
358    // Drained while the child runs: a pipe holds 64 KiB, and a child with more
359    // to say (an `ls-remote` of a mirror with thousands of refs) would block
360    // on the full pipe until the deadline kills it.
361    let drained = child.stdout.take().map(|mut out| {
362        let (tx, rx) = std::sync::mpsc::channel();
363        std::thread::spawn(move || {
364            use std::io::Read;
365            let mut text = String::new();
366            // A read error ends the stream early; what was read still counts.
367            let read = out.read_to_string(&mut text);
368            drop(read);
369            // The receiver gave up at the deadline: nobody to tell.
370            let sent = tx.send(text);
371            drop(sent);
372        });
373        rx
374    });
375    // `None` when the stream did not end: a grandchild still holds the pipe
376    // open after the child exited. That is "git did not answer", never an
377    // empty answer, which `land` would read as "no such ref".
378    let read_out = |drained: &Option<std::sync::mpsc::Receiver<String>>| -> Option<String> {
379        match drained {
380            None => Some(String::new()),
381            Some(rx) => rx.recv_timeout(std::time::Duration::from_secs(2)).ok(),
382        }
383    };
384    // No deadline (`budget_secs == 0`) is an hour here, not forever: the
385    // capture path polls like the bounded one and a poll with no end is the
386    // unbounded wait this module exists to avoid.
387    let budget = if budget_secs == 0 { 3600 } else { budget_secs };
388    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(budget);
389    loop {
390        match child.try_wait() {
391            Ok(Some(s)) => {
392                return match read_out(&drained) {
393                    Some(text) => (s.code().map(Probe::Exit).unwrap_or(Probe::Failed), text),
394                    None => (Probe::Failed, String::new()),
395                };
396            }
397            Ok(None) => {}
398            Err(_) => return (Probe::Failed, String::new()),
399        }
400        if std::time::Instant::now() >= deadline {
401            let _ = child.kill();
402            let _ = child.wait();
403            return (Probe::TimedOut(budget), String::new());
404        }
405        std::thread::sleep(std::time::Duration::from_millis(25));
406    }
407}
408
409/// True when the command exits 0. Output discarded.
410pub fn succeeds(args: &[&str]) -> bool {
411    let mut cmd = Command::new("git");
412    cmd.args(args)
413        .stdin(Stdio::null())
414        .stdout(Stdio::null())
415        .stderr(Stdio::null());
416    retrying(|| cmd.status())
417        .map(|s| s.success())
418        .unwrap_or(false)
419}
420
421/// A path list from `diff --name-only`, `diff-tree --name-only` or
422/// `ls-files` — commands whose output is meant to be split into individual
423/// paths, never just read as one blob.
424///
425/// By default git QUOTES any "unusual" byte in a path, non-ASCII included:
426/// `é.json` prints as `"\303\251.json"`. Reading that line as a literal path
427/// looks up a file that does not exist — the caller then treats real,
428/// unstaged content as absent, which is how `StagedOnly` used to lose it.
429/// `-z` disables quoting entirely and NUL-terminates each entry instead, so
430/// there is no escaping left to get wrong. Inserted right after the
431/// subcommand (`args[0]`), which is always a valid position for it on every
432/// command this is used for.
433pub fn stdout_paths(args: &[&str]) -> Option<Vec<String>> {
434    let (first, rest) = args.split_first()?;
435    let mut argv = Vec::with_capacity(args.len() + 1);
436    argv.push(*first);
437    argv.push("-z");
438    argv.extend_from_slice(rest);
439    stdout_raw(&argv).map(|raw| split_nul_paths(&raw))
440}
441
442/// The parsing half of [`stdout_paths`], split out so it can be tested on
443/// literal bytes rather than a real git process — including the byte
444/// sequence a QUOTED path would have produced under the old line-splitting
445/// approach, to prove `-z` output is never reinterpreted that way.
446pub(crate) fn split_nul_paths(raw: &[u8]) -> Vec<String> {
447    raw.split(|&b| b == 0)
448        .filter(|s| !s.is_empty())
449        .map(|s| String::from_utf8_lossy(s).into_owned())
450        .collect()
451}
452
453#[cfg(test)]
454mod retry_tests {
455    use super::*;
456
457    /// The classifier: scheduler hiccups retry, real answers do not.
458    #[test]
459    fn transient_covers_the_fork_pressure_kinds_and_nothing_else() {
460        for code in [4, 11, 26, 35] {
461            assert!(
462                transient(&std::io::Error::from_raw_os_error(code)),
463                "raw {code} is a loaded-machine hiccup"
464            );
465        }
466        assert!(transient(&std::io::Error::from(
467            std::io::ErrorKind::Interrupted
468        )));
469        assert!(!transient(&std::io::Error::from(
470            std::io::ErrorKind::NotFound
471        )));
472        assert!(!transient(&std::io::Error::from_raw_os_error(13))); // EACCES
473    }
474
475    /// Three attempts, then the error is the caller's: a git that is
476    /// genuinely absent must not cost more than ~130ms of patience.
477    #[test]
478    fn retrying_gives_up_after_three_transient_failures() {
479        let mut calls = 0;
480        let r: std::io::Result<()> = retrying(|| {
481            calls += 1;
482            Err(std::io::Error::from_raw_os_error(11))
483        });
484        assert!(r.is_err());
485        assert_eq!(calls, 3);
486    }
487
488    /// A non-transient error returns immediately — a missing git is an
489    /// answer, not a hiccup.
490    #[test]
491    fn a_hard_error_is_not_retried() {
492        let mut calls = 0;
493        let r: std::io::Result<()> = retrying(|| {
494            calls += 1;
495            Err(std::io::Error::from(std::io::ErrorKind::NotFound))
496        });
497        assert!(r.is_err());
498        assert_eq!(calls, 1);
499    }
500
501    /// A success after a hiccup is a success.
502    #[test]
503    fn one_hiccup_then_an_answer_is_an_answer() {
504        let mut calls = 0;
505        let r = retrying(|| {
506            calls += 1;
507            if calls == 1 {
508                Err(std::io::Error::from_raw_os_error(4))
509            } else {
510                Ok(42)
511            }
512        });
513        assert_eq!(r.unwrap(), 42);
514        assert_eq!(calls, 2);
515    }
516}
517
518#[cfg(test)]
519mod tests {
520    use super::*;
521
522    #[test]
523    fn probe_remote_stdout_returns_what_git_printed_and_the_exit_code() {
524        // `probe_remote_stdout` spawns git in the process cwd, which the
525        // cwd-moving tests in `attest` and `gate_stamp` change under it: it ran
526        // inside another test's repository, or one already deleted, and git
527        // exited non-zero. The crate-wide lock is the rule for exactly this.
528        let _cwd = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
529        let dir = std::env::temp_dir().join(format!("amont-probe-stdout-{}", std::process::id()));
530        let _ = std::fs::remove_dir_all(&dir);
531        std::fs::create_dir_all(&dir).expect("mkdir");
532        let run = |args: &[&str]| {
533            let out = Command::new("git")
534                .arg("-C")
535                .arg(&dir)
536                .args(args)
537                .output()
538                .expect("git");
539            assert!(out.status.success(), "{args:?}");
540            String::from_utf8_lossy(&out.stdout).trim().to_string()
541        };
542        run(&["init", "-q", "--initial-branch=main", "."]);
543        run(&[
544            "-c",
545            "user.email=t@e",
546            "-c",
547            "user.name=t",
548            "-c",
549            "core.hooksPath=/dev/null",
550            "commit",
551            "-q",
552            "--allow-empty",
553            "-m",
554            "x",
555        ]);
556        let sha = run(&["rev-parse", "HEAD"]);
557        let url = dir.to_string_lossy().to_string();
558
559        let (probe, out) = probe_remote_stdout(&["ls-remote", &url, "refs/heads/main"], 30);
560        assert!(matches!(probe, Probe::Exit(0)), "{probe:?} {out}");
561        assert!(out.starts_with(&sha), "{out}");
562
563        // Connected, and no such ref: success with nothing on stdout.
564        let (probe, out) = probe_remote_stdout(&["ls-remote", &url, "refs/heads/nope"], 30);
565        assert!(matches!(probe, Probe::Exit(0)), "{probe:?} {out}");
566        assert!(out.trim().is_empty());
567
568        // Could not connect: the exit code stays visible, stdout is empty.
569        let (probe, out) = probe_remote_stdout(&["ls-remote", "/nonexistent/repo.git"], 30);
570        assert!(matches!(probe, Probe::Exit(c) if c != 0));
571        assert!(out.is_empty());
572        let _ = std::fs::remove_dir_all(&dir);
573    }
574
575    #[test]
576    fn splits_on_nul_and_drops_the_trailing_empty_segment() {
577        assert_eq!(
578            split_nul_paths(b"src/main.rs\0Cargo.toml\0"),
579            vec!["src/main.rs", "Cargo.toml"]
580        );
581    }
582
583    #[test]
584    fn empty_input_is_no_paths() {
585        assert_eq!(split_nul_paths(b""), Vec::<String>::new());
586    }
587
588    /// The exact bug this exists to prevent: under `--name-only` without
589    /// `-z`, git would have printed `é.json` as the quoted, LINE-oriented
590    /// text `"\303\251.json"` — literal backslashes, digits and quotes, nine
591    /// bytes standing in for the original two-byte UTF-8 sequence. `-z`
592    /// output carries the real UTF-8 bytes of the path with no such
593    /// reinterpretation, so splitting on NUL must hand them back unchanged.
594    #[test]
595    fn a_non_ascii_path_is_not_reinterpreted_as_its_quoted_form() {
596        let mut raw = "é.json".as_bytes().to_vec();
597        raw.push(0);
598        let got = split_nul_paths(&raw);
599        assert_eq!(got, vec!["é.json".to_string()]);
600        assert_ne!(got[0], "\"\\303\\251.json\"", "must not be the quoted form");
601    }
602}
603
604/// The branch `HEAD` names, or `None` on a detached head — asked of git ONCE
605/// per process and lent to every check that wants it.
606///
607/// Two always-on pre-commit checks (`branch-pattern`, `branch-protect`) open
608/// with this same question. Asked twice it is two spawns on every commit,
609/// which is exactly the o(checks) growth `tests/it/spawn_budget.rs` exists to
610/// refuse; asked once it is the price of one check, however many share it.
611pub fn current_branch() -> Option<&'static str> {
612    static BRANCH: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
613    BRANCH
614        .get_or_init(|| stdout(&["symbolic-ref", "--quiet", "--short", "HEAD"]))
615        .as_deref()
616}
617
618/// Whether any remote is configured. Same device, same reason: a contract
619/// about pushing has nothing to gate in a repository nothing is pushed from,
620/// and more than one check asks before speaking.
621pub fn has_remote() -> bool {
622    static REMOTE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
623    *REMOTE.get_or_init(|| stdout(&["remote"]).is_some_and(|r| !r.is_empty()))
624}
625
626#[cfg(test)]
627mod probe_tests {
628    use super::*;
629
630    /// A remote advertising far more than a pipe holds is read whole, quickly,
631    /// instead of blocking until the deadline.
632    #[test]
633    fn a_long_ls_remote_is_drained_while_the_child_runs() {
634        let dir = std::env::temp_dir().join(format!("amont-probe-{}", std::process::id()));
635        let _ = std::fs::remove_dir_all(&dir); // a leftover of an earlier run, if any
636        let path = dir.display().to_string();
637        let git = |args: &[&str]| {
638            let mut all = vec!["-C", path.as_str()];
639            all.extend_from_slice(args);
640            let mut cmd = Command::new("git");
641            cmd.args(&all).env("GIT_CONFIG_GLOBAL", "/dev/null");
642            for (k, _) in std::env::vars_os() {
643                if k.to_string_lossy().starts_with("GIT_") {
644                    cmd.env_remove(&k);
645                }
646            }
647            cmd.env("GIT_CONFIG_GLOBAL", "/dev/null");
648            cmd.output().expect("git")
649        };
650        std::fs::create_dir_all(&dir).expect("mkdir");
651        assert!(git(&["init", "-q", "--bare"]).status.success());
652        let commit = {
653            let out = Command::new("git")
654                .args([
655                    "-C",
656                    path.as_str(),
657                    "commit-tree",
658                    "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
659                    "-m",
660                    "x",
661                ])
662                .env("GIT_AUTHOR_NAME", "t")
663                .env("GIT_AUTHOR_EMAIL", "t@t")
664                .env("GIT_COMMITTER_NAME", "t")
665                .env("GIT_COMMITTER_EMAIL", "t@t")
666                .env("GIT_CONFIG_GLOBAL", "/dev/null")
667                .output()
668                .expect("commit-tree");
669            String::from_utf8_lossy(&out.stdout).trim().to_string()
670        };
671        assert_eq!(commit.len(), 40, "a commit");
672        let refs: String = (0..3000)
673            .map(|i| format!("{commit} refs/pull/{i}/head-with-a-long-name-to-fill-the-pipe\n"))
674            .collect();
675        std::fs::write(dir.join("packed-refs"), refs).expect("packed-refs");
676        let started = std::time::Instant::now();
677        let (probe, out) = probe_remote_stdout(&["ls-remote", path.as_str()], 20);
678        assert!(matches!(probe, Probe::Exit(0)), "{probe:?}");
679        assert_eq!(out.lines().count(), 3000);
680        assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed());
681        std::fs::remove_dir_all(&dir).expect("clean");
682    }
683
684    /// A child that exits while a grandchild still holds its stdout is "git did
685    /// not answer", not an empty answer that `land` would read as "no such ref".
686    #[test]
687    fn a_stdout_held_open_after_the_child_exits_is_a_failure_not_an_empty_answer() {
688        let started = std::time::Instant::now();
689        // the alias shell leaves a `sleep` behind holding git's stdout
690        let (probe, out) =
691            probe_remote_stdout(&["-c", "alias.holdit=!(sleep 4 &); true", "holdit"], 20);
692        assert!(matches!(probe, Probe::Failed), "{probe:?}");
693        assert_eq!(out, "");
694        assert!(started.elapsed().as_secs() < 4, "{:?}", started.elapsed());
695    }
696}