Skip to main content

gitpoulpi_cli_backend/
process.rs

1use std::collections::HashMap;
2use std::ffi::{OsStr, OsString};
3use std::io::Write;
4use std::path::{Path, PathBuf};
5use std::process::{Command, Output, Stdio};
6use std::sync::OnceLock;
7
8use gitpoulpi_core::domain::NetworkAuth;
9use gitpoulpi_core::Result;
10
11/// `-c key=value` overrides prepended to *every* git invocation.
12///
13/// The user's own git config must never change what this backend parses:
14/// a global `diff.mnemonicPrefix = true` makes git emit `i/f.txt w/f.txt`
15/// instead of `a/f.txt b/f.txt`, which breaks every diff and staging
16/// operation.
17///
18/// Only output *shape* is pinned. Anything expressing what the user wants
19/// git to do (signing, hooks, push/fetch defaults, autocrlf, credentials,
20/// `insteadOf`) is left alone, which is why the global config is
21/// overridden key by key rather than suppressed with `GIT_CONFIG_GLOBAL`.
22///
23/// `diff.external` is *not* in this list: `-c diff.external=` sets it to
24/// the empty string and git then fails with "cannot run : No such file or
25/// directory". Diff commands pass `--no-ext-diff` instead.
26const CONFIG_OVERRIDES: &[&str] = &[
27    // `color.ui = always` would inject ANSI escapes into output that is
28    // parsed, not displayed.
29    "color.ui=false",
30    // Non-ASCII paths verbatim instead of `"\303\251.txt"` octal escapes.
31    "core.quotepath=false",
32    // The knobs that move diff path prefixes off `a/` and `b/`.
33    "diff.mnemonicprefix=false",
34    "diff.noprefix=false",
35    "diff.srcprefix=a/",
36    "diff.dstprefix=b/",
37    // `log.showSignature = true` interleaves gpg output into `git log`.
38    "log.showsignature=false",
39    // Paths relative to the repo root, whatever the process' cwd is.
40    "status.relativepaths=false",
41    // Output is read back as UTF-8, so ask for UTF-8.
42    "i18n.logoutputencoding=UTF-8",
43];
44
45/// Environment variables that must not leak in from the parent process.
46///
47/// `GIT_DIR` and friends are set by git itself when it runs a hook, so a
48/// GitPoulpi launched from inside one would otherwise operate on whatever
49/// repository that hook belonged to rather than on `repo_root`.
50const CLEARED_ENV: &[&str] = &[
51    "GIT_DIR",
52    "GIT_WORK_TREE",
53    "GIT_INDEX_FILE",
54    "GIT_OBJECT_DIRECTORY",
55    "GIT_ALTERNATE_OBJECT_DIRECTORIES",
56    "GIT_COMMON_DIR",
57    "GIT_PREFIX",
58    "GIT_EXTERNAL_DIFF",
59    "GIT_PAGER",
60    // Inherited `-c` overrides; ours are passed as arguments, and git
61    // rebuilds this variable from them for its own subprocesses.
62    "GIT_CONFIG_PARAMETERS",
63    "GIT_CONFIG_COUNT",
64    // git-lfs knobs: a stray value in GitPoulpi's own environment must not
65    // silently skip smudging or redirect progress in every child. The
66    // operations that want them set them explicitly.
67    "GIT_LFS_SKIP_SMUDGE",
68    "GIT_LFS_PROGRESS",
69];
70
71/// Transports a network operation may use: the web, ssh, the git daemon and
72/// local paths (`file` only when the user started the operation, which is
73/// what `user` means). Everything else, remote helpers such as `ext::`
74/// included, is off.
75const TRANSPORT_ALLOWLIST: &[&str] = &[
76    "protocol.allow=never",
77    "protocol.https.allow=always",
78    "protocol.http.allow=always",
79    "protocol.ssh.allow=always",
80    "protocol.git.allow=always",
81    "protocol.file.allow=user",
82];
83
84/// Prepends the global flags and config overrides to a command's own
85/// arguments. `--no-pager` is belt-and-braces - git already skips the
86/// pager when stdout is a pipe - but costs nothing and covers
87/// `GIT_PAGER`-style surprises.
88fn full_args(args: &[&str]) -> Vec<String> {
89    full_args_with(&[], args)
90}
91
92/// [`full_args`] with `extra` (already `-c key=value` pairs, see
93/// [`apply_network_auth`]) among the global options, after the transport
94/// allowlist and the shape overrides and before the command's own arguments.
95fn full_args_with(extra: &[String], args: &[&str]) -> Vec<String> {
96    let mut out = Vec::with_capacity(args.len() + CONFIG_OVERRIDES.len() * 2 + extra.len() + 1);
97    out.push("--no-pager".to_string());
98    // Submodule clones run with `GIT_PROTOCOL_FROM_USER=0`, which `user`
99    // would refuse for a local-path submodule: allow `file` for those.
100    let submodules = args
101        .iter()
102        .any(|a| *a == "submodule" || *a == "--recurse-submodules");
103    for kv in TRANSPORT_ALLOWLIST {
104        out.push("-c".to_string());
105        let kv = if submodules && *kv == "protocol.file.allow=user" {
106            "protocol.file.allow=always"
107        } else {
108            kv
109        };
110        out.push(kv.to_string());
111    }
112    for kv in CONFIG_OVERRIDES {
113        out.push("-c".to_string());
114        out.push((*kv).to_string());
115    }
116    out.extend(extra.iter().cloned());
117    out.extend(args.iter().map(|a| (*a).to_string()));
118    out
119}
120
121thread_local! {
122    static SPAWNS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
123}
124
125/// Every `git` command built by any thread of this process (an always-on
126/// atomic: one relaxed add per spawn, which is nothing next to a spawn).
127static TOTAL_SPAWNS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
128
129fn count_spawn() {
130    SPAWNS.with(|c| c.set(c.get() + 1));
131    TOTAL_SPAWNS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
132}
133
134/// How many `git` commands the whole process has built so far, on any
135/// thread. Unlike the per-thread count it sees the daemon's worker threads, so
136/// the daemon tests and `xtask perf` use it; callers that share a process
137/// with other git users must serialise themselves to diff it.
138pub fn total_spawn_count() -> u64 {
139    TOTAL_SPAWNS.load(std::sync::atomic::Ordering::Relaxed)
140}
141
142/// How many `git` commands the calling thread has built so far (every spawn
143/// goes through [`git`] or [`git_async`]). Per thread, so parallel tests do
144/// not see each other; a test diffs it to assert a call spawns nothing.
145#[cfg(all(test, feature = "lfs"))]
146pub fn spawn_count() -> u64 {
147    SPAWNS.with(std::cell::Cell::get)
148}
149
150/// The `git` executable every spawn uses, resolved once per process.
151///
152/// Order: the `GITPOULPI_GIT` environment variable; on Windows the real
153/// `mingw64\bin\git.exe` when `git` on `PATH` is Git for Windows' `cmd\git.exe`
154/// shim (the shim starts a second process, roughly doubling every spawn);
155/// otherwise plain `git`, left to the OS `PATH` lookup.
156pub fn git_program() -> &'static OsStr {
157    static PROGRAM: OnceLock<OsString> = OnceLock::new();
158    PROGRAM.get_or_init(resolve_git_program)
159}
160
161fn resolve_git_program() -> OsString {
162    if let Some(p) = std::env::var_os("GITPOULPI_GIT").filter(|p| !p.is_empty()) {
163        return p;
164    }
165    #[cfg(windows)]
166    if let Some(real) = windows_unshimmed_git(std::env::var_os("PATH").as_deref()) {
167        return real.into_os_string();
168    }
169    OsString::from("git")
170}
171
172/// Finds `git.exe` on `path`; when it sits in a `cmd` directory next to a
173/// `mingw64\bin\git.exe`, returns that real binary instead.
174#[cfg_attr(not(windows), allow(dead_code))]
175fn windows_unshimmed_git(path: Option<&OsStr>) -> Option<PathBuf> {
176    let path = path?;
177    let shim = std::env::split_paths(path)
178        .map(|d| d.join("git.exe"))
179        .find(|c| c.is_file())?;
180    let dir = shim.parent()?;
181    if !dir.file_name()?.eq_ignore_ascii_case("cmd") {
182        return None;
183    }
184    let real = dir.parent()?.join("mingw64").join("bin").join("git.exe");
185    real.is_file().then_some(real)
186}
187
188/// `PATH` for children when the resolved git is a Git for Windows
189/// `mingw64\bin\git.exe`: the shim put `mingw64\bin` and `usr\bin` on `PATH`
190/// (hooks need `sh`, credential helpers and ssh live there), so the direct
191/// binary must do it itself. `None` when nothing needs adding.
192fn child_path() -> Option<&'static OsString> {
193    static PATH_VAR: OnceLock<Option<OsString>> = OnceLock::new();
194    PATH_VAR
195        .get_or_init(|| {
196            let prog = Path::new(git_program());
197            let bin = prog.parent()?;
198            if !bin.ends_with(Path::new("mingw64").join("bin")) {
199                return None;
200            }
201            let root = bin.parent()?.parent()?;
202            let mut paths = vec![bin.to_path_buf(), root.join("usr").join("bin")];
203            paths.extend(std::env::split_paths(&std::env::var_os("PATH")?));
204            std::env::join_paths(paths).ok()
205        })
206        .as_ref()
207}
208
209fn apply_git_env(cmd: &mut Command) {
210    if let Some(p) = child_path() {
211        cmd.env("PATH", p);
212    }
213}
214
215/// How network commands get HTTPS credentials (`credentials.https_mode`).
216/// Process-wide because the daemon owns the process and re-reads the
217/// setting before each network operation.
218#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
219pub enum CredentialMode {
220    /// git's own handling: the configured helper, then its prompt.
221    #[default]
222    Helper,
223    /// No helper; git may prompt on a terminal.
224    Prompt,
225    /// No helper and no prompt: anonymous access only.
226    None,
227}
228
229static CREDENTIAL_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
230
231/// Sets the mode every later network command uses.
232pub fn set_credential_mode(mode: CredentialMode) {
233    CREDENTIAL_MODE.store(mode as u8, std::sync::atomic::Ordering::Relaxed);
234}
235
236pub fn credential_mode() -> CredentialMode {
237    match CREDENTIAL_MODE.load(std::sync::atomic::Ordering::Relaxed) {
238        1 => CredentialMode::Prompt,
239        2 => CredentialMode::None,
240        _ => CredentialMode::Helper,
241    }
242}
243
244/// The global `-c` arguments and environment a mode adds.
245fn credential_settings(mode: CredentialMode) -> (&'static [&'static str], Option<&'static str>) {
246    match mode {
247        CredentialMode::Helper => (&[], None),
248        // An empty value resets the helper list.
249        CredentialMode::Prompt => (&["-c", "credential.helper="], None),
250        CredentialMode::None => (&["-c", "credential.helper="], Some("0")),
251    }
252}
253
254/// The private (else public) key file `ssh.private_key_path` /
255/// `ssh.public_key_path` name, process-wide like the credential mode: the
256/// daemon re-reads the setting before each network operation.
257static SSH_KEY: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
258
259/// Sets the key file every later network command offers to ssh (`None`: leave
260/// ssh to the agent and its own configuration). See [`ssh_key_command`].
261pub fn set_ssh_key(path: Option<String>) {
262    if let Ok(mut slot) = SSH_KEY.write() {
263        *slot = path.filter(|p| !p.trim().is_empty());
264    }
265}
266
267/// The `GIT_SSH_COMMAND` a network command needs to use the configured key,
268/// or `None` when it must be left alone. Precedence, highest first - the
269/// configured key only fills a gap, it never overrides:
270///
271/// 1. `GIT_SSH_COMMAND` / `GIT_SSH` already in the environment,
272/// 2. `core.sshCommand` in the effective git config (the repository's own
273///    pin from "SSH key for this repository", or a global one),
274/// 3. the configured key (`ssh -i "<key>" -o IdentitiesOnly=yes`),
275/// 4. nothing: ssh's own configuration and the ssh-agent.
276pub fn ssh_key_command(repo_root: &Path) -> Option<String> {
277    let key = SSH_KEY.read().ok()?.clone()?;
278    let user_env = |name: &str| std::env::var_os(name).is_some_and(|v| !v.is_empty());
279    if user_env("GIT_SSH_COMMAND") || user_env("GIT_SSH") {
280        return None;
281    }
282    // Only asked when a key is configured, so nobody else pays the spawn.
283    let pinned = git(repo_root, &["config", "--get", "core.sshCommand"])
284        .output()
285        .ok()
286        .filter(|o| o.status.success())
287        .is_some_and(|o| !String::from_utf8_lossy(&o.stdout).trim().is_empty());
288    if pinned {
289        return None;
290    }
291    Some(gitpoulpi_core::repo_config::ssh_command_for_key(
292        &expand_home(&key),
293    ))
294}
295
296/// How each repository's network git processes authenticate, keyed by the
297/// canonical repository root (ADR-0010). Process-wide like the credential mode
298/// and key it overrides, because the network operations are free functions
299/// that only receive a repository root; keyed by repository, because one
300/// daemon serves many of them at once and a per-repository setting kept in
301/// a single slot would race between two concurrent fetches.
302static NETWORK_AUTH: std::sync::RwLock<Option<HashMap<PathBuf, NetworkAuth>>> =
303    std::sync::RwLock::new(None);
304
305/// The registry key of a repository root: canonical when it can be, so a
306/// symlinked or relative spelling finds the same entry.
307fn auth_key(repo_root: &Path) -> PathBuf {
308    std::fs::canonicalize(repo_root).unwrap_or_else(|_| repo_root.to_path_buf())
309}
310
311/// Sets (`Some`) or removes (`None`) the entry of the repository at
312/// `repo_root`. Memory only.
313pub(crate) fn set_network_auth(repo_root: &Path, auth: Option<NetworkAuth>) {
314    let key = auth_key(repo_root);
315    if let Ok(mut slot) = NETWORK_AUTH.write() {
316        let map = slot.get_or_insert_with(HashMap::new);
317        match auth {
318            Some(auth) => {
319                map.insert(key, auth);
320            }
321            None => {
322                map.remove(&key);
323            }
324        }
325    }
326}
327
328fn network_auth_for(repo_root: &Path) -> Option<NetworkAuth> {
329    let slot = NETWORK_AUTH.read().ok()?;
330    let map = slot.as_ref().filter(|m| !m.is_empty())?;
331    map.get(&auth_key(repo_root)).cloned()
332}
333
334/// The one place a network command gets its credentials and ssh command, for
335/// the async commands (`git_async`) and the synchronous one (`run_network`)
336/// alike, so submodules and LFS cannot drift from fetch and push.
337///
338/// With an entry for the repository, [`NetworkAuth`] applies **instead of**
339/// the process-wide credential mode and ssh key. Without one, the mode and
340/// key apply as they always did.
341///
342/// The environment is set on `cmd` now. The `-c` arguments cannot be added to
343/// a command that already holds its arguments (they must come before the
344/// subcommand), so they are returned for the caller to put among the global
345/// options, see [`full_args_with`].
346fn apply_network_auth(cmd: &mut Command, repo_root: &Path) -> Vec<String> {
347    let mut args = Vec::new();
348    let set = |args: &mut Vec<String>, kv: String| {
349        args.push("-c".to_string());
350        args.push(kv);
351    };
352    let Some(auth) = network_auth_for(repo_root) else {
353        let (credential_args, prompt) = credential_settings(credential_mode());
354        args.extend(credential_args.iter().map(|a| (*a).to_string()));
355        if let Some(prompt) = prompt {
356            cmd.env("GIT_TERMINAL_PROMPT", prompt);
357        }
358        if let Some(ssh) = ssh_key_command(repo_root) {
359            cmd.env("GIT_SSH_COMMAND", ssh);
360        }
361        return args;
362    };
363    if let Some(helpers) = &auth.credential_helpers {
364        // The empty value resets the list built so far: every config file's
365        // (the repository's and what it includes), URL-scoped entries too.
366        set(&mut args, "credential.helper=".to_string());
367        for helper in helpers {
368            set(&mut args, format!("credential.helper={helper}"));
369        }
370        for (url, helper) in &auth.credential_url_helpers {
371            set(&mut args, format!("credential.{url}.helper={helper}"));
372        }
373    }
374    if let Some(user) = &auth.credential_username {
375        set(&mut args, format!("credential.username={user}"));
376    }
377    if auth.no_prompt {
378        set(&mut args, "core.askPass=".to_string());
379        cmd.env("GIT_TERMINAL_PROMPT", "0");
380        cmd.env_remove("GIT_ASKPASS");
381        cmd.env_remove("SSH_ASKPASS");
382    }
383    if auth.reset_extra_header {
384        set(&mut args, "http.extraHeader=".to_string());
385    }
386    if let Some(ssh) = &auth.ssh_command {
387        // Ranks above `core.sshCommand`, and replaces one the user exported.
388        cmd.env("GIT_SSH_COMMAND", ssh);
389    }
390    for (name, value) in &auth.env {
391        cmd.env(name, value);
392    }
393    args
394}
395
396/// `~/x` as the user's home plus `x` (ssh would, but the shell git runs the
397/// command in does not expand a quoted tilde).
398pub fn expand_home(path: &str) -> String {
399    let rest = path.strip_prefix("~/").or_else(|| path.strip_prefix("~\\"));
400    match (
401        rest,
402        std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")),
403    ) {
404        (Some(rest), Some(home)) => Path::new(&home).join(rest).display().to_string(),
405        _ => path.to_string(),
406    }
407}
408
409/// Builds a `git` command that is immune to the ambient git environment.
410pub(crate) fn git(repo_root: &Path, args: &[&str]) -> Command {
411    count_spawn();
412    let mut cmd = Command::new(git_program());
413    apply_git_env(&mut cmd);
414    cmd.args(full_args(args).iter().map(OsStr::new));
415    cmd.current_dir(repo_root);
416    for key in CLEARED_ENV {
417        cmd.env_remove(key);
418    }
419    cmd
420}
421
422/// Async twin of [`git`], for the network operations that run on tokio.
423pub(crate) fn git_async(repo_root: &Path, args: &[&str]) -> tokio::process::Command {
424    count_spawn();
425    let mut cmd = tokio::process::Command::new(git_program());
426    if let Some(p) = child_path() {
427        cmd.env("PATH", p);
428    }
429    let network_args = apply_network_auth(cmd.as_std_mut(), repo_root);
430    // A network command never waits on the terminal (see
431    // `tree_kill::spawn_guarded`, which also drops the controlling one).
432    cmd.stdin(Stdio::null());
433    cmd.args(full_args_with(&network_args, args).iter().map(OsStr::new));
434    cmd.current_dir(repo_root);
435    for key in CLEARED_ENV {
436        cmd.env_remove(key);
437    }
438    cmd
439}
440
441/// Turns a failed git invocation's stderr into an error: the typed
442/// [`gitpoulpi_core::Error::LfsUnavailable`] when git says an LFS filter or
443/// hook could not run because `git-lfs` is missing, otherwise the plain
444/// `Backend` error naming the command.
445pub(crate) fn failed(args: &[&str], stderr: &str) -> gitpoulpi_core::Error {
446    failed_with(args, None, stderr)
447}
448
449/// [`failed`] knowing the exit code. The error carries an
450/// [`gitpoulpi_core::ErrorDetail`] (redacted command line, exit code and the
451/// tail of stderr); its message is the same text as ever, with credentials
452/// masked.
453pub(crate) fn failed_with(
454    args: &[&str],
455    exit_code: Option<i32>,
456    stderr: &str,
457) -> gitpoulpi_core::Error {
458    classify_lfs_failure(stderr).unwrap_or_else(|| {
459        let message = gitpoulpi_core::redact(&format!("git {} failed: {}", args.join(" "), stderr));
460        gitpoulpi_core::Error::git(
461            message,
462            gitpoulpi_core::ErrorDetail::from_git(args, exit_code, stderr),
463        )
464    })
465}
466
467/// Recognises the messages git prints when a repository is configured for
468/// Git LFS (filters in config, or the hook in `.git/hooks`) but the
469/// `git-lfs` program is not installed. Matched on fragments that git and
470/// the shell have printed verbatim on every platform tried; each is
471/// pinned against a recorded real message in the tests below.
472pub fn classify_lfs_failure(stderr: &str) -> Option<gitpoulpi_core::Error> {
473    const MISSING: &[&str] = &[
474        // Linux / macOS: the filter or hook shell could not find it.
475        "git-lfs: command not found",
476        "git-lfs: not found",
477        // `git lfs ...` when the subcommand is absent.
478        "'lfs' is not a git command",
479        // The pre-push / post-checkout hook shim git-lfs installs.
480        "'git-lfs' was not found on your path",
481        // Windows: CreateProcess failing on the filter command.
482        "cannot run git-lfs",
483    ];
484    let lower = stderr.to_lowercase();
485    MISSING
486        .iter()
487        .any(|needle| lower.contains(needle))
488        .then_some(gitpoulpi_core::Error::LfsUnavailable {
489            reason: gitpoulpi_core::domain::LfsUnavailableReason::Missing,
490        })
491}
492
493pub(crate) fn spawn_failed(e: std::io::Error) -> gitpoulpi_core::Error {
494    gitpoulpi_core::Error::Backend(format!("failed to spawn git: {e}"))
495}
496
497fn utf8_stdout(stdout: Vec<u8>) -> Result<String> {
498    String::from_utf8(stdout)
499        .map_err(|e| gitpoulpi_core::Error::Backend(format!("git output was not utf-8: {e}")))
500}
501
502/// `output` itself when git succeeded, else the [`failed`] error.
503fn checked(args: &[&str], output: Output) -> Result<Output> {
504    if output.status.success() {
505        Ok(output)
506    } else {
507        Err(failed_with(
508            args,
509            output.status.code(),
510            &String::from_utf8_lossy(&output.stderr),
511        ))
512    }
513}
514
515/// The [`StatusOutput`] of a run whose failure is an expected outcome;
516/// only a missing `git-lfs` is still an `Err`.
517fn status_of(output: &Output) -> Result<StatusOutput> {
518    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
519    if !output.status.success() {
520        if let Some(e) = classify_lfs_failure(&stderr) {
521            return Err(e);
522        }
523    }
524    Ok(StatusOutput {
525        success: output.status.success(),
526        stderr,
527        exit_code: output.status.code(),
528    })
529}
530
531/// Runs an abort (`merge --abort`, `rebase --abort`, ...), whose reset step
532/// fails with "Entry 'x' not uptodate. Cannot merge." when the index's cached
533/// stat data of a file is stale (an antivirus, an indexer or a line-ending
534/// filter touched it; common on Windows). That is not a real change: refresh
535/// the index (`update-index -q --refresh` compares contents) and run the abort
536/// once more. Git's messages are forced to English for the match. The result
537/// is the last run; it still names the files when they really differ.
538pub(crate) fn run_abort(repo_root: &Path, args: &[&str]) -> Result<StatusOutput> {
539    let english = [("LC_ALL", "C"), ("LANGUAGE", "C")];
540    let first = run_status_with_env(repo_root, args, &english)?;
541    if first.success || not_uptodate_paths(&first.stderr).is_empty() {
542        return Ok(first);
543    }
544    // A refresh that fails (it exits 1 when files need an update) still
545    // refreshed what it could: the retry decides.
546    let _ = run_status_with_env(repo_root, &["update-index", "-q", "--refresh"], &english);
547    run_status_with_env(repo_root, args, &english)
548}
549
550/// The files of git's "Entry 'x' not uptodate. Cannot merge." lines.
551pub(crate) fn not_uptodate_paths(stderr: &str) -> Vec<String> {
552    let mut out = Vec::new();
553    for line in stderr.lines() {
554        let Some(at) = line.find("Entry '") else {
555            continue;
556        };
557        let rest = &line[at + "Entry '".len()..];
558        if let Some(end) = rest.find("' not uptodate") {
559            let path = rest[..end].to_string();
560            if !out.contains(&path) {
561                out.push(path);
562            }
563        }
564    }
565    out
566}
567
568/// The error for an abort that failed: the files with local changes it would
569/// overwrite as a typed refusal, else git's failure as usual.
570pub(crate) fn abort_failed(args: &[&str], out: &StatusOutput) -> gitpoulpi_core::Error {
571    let paths = not_uptodate_paths(&out.stderr);
572    if paths.is_empty() {
573        failed_with(args, out.exit_code, &out.stderr)
574    } else {
575        gitpoulpi_core::Error::ConflictRefused(
576            gitpoulpi_core::domain::ConflictRefusal::LocalChanges { paths },
577        )
578    }
579}
580
581fn with_env(mut cmd: Command, env: &[(&str, &str)]) -> Command {
582    for (key, value) in env {
583        cmd.env(key, value);
584    }
585    cmd
586}
587
588fn join_writer(writer: std::thread::JoinHandle<std::io::Result<()>>) -> Result<()> {
589    writer
590        .join()
591        .map_err(|_| gitpoulpi_core::Error::Backend("git stdin writer panicked".into()))?
592        .map_err(|e| gitpoulpi_core::Error::Backend(format!("failed to write git stdin: {e}")))
593}
594
595/// Spawns `cmd` with `input` on its stdin and waits for it.
596///
597/// stdin is written from a thread of its own: `git cat-file --batch`
598/// answers while it is still reading, and once both pipes are full a
599/// writer that waits for its whole input to be taken before reading
600/// anything would wait forever. The writer's result is returned for the
601/// caller to check once the exit status has been.
602fn run_piped_stdin(
603    mut cmd: Command,
604    input: Vec<u8>,
605) -> Result<(Output, std::thread::JoinHandle<std::io::Result<()>>)> {
606    let mut child = cmd
607        .stdin(Stdio::piped())
608        .stdout(Stdio::piped())
609        .stderr(Stdio::piped())
610        .spawn()
611        .map_err(spawn_failed)?;
612    let mut pipe = child.stdin.take().expect("stdin was piped");
613    let writer = std::thread::spawn(move || pipe.write_all(&input));
614    let output = child
615        .wait_with_output()
616        .map_err(|e| gitpoulpi_core::Error::Backend(format!("failed to wait for git: {e}")))?;
617    Ok((output, writer))
618}
619
620/// Runs `git <args>` in `repo_root` and returns stdout as UTF-8. Every
621/// SystemGitBackend method goes through this so error formatting and
622/// working-directory handling stay consistent.
623pub fn run(repo_root: &Path, args: &[&str]) -> Result<String> {
624    let output = git(repo_root, args).output().map_err(spawn_failed)?;
625    utf8_stdout(checked(args, output)?.stdout)
626}
627
628/// [`run`] with git's messages forced to English, for the one caller that
629/// recognises a message of git's (`stash push`'s "No local changes to save").
630pub fn run_in_english(repo_root: &Path, args: &[&str]) -> Result<String> {
631    let output = git(repo_root, args)
632        .env("LC_ALL", "C")
633        .env("LANGUAGE", "C")
634        .output()
635        .map_err(spawn_failed)?;
636    utf8_stdout(checked(args, output)?.stdout)
637}
638
639/// [`run`] for commands that may reach a remote (`submodule update` clones
640/// and fetches): `credentials.https_mode` applies, as it does to the async
641/// network commands.
642#[cfg(feature = "submodule")]
643pub fn run_network(repo_root: &Path, args: &[&str]) -> Result<String> {
644    count_spawn();
645    let mut cmd = Command::new(git_program());
646    apply_git_env(&mut cmd);
647    let network_args = apply_network_auth(&mut cmd, repo_root);
648    cmd.args(full_args_with(&network_args, args).iter().map(OsStr::new));
649    cmd.current_dir(repo_root);
650    for key in CLEARED_ENV {
651        cmd.env_remove(key);
652    }
653    cmd.stdin(Stdio::null());
654    #[cfg(unix)]
655    {
656        use std::os::unix::process::CommandExt;
657        // SAFETY: `setsid` is async-signal-safe. No controlling terminal, so
658        // ssh cannot stop on a prompt in a background process group.
659        unsafe {
660            cmd.pre_exec(|| {
661                libc::setsid();
662                Ok(())
663            });
664        }
665    }
666    let output = cmd.output().map_err(spawn_failed)?;
667    utf8_stdout(checked(args, output)?.stdout)
668}
669
670/// Like [`run`], but hands back stdout as raw bytes.
671///
672/// `run` validates UTF-8, which is right for every machine-readable
673/// *format* git produces but wrong for file content: `git cat-file blob`
674/// on a PNG is not an error, it is a PNG. Callers decide what those bytes
675/// are (see `gitpoulpi_core::domain::BlobContent::from_bytes`).
676///
677/// Still goes through [`git`], so the config pinning and the cleared
678/// `GIT_DIR` family apply here exactly as everywhere else.
679pub fn run_bytes(repo_root: &Path, args: &[&str]) -> Result<Vec<u8>> {
680    let output = git(repo_root, args).output().map_err(spawn_failed)?;
681    Ok(checked(args, output)?.stdout)
682}
683
684/// [`run_bytes`] for a query whose "nothing found" is exit status 1 (`git
685/// grep`): that gives an empty answer, any other failure is an error.
686pub fn run_lenient_bytes(repo_root: &Path, args: &[&str]) -> Result<Vec<u8>> {
687    let output = git(repo_root, args).output().map_err(spawn_failed)?;
688    if output.status.code() == Some(1) {
689        return Ok(output.stdout);
690    }
691    Ok(checked(args, output)?.stdout)
692}
693
694/// Runs `git <args>` in `repo_root`, writing `stdin` to the child process --
695/// used for `git apply --cached [--reverse] -` when staging/unstaging a
696/// single hunk or a subset of lines.
697pub fn run_with_stdin(repo_root: &Path, args: &[&str], stdin: &str) -> Result<String> {
698    run_with_env_and_stdin(repo_root, args, &[], stdin)
699}
700
701/// [`run_with_stdin`] for input that is not text (a raw tag object).
702pub fn run_with_stdin_bytes(repo_root: &Path, args: &[&str], stdin: &[u8]) -> Result<String> {
703    let (output, writer) = run_piped_stdin(git(repo_root, args), stdin.to_vec())?;
704    let output = checked(args, output)?;
705    join_writer(writer)?;
706    utf8_stdout(output.stdout)
707}
708
709/// [`run_with_stdin`] with extra environment variables - for
710/// `git commit-tree`, whose author identity and date can only be given
711/// through `GIT_AUTHOR_*`.
712///
713/// stdin is written from its own thread, see [`run_piped_stdin`].
714pub fn run_with_env_and_stdin(
715    repo_root: &Path,
716    args: &[&str],
717    env: &[(&str, &str)],
718    stdin: &str,
719) -> Result<String> {
720    let cmd = with_env(git(repo_root, args), env);
721    let (output, writer) = run_piped_stdin(cmd, stdin.as_bytes().to_vec())?;
722    let output = checked(args, output)?;
723    join_writer(writer)?;
724    utf8_stdout(output.stdout)
725}
726
727/// Result of a git invocation that may legitimately fail (e.g. a merge
728/// stopping on conflicts) - callers inspect `success`/`stderr` themselves
729/// instead of getting an `Err`.
730pub struct StatusOutput {
731    pub success: bool,
732    pub stderr: String,
733    pub exit_code: Option<i32>,
734}
735
736/// Like `run`, but never turns a non-zero exit into `Err` - used for
737/// commands (merge, rebase, cherry-pick, revert) whose failure is an
738/// expected outcome (conflicts) that callers turn into a typed `*Outcome`.
739pub fn run_status(repo_root: &Path, args: &[&str]) -> Result<StatusOutput> {
740    status_of(&git(repo_root, args).output().map_err(spawn_failed)?)
741}
742
743/// [`run_status`] with extra environment variables - interactive rebase
744/// needs `GIT_SEQUENCE_EDITOR`/`GITPOULPI_TODO`/`GIT_EDITOR` set for the
745/// duration of a single `git rebase` invocation.
746pub fn run_status_with_env(
747    repo_root: &Path,
748    args: &[&str],
749    env: &[(&str, &str)],
750) -> Result<StatusOutput> {
751    let output = with_env(git(repo_root, args), env)
752        .output()
753        .map_err(spawn_failed)?;
754    status_of(&output)
755}
756
757/// Runs `git <args>` to its end and captures it, like `.output()`, but
758/// under a process-tree guard: dropping the future (a canceled job) kills git
759/// and every helper it started, and removes the lock files a hard kill leaves
760/// (`cancel_cleanup`). Disarmed once git has ended.
761async fn output_guarded(repo_root: &Path, args: &[&str]) -> Result<Output> {
762    let mut cmd = git_async(repo_root, args);
763    crate::tree_kill::captured(&mut cmd);
764    let cleanup = crate::cancel_cleanup::for_command(repo_root, args);
765    let (child, mut guard) = crate::tree_kill::spawn_guarded(&mut cmd).map_err(spawn_failed)?;
766    let output = child.wait_with_output().await.map_err(spawn_failed)?;
767    guard.disarm();
768    if let Some(mut cleanup) = cleanup {
769        cleanup.disarm();
770    }
771    Ok(output)
772}
773
774/// Async variant of `run`, for network operations (fetch/pull/push/clone)
775/// that must not block the daemon's executor while they hit the network.
776pub async fn run_async(repo_root: &Path, args: &[&str]) -> Result<String> {
777    let output = output_guarded(repo_root, args).await?;
778    utf8_stdout(checked(args, output)?.stdout)
779}
780
781/// Everything an invocation that may legitimately fail produced: exit
782/// status, stdout *and* stderr.
783pub struct FullOutput {
784    pub success: bool,
785    pub stdout: String,
786    pub stderr: String,
787    pub exit_code: Option<i32>,
788}
789
790/// Async, never turns a non-zero exit into `Err`, and keeps stdout --
791/// for `git push --porcelain`, whose rejection report is on stdout and
792/// arrives *with* a failing exit status.
793pub async fn run_full_async(repo_root: &Path, args: &[&str]) -> Result<FullOutput> {
794    let output = output_guarded(repo_root, args).await?;
795    let status = status_of(&output)?;
796    Ok(FullOutput {
797        success: status.success,
798        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
799        stderr: status.stderr,
800        exit_code: status.exit_code,
801    })
802}
803
804/// [`run_full_async`] with git's messages forced to English, for callers that
805/// recognise a refusal by its words (`push --atomic` on a server that lacks
806/// it). Same credential and cancel behaviour.
807pub(crate) async fn run_full_async_english(repo_root: &Path, args: &[&str]) -> Result<FullOutput> {
808    run_full_async_with(repo_root, args, false).await
809}
810
811/// The ssh command a network command of `repo_root` would run, with `-v`
812/// appended, so ssh reports which key the server accepted. `cmd` is the
813/// command built by [`git_async`]: what [`apply_network_auth`] chose for it
814/// (an entry's command, or the global key's) is read back from its
815/// environment; otherwise git's own order applies: an exported
816/// `GIT_SSH_COMMAND`, `core.sshCommand`, an exported `GIT_SSH`, plain `ssh`.
817/// Only a connection test asks for this; no ordinary operation is verbose.
818fn verbose_ssh_command(cmd: &tokio::process::Command, repo_root: &Path) -> String {
819    let chosen = cmd
820        .as_std()
821        .get_envs()
822        .find(|(k, _)| *k == "GIT_SSH_COMMAND")
823        .and_then(|(_, v)| v.map(|v| v.to_string_lossy().into_owned()));
824    let base = chosen
825        .or_else(|| {
826            std::env::var("GIT_SSH_COMMAND")
827                .ok()
828                .filter(|v| !v.is_empty())
829        })
830        .or_else(|| {
831            git(repo_root, &["config", "--get", "core.sshCommand"])
832                .output()
833                .ok()
834                .filter(|o| o.status.success())
835                .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
836                .filter(|v| !v.is_empty())
837        })
838        .or_else(|| {
839            std::env::var("GIT_SSH")
840                .ok()
841                .filter(|v| !v.is_empty())
842                .map(|v| gitpoulpi_core::repo_config::sh_quote_path(&v))
843        })
844        .unwrap_or_else(|| "ssh".to_string());
845    format!("{base} -v")
846}
847
848/// [`run_full_async_english`], optionally with ssh run verbose (see
849/// [`verbose_ssh_command`]).
850pub(crate) async fn run_full_async_with(
851    repo_root: &Path,
852    args: &[&str],
853    ssh_verbose: bool,
854) -> Result<FullOutput> {
855    let mut cmd = git_async(repo_root, args);
856    cmd.env("LC_ALL", "C").env("LANGUAGE", "C");
857    if ssh_verbose {
858        let ssh = verbose_ssh_command(&cmd, repo_root);
859        cmd.env("GIT_SSH_COMMAND", ssh);
860    }
861    crate::tree_kill::captured(&mut cmd);
862    let (child, mut guard) = crate::tree_kill::spawn_guarded(&mut cmd).map_err(spawn_failed)?;
863    let output = child.wait_with_output().await.map_err(spawn_failed)?;
864    guard.disarm();
865    let status = status_of(&output)?;
866    Ok(FullOutput {
867        success: status.success,
868        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
869        stderr: status.stderr,
870        exit_code: status.exit_code,
871    })
872}
873
874/// Runs `git <args>` in `repo_root`, handing every *chunk* of stderr to
875/// `on_stderr` as it arrives. Only `clone` uses this, for its progress
876/// output.
877///
878/// - **Chunks, not lines.** git separates progress updates with `\r`, so a
879///   line-oriented reader sees nothing until the phase ends.
880/// - **stdout is piped and drained**: a child whose stdout pipe fills
881///   blocks forever, and `git clone` on a large repository fills one.
882pub async fn run_streaming_stderr<F>(
883    repo_root: &Path,
884    args: &[&str],
885    mut on_stderr: F,
886) -> Result<()>
887where
888    F: FnMut(&str) + Send,
889{
890    use tokio::io::AsyncReadExt;
891
892    let mut cmd = git_async(repo_root, args);
893    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
894    // Dropping this future (a canceled clone) kills git and its helpers.
895    let (mut child, mut tree) = crate::tree_kill::spawn_guarded(&mut cmd).map_err(spawn_failed)?;
896
897    let mut stdout = child.stdout.take().expect("stdout was piped");
898    let drain_stdout = tokio::spawn(async move {
899        let mut sink = Vec::new();
900        let _ = stdout.read_to_end(&mut sink).await;
901    });
902
903    let mut stderr = child.stderr.take().expect("stderr was piped");
904    let mut buf = [0u8; 4096];
905    let mut tail = String::new();
906    loop {
907        match stderr.read(&mut buf).await {
908            Ok(0) | Err(_) => break,
909            Ok(n) => {
910                let chunk = String::from_utf8_lossy(&buf[..n]);
911                tail.push_str(&chunk);
912                // Keep only the last few KiB: the whole point is the
913                // *latest* state, and a clone of a big repository emits
914                // megabytes of progress.
915                if tail.len() > 8192 {
916                    let cut = tail.len() - 4096;
917                    tail = tail[tail
918                        .char_indices()
919                        .find(|(i, _)| *i >= cut)
920                        .map_or(0, |(i, _)| i)..]
921                        .to_string();
922                }
923                on_stderr(&chunk);
924            }
925        }
926    }
927
928    let status = child
929        .wait()
930        .await
931        .map_err(|e| gitpoulpi_core::Error::Backend(format!("failed to wait for git: {e}")))?;
932    let _ = drain_stdout.await;
933    tree.disarm();
934
935    if !status.success() {
936        return Err(failed_with(args, status.code(), tail.trim()));
937    }
938    Ok(())
939}
940
941/// Async variant of `run_status`, for network operations whose failure
942/// (e.g. a `pull` stopping on conflicts) is an expected outcome.
943pub async fn run_status_async(repo_root: &Path, args: &[&str]) -> Result<StatusOutput> {
944    let output = output_guarded(repo_root, args).await?;
945    status_of(&output)
946}
947
948/// Runs `git <args>` and reports `(success, stdout)`, never turning a
949/// non-zero exit into `Err`. For queries whose "no" is an exit status --
950/// `git config --get` exits 1 for an unset key.
951pub fn run_lenient(repo_root: &Path, args: &[&str]) -> Result<(bool, String)> {
952    let output = git(repo_root, args).output().map_err(spawn_failed)?;
953    Ok((
954        output.status.success(),
955        String::from_utf8_lossy(&output.stdout).into_owned(),
956    ))
957}
958
959/// [`run_bytes`] with bytes written to the child's stdin, for
960/// `git cat-file --batch`, whose answers are file content and so cannot
961/// go through the UTF-8-checked [`run_with_stdin`].
962///
963/// stdin is written from its own thread, see [`run_piped_stdin`].
964pub fn run_bytes_with_stdin(repo_root: &Path, args: &[&str], stdin: &[u8]) -> Result<Vec<u8>> {
965    let (output, writer) = run_piped_stdin(git(repo_root, args), stdin.to_vec())?;
966    let output = checked(args, output)?;
967    join_writer(writer)?;
968    Ok(output.stdout)
969}
970
971/// Like `run`, but for commands invoked with `-z` (NUL-delimited output).
972pub fn run_z_fields(repo_root: &Path, args: &[&str]) -> Result<Vec<String>> {
973    let raw = run(repo_root, args)?;
974    Ok(raw
975        .split('\0')
976        .filter(|s| !s.is_empty())
977        .map(str::to_string)
978        .collect())
979}
980
981/// The installed git's `(major, minor)`, asked once per process
982/// (`git --version`: `git version 2.45.2.windows.1`).
983pub(crate) fn git_version() -> Option<(u32, u32)> {
984    static VERSION: OnceLock<Option<(u32, u32)>> = OnceLock::new();
985    *VERSION.get_or_init(|| {
986        run(Path::new("."), &["--version"])
987            .ok()
988            .and_then(|v| parse_git_version(&v))
989    })
990}
991
992/// `(major, minor)` out of `git version 2.45.2.windows.1`.
993pub(crate) fn parse_git_version(text: &str) -> Option<(u32, u32)> {
994    let mut parts = text.trim().strip_prefix("git version ")?.split('.');
995    Some((parts.next()?.parse().ok()?, parts.next()?.parse().ok()?))
996}
997
998/// Whether the installed git is at least `(major, minor)`.
999pub(crate) fn git_at_least(major: u32, minor: u32) -> bool {
1000    git_version().is_some_and(|v| v >= (major, minor))
1001}
1002
1003/// What `git cat-file --batch` said about one object: its size, and its
1004/// bytes unless it was over the cap.
1005pub(crate) struct BatchObject {
1006    pub size: u64,
1007    pub bytes: Option<Vec<u8>>,
1008}
1009
1010/// Reads the objects `oids` through **one** `git cat-file --batch`,
1011/// keeping at most `cap` bytes per object: a larger one is reported with
1012/// its size and its bytes are drained, never held, so a conflict on a
1013/// gigabyte file costs no memory. Asked one object at a time so the child
1014/// is never left mid-stream. A missing object is an error.
1015pub(crate) fn cat_file_batch_capped(
1016    repo_root: &Path,
1017    oids: &[String],
1018    cap: u64,
1019) -> Result<Vec<BatchObject>> {
1020    use std::io::{BufRead, BufReader, Read};
1021
1022    let mut out = Vec::with_capacity(oids.len());
1023    if oids.is_empty() {
1024        return Ok(out);
1025    }
1026    let mut child = git(repo_root, &["cat-file", "--batch"])
1027        .stdin(Stdio::piped())
1028        .stdout(Stdio::piped())
1029        .stderr(Stdio::null())
1030        .spawn()
1031        .map_err(spawn_failed)?;
1032    let mut stdin = child.stdin.take().expect("stdin was piped");
1033    let mut stdout = BufReader::new(child.stdout.take().expect("stdout was piped"));
1034    let io_err =
1035        |e: std::io::Error| gitpoulpi_core::Error::Backend(format!("git cat-file --batch: {e}"));
1036    for oid in oids {
1037        writeln!(stdin, "{oid}").map_err(io_err)?;
1038        stdin.flush().map_err(io_err)?;
1039        let mut header = String::new();
1040        stdout.read_line(&mut header).map_err(io_err)?;
1041        let mut words = header.split_whitespace();
1042        let size: u64 = match (words.next(), words.next(), words.next()) {
1043            (Some(_), Some("blob"), Some(size)) => size.parse().map_err(|_| {
1044                gitpoulpi_core::Error::Backend(format!("git cat-file gave `{}`", header.trim()))
1045            })?,
1046            _ => {
1047                return Err(gitpoulpi_core::Error::Backend(format!(
1048                    "git cat-file --batch: no blob for {oid} (`{}`)",
1049                    header.trim()
1050                )))
1051            }
1052        };
1053        let bytes = if size <= cap {
1054            let mut buf = vec![0u8; size as usize];
1055            stdout.read_exact(&mut buf).map_err(io_err)?;
1056            Some(buf)
1057        } else {
1058            std::io::copy(&mut (&mut stdout).take(size), &mut std::io::sink()).map_err(io_err)?;
1059            None
1060        };
1061        // The newline git prints after every object.
1062        let mut newline = [0u8; 1];
1063        stdout.read_exact(&mut newline).map_err(io_err)?;
1064        out.push(BatchObject { size, bytes });
1065    }
1066    drop(stdin);
1067    let _ = child.wait();
1068    Ok(out)
1069}
1070
1071/// Reads the blobs named by `specs` (`:path` for the index) through one
1072/// `git cat-file --batch`, the lenient sibling of [`cat_file_batch_capped`]:
1073/// a spec that is missing, is not a blob (a submodule) or is over `cap`
1074/// answers `None`, and the rest still answer. A failure of the process
1075/// itself answers `None` for every spec.
1076pub(crate) fn cat_file_batch_lenient(
1077    repo_root: &Path,
1078    specs: &[String],
1079    cap: u64,
1080) -> Vec<Option<Vec<u8>>> {
1081    use std::io::{BufRead, BufReader, Read};
1082
1083    let mut out: Vec<Option<Vec<u8>>> = Vec::with_capacity(specs.len());
1084    if specs.is_empty() {
1085        return out;
1086    }
1087    let Ok(mut child) = git(repo_root, &["cat-file", "--batch"])
1088        .stdin(Stdio::piped())
1089        .stdout(Stdio::piped())
1090        .stderr(Stdio::null())
1091        .spawn()
1092    else {
1093        return vec![None; specs.len()];
1094    };
1095    let mut stdin = child.stdin.take().expect("stdin was piped");
1096    let mut stdout = BufReader::new(child.stdout.take().expect("stdout was piped"));
1097    let mut ask = |spec: &str| -> std::io::Result<Option<Vec<u8>>> {
1098        writeln!(stdin, "{spec}")?;
1099        stdin.flush()?;
1100        let mut header = String::new();
1101        stdout.read_line(&mut header)?;
1102        let mut words = header.split_whitespace();
1103        let (_, kind, size) = (words.next(), words.next(), words.next());
1104        let (Some(kind), Some(size)) = (kind, size.and_then(|s| s.parse::<u64>().ok())) else {
1105            // `<spec> missing` (or ambiguous): one line, no body.
1106            return Ok(None);
1107        };
1108        let bytes = if kind == "blob" && size <= cap {
1109            let mut buf = vec![0u8; size as usize];
1110            stdout.read_exact(&mut buf)?;
1111            Some(buf)
1112        } else {
1113            std::io::copy(&mut (&mut stdout).take(size), &mut std::io::sink())?;
1114            None
1115        };
1116        let mut newline = [0u8; 1];
1117        stdout.read_exact(&mut newline)?;
1118        Ok(bytes)
1119    };
1120    for spec in specs {
1121        match ask(spec) {
1122            Ok(bytes) => out.push(bytes),
1123            Err(_) => break,
1124        }
1125    }
1126    drop(stdin);
1127    let _ = child.wait();
1128    out.resize(specs.len(), None);
1129    out
1130}
1131
1132/// `git merge-file`, whose exit status is the number of conflicts (0 to
1133/// 127) and only a larger one is a failure. Returns stdout.
1134pub(crate) fn run_merge_file(repo_root: &Path, args: &[&str]) -> Result<Vec<u8>> {
1135    let output = git(repo_root, args).output().map_err(spawn_failed)?;
1136    match output.status.code() {
1137        Some(code) if (0..=127).contains(&code) => Ok(output.stdout),
1138        _ => Err(failed(args, &String::from_utf8_lossy(&output.stderr))),
1139    }
1140}
1141
1142/// How long a failed read waits before its one retry.
1143const READ_RETRY_PAUSE: std::time::Duration = std::time::Duration::from_millis(100);
1144
1145/// Runs a read, and once more after a short pause if it failed (the process
1146/// killed by a signal, or a non-zero exit while the repository was changing
1147/// under it). A second failure is the answer: the caller gets the error with
1148/// its detail (exit code, `None` for a signal, and stderr), never a retry
1149/// loop. Reads only: a mutation that failed must never run twice.
1150pub(crate) fn read_with_retry<T>(op: impl FnMut() -> Result<T>) -> Result<T> {
1151    retry_once(op, || std::thread::sleep(READ_RETRY_PAUSE))
1152}
1153
1154/// The policy of [`read_with_retry`], with the pause injectable.
1155fn retry_once<T>(mut op: impl FnMut() -> Result<T>, pause: impl FnOnce()) -> Result<T> {
1156    match op() {
1157        Ok(value) => Ok(value),
1158        Err(_) => {
1159            pause();
1160            op()
1161        }
1162    }
1163}
1164
1165#[cfg(test)]
1166mod retry_tests {
1167    use super::*;
1168
1169    fn died_by_signal() -> gitpoulpi_core::Error {
1170        failed_with(&["for-each-ref"], None, "")
1171    }
1172
1173    #[test]
1174    fn a_read_that_succeeds_runs_once() {
1175        let mut calls = 0;
1176        let mut paused = false;
1177        let out = retry_once(
1178            || {
1179                calls += 1;
1180                Ok("ok")
1181            },
1182            || paused = true,
1183        );
1184        assert_eq!(out.unwrap(), "ok");
1185        assert_eq!(calls, 1);
1186        assert!(!paused, "no pause without a failure");
1187    }
1188
1189    #[test]
1190    fn a_read_killed_once_is_retried_and_succeeds() {
1191        let mut calls = 0;
1192        let out = retry_once(
1193            || {
1194                calls += 1;
1195                if calls == 1 {
1196                    Err(died_by_signal())
1197                } else {
1198                    Ok("ok")
1199                }
1200            },
1201            || {},
1202        );
1203        assert_eq!(out.unwrap(), "ok");
1204        assert_eq!(calls, 2);
1205    }
1206
1207    #[test]
1208    fn a_read_that_fails_twice_returns_the_second_error_with_its_detail() {
1209        let mut calls = 0;
1210        let out: Result<()> = retry_once(
1211            || {
1212                calls += 1;
1213                Err(if calls == 1 {
1214                    failed_with(&["for-each-ref"], Some(128), "first")
1215                } else {
1216                    failed_with(&["for-each-ref"], None, "free(): double free detected")
1217                })
1218            },
1219            || {},
1220        );
1221        let err = out.unwrap_err();
1222        assert_eq!(calls, 2);
1223        let detail = err.detail().expect("detail");
1224        assert_eq!(detail.exit_code, None);
1225        assert!(detail.stderr.contains("double free"), "{}", detail.stderr);
1226    }
1227}
1228
1229#[cfg(test)]
1230mod failure_detail_tests {
1231    use super::*;
1232
1233    /// Even if an address got past the argument checks, the transport
1234    /// allowlist stops a remote helper: `ext::` would run a command.
1235    #[test]
1236    fn the_transport_allowlist_blocks_remote_helpers() {
1237        let dir = tempfile::tempdir().unwrap();
1238        let marker = dir.path().join("ran");
1239        let url = format!("ext::sh -c touch% {}", marker.display());
1240        assert!(run(dir.path(), &["ls-remote", &url]).is_err());
1241        assert!(!marker.exists(), "the helper command must not run");
1242        assert!(full_args(&["fetch"])
1243            .windows(2)
1244            .any(|w| w == ["-c", "protocol.allow=never"]));
1245    }
1246
1247    /// The message and the detail of a failed command never hold a password
1248    /// that the tool (or the caller's arguments) echoed.
1249    #[test]
1250    fn a_failed_command_hides_credentials_everywhere() {
1251        let err = failed_with(
1252            &["push", "https://me:topsecret@host/r.git"],
1253            Some(128),
1254            "fatal: Authentication failed for 'https://me:topsecret@host/r.git/'\n",
1255        );
1256        let all = format!("{err} {err:?}");
1257        assert!(!all.contains("topsecret"), "{all}");
1258        let detail = err.detail().expect("detail");
1259        assert_eq!(detail.exit_code, Some(128));
1260        assert_eq!(detail.operation, "push");
1261        assert!(detail.command.as_deref().unwrap().starts_with("git push"));
1262        assert!(detail.stderr.contains("Authentication failed"));
1263    }
1264}
1265
1266#[cfg(test)]
1267mod lfs_classifier_tests {
1268    use super::*;
1269    use gitpoulpi_core::domain::LfsUnavailableReason;
1270    use gitpoulpi_core::Error;
1271
1272    fn is_missing(stderr: &str) -> bool {
1273        matches!(
1274            classify_lfs_failure(stderr),
1275            Some(Error::LfsUnavailable {
1276                reason: LfsUnavailableReason::Missing
1277            })
1278        )
1279    }
1280
1281    /// The three messages recorded from real git on machines without
1282    /// `git-lfs` (a repository whose config or hooks still call it).
1283    #[test]
1284    fn the_recorded_missing_program_messages_are_recognized() {
1285        assert!(is_missing(
1286            "git-lfs filter-process: git-lfs: command not found\nfatal: a.bin: smudge filter lfs failed"
1287        ));
1288        assert!(is_missing(
1289            "git: 'lfs' is not a git command. See 'git --help'."
1290        ));
1291        assert!(is_missing(
1292            "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. \
1293             If you no longer wish to use Git LFS, remove this hook by deleting the 'pre-push' file in the hooks directory."
1294        ));
1295    }
1296
1297    #[test]
1298    fn ordinary_failures_are_not_mistaken_for_a_missing_program() {
1299        assert!(!is_missing("fatal: not a git repository"));
1300        assert!(!is_missing(
1301            "error: pathspec 'lfs' did not match any file(s) known to git"
1302        ));
1303        assert!(!is_missing("remote: Git LFS: (0 of 1 files) 404 not found"));
1304    }
1305
1306    #[test]
1307    fn a_failed_command_carries_the_typed_error_or_the_plain_one() {
1308        assert!(matches!(
1309            failed(&["checkout", "x"], "git-lfs: command not found"),
1310            Error::LfsUnavailable { .. }
1311        ));
1312        assert!(
1313            matches!(failed(&["checkout", "x"], "boom"), Error::Git { message, .. } if message.contains("checkout x failed: boom"))
1314        );
1315    }
1316}
1317
1318#[cfg(test)]
1319mod resolve_tests {
1320    use super::*;
1321
1322    #[test]
1323    fn cmd_shim_resolves_to_the_mingw_binary_next_to_it() {
1324        let root = tempfile::tempdir().unwrap();
1325        let cmd = root.path().join("cmd");
1326        let bin = root.path().join("mingw64").join("bin");
1327        std::fs::create_dir_all(&cmd).unwrap();
1328        std::fs::create_dir_all(&bin).unwrap();
1329        std::fs::write(cmd.join("git.exe"), "").unwrap();
1330        let path = std::env::join_paths([cmd.clone()]).unwrap();
1331        // No real binary yet: keep the shim (None means "use plain git").
1332        assert_eq!(windows_unshimmed_git(Some(&path)), None);
1333        std::fs::write(bin.join("git.exe"), "").unwrap();
1334        assert_eq!(
1335            windows_unshimmed_git(Some(&path)),
1336            Some(bin.join("git.exe"))
1337        );
1338        // A git that is not in a `cmd` directory is left alone.
1339        let path = std::env::join_paths([bin]).unwrap();
1340        assert_eq!(windows_unshimmed_git(Some(&path)), None);
1341    }
1342}
1343
1344#[cfg(test)]
1345mod stdin_writer_tests {
1346    use super::*;
1347
1348    #[test]
1349    fn a_stdin_the_child_never_reads_is_reported_not_swallowed() {
1350        let dir = tempfile::tempdir().unwrap();
1351        // `git --version` exits 0 without reading stdin; more than a pipe
1352        // buffer of input makes the writer thread fail with a broken pipe.
1353        let input = vec![b'x'; 4 << 20];
1354        assert!(run_bytes_with_stdin(dir.path(), &["--version"], &input).is_err());
1355        assert!(run_with_stdin(dir.path(), &["--version"], &"x".repeat(4 << 20)).is_err());
1356    }
1357}
1358
1359#[cfg(test)]
1360mod network_auth_tests {
1361    use super::*;
1362
1363    fn envs(cmd: &Command) -> Vec<(String, Option<String>)> {
1364        cmd.get_envs()
1365            .map(|(k, v)| {
1366                (
1367                    k.to_string_lossy().into_owned(),
1368                    v.map(|v| v.to_string_lossy().into_owned()),
1369                )
1370            })
1371            .collect()
1372    }
1373
1374    /// An entry puts its settings among the global options, before the
1375    /// subcommand, and the global credential mode does not apply next to it.
1376    #[test]
1377    fn an_entry_replaces_the_global_mode_and_sits_before_the_subcommand() {
1378        let dir = tempfile::tempdir().unwrap();
1379        set_network_auth(
1380            dir.path(),
1381            Some(NetworkAuth {
1382                credential_helpers: Some(vec!["!h".into()]),
1383                credential_url_helpers: vec![("https://h".into(), "!u".into())],
1384                credential_username: Some("u".into()),
1385                no_prompt: true,
1386                reset_extra_header: true,
1387                ssh_command: Some("ssh -i k".into()),
1388                env: vec![("GRANT".into(), "g1".into())],
1389            }),
1390        );
1391        let mut cmd = Command::new("git");
1392        let extra = apply_network_auth(&mut cmd, dir.path());
1393        let all = full_args_with(&extra, &["fetch", "origin"]);
1394        let flat = all.join(" ");
1395        assert!(
1396            flat.contains(
1397                "-c credential.helper= -c credential.helper=!h \
1398                 -c credential.https://h.helper=!u -c credential.username=u \
1399                 -c core.askPass= -c http.extraHeader= fetch origin"
1400            ),
1401            "{flat}"
1402        );
1403        // The transport allowlist is still in front of everything.
1404        assert!(
1405            flat.starts_with("--no-pager -c protocol.allow=never"),
1406            "{flat}"
1407        );
1408        let env = envs(&cmd);
1409        let get = |name: &str| env.iter().find(|(k, _)| k == name).cloned();
1410        assert_eq!(
1411            get("GIT_SSH_COMMAND"),
1412            Some(("GIT_SSH_COMMAND".into(), Some("ssh -i k".into())))
1413        );
1414        assert_eq!(get("GRANT").and_then(|e| e.1), Some("g1".into()));
1415        assert_eq!(
1416            get("GIT_TERMINAL_PROMPT").and_then(|e| e.1),
1417            Some("0".into())
1418        );
1419        assert_eq!(get("GIT_ASKPASS"), Some(("GIT_ASKPASS".into(), None)));
1420        assert_eq!(get("SSH_ASKPASS"), Some(("SSH_ASKPASS".into(), None)));
1421
1422        set_network_auth(dir.path(), None);
1423        let mut cmd = Command::new("git");
1424        let extra = apply_network_auth(&mut cmd, dir.path());
1425        assert!(
1426            !extra.iter().any(|a| a.starts_with("core.askPass")),
1427            "an entry survived its removal: {extra:?}"
1428        );
1429    }
1430
1431    /// A repository has its own entry: another repository's root finds
1432    /// nothing, and another spelling of the same root finds it.
1433    #[test]
1434    fn entries_are_keyed_by_repository_root() {
1435        let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
1436        set_network_auth(
1437            a.path(),
1438            Some(NetworkAuth {
1439                no_prompt: true,
1440                ..NetworkAuth::default()
1441            }),
1442        );
1443        assert!(network_auth_for(a.path()).is_some());
1444        assert!(network_auth_for(b.path()).is_none());
1445        let dotted = a.path().join(".");
1446        assert!(network_auth_for(&dotted).is_some());
1447        set_network_auth(a.path(), None);
1448        assert!(network_auth_for(a.path()).is_none());
1449    }
1450}