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
11const CONFIG_OVERRIDES: &[&str] = &[
27 "color.ui=false",
30 "core.quotepath=false",
32 "diff.mnemonicprefix=false",
34 "diff.noprefix=false",
35 "diff.srcprefix=a/",
36 "diff.dstprefix=b/",
37 "log.showsignature=false",
39 "status.relativepaths=false",
41 "i18n.logoutputencoding=UTF-8",
43];
44
45const 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 "GIT_CONFIG_PARAMETERS",
63 "GIT_CONFIG_COUNT",
64 "GIT_LFS_SKIP_SMUDGE",
68 "GIT_LFS_PROGRESS",
69];
70
71const 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
84fn full_args(args: &[&str]) -> Vec<String> {
89 full_args_with(&[], args)
90}
91
92fn 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 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
125static 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
134pub fn total_spawn_count() -> u64 {
139 TOTAL_SPAWNS.load(std::sync::atomic::Ordering::Relaxed)
140}
141
142#[cfg(all(test, feature = "lfs"))]
146pub fn spawn_count() -> u64 {
147 SPAWNS.with(std::cell::Cell::get)
148}
149
150pub 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#[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
188fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
219pub enum CredentialMode {
220 #[default]
222 Helper,
223 Prompt,
225 None,
227}
228
229static CREDENTIAL_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
230
231pub 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
244fn credential_settings(mode: CredentialMode) -> (&'static [&'static str], Option<&'static str>) {
246 match mode {
247 CredentialMode::Helper => (&[], None),
248 CredentialMode::Prompt => (&["-c", "credential.helper="], None),
250 CredentialMode::None => (&["-c", "credential.helper="], Some("0")),
251 }
252}
253
254static SSH_KEY: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
258
259pub 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
267pub 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 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
296static NETWORK_AUTH: std::sync::RwLock<Option<HashMap<PathBuf, NetworkAuth>>> =
303 std::sync::RwLock::new(None);
304
305fn auth_key(repo_root: &Path) -> PathBuf {
308 std::fs::canonicalize(repo_root).unwrap_or_else(|_| repo_root.to_path_buf())
309}
310
311pub(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
334fn 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 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 cmd.env("GIT_SSH_COMMAND", ssh);
389 }
390 for (name, value) in &auth.env {
391 cmd.env(name, value);
392 }
393 args
394}
395
396pub 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
409pub(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
422pub(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 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
441pub(crate) fn failed(args: &[&str], stderr: &str) -> gitpoulpi_core::Error {
446 failed_with(args, None, stderr)
447}
448
449pub(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
467pub fn classify_lfs_failure(stderr: &str) -> Option<gitpoulpi_core::Error> {
473 const MISSING: &[&str] = &[
474 "git-lfs: command not found",
476 "git-lfs: not found",
477 "'lfs' is not a git command",
479 "'git-lfs' was not found on your path",
481 "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
502fn 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
515fn 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
531pub(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 let _ = run_status_with_env(repo_root, &["update-index", "-q", "--refresh"], &english);
547 run_status_with_env(repo_root, args, &english)
548}
549
550pub(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
568pub(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
595fn 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
620pub 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
628pub 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#[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 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
670pub 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
684pub 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
694pub 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
701pub fn run_with_env_and_stdin(
707 repo_root: &Path,
708 args: &[&str],
709 env: &[(&str, &str)],
710 stdin: &str,
711) -> Result<String> {
712 let cmd = with_env(git(repo_root, args), env);
713 let (output, writer) = run_piped_stdin(cmd, stdin.as_bytes().to_vec())?;
714 let output = checked(args, output)?;
715 join_writer(writer)?;
716 utf8_stdout(output.stdout)
717}
718
719pub struct StatusOutput {
723 pub success: bool,
724 pub stderr: String,
725 pub exit_code: Option<i32>,
726}
727
728pub fn run_status(repo_root: &Path, args: &[&str]) -> Result<StatusOutput> {
732 status_of(&git(repo_root, args).output().map_err(spawn_failed)?)
733}
734
735pub fn run_status_with_env(
739 repo_root: &Path,
740 args: &[&str],
741 env: &[(&str, &str)],
742) -> Result<StatusOutput> {
743 let output = with_env(git(repo_root, args), env)
744 .output()
745 .map_err(spawn_failed)?;
746 status_of(&output)
747}
748
749async fn output_guarded(repo_root: &Path, args: &[&str]) -> Result<Output> {
754 let mut cmd = git_async(repo_root, args);
755 crate::tree_kill::captured(&mut cmd);
756 let cleanup = crate::cancel_cleanup::for_command(repo_root, args);
757 let (child, mut guard) = crate::tree_kill::spawn_guarded(&mut cmd).map_err(spawn_failed)?;
758 let output = child.wait_with_output().await.map_err(spawn_failed)?;
759 guard.disarm();
760 if let Some(mut cleanup) = cleanup {
761 cleanup.disarm();
762 }
763 Ok(output)
764}
765
766pub async fn run_async(repo_root: &Path, args: &[&str]) -> Result<String> {
769 let output = output_guarded(repo_root, args).await?;
770 utf8_stdout(checked(args, output)?.stdout)
771}
772
773pub struct FullOutput {
776 pub success: bool,
777 pub stdout: String,
778 pub stderr: String,
779 pub exit_code: Option<i32>,
780}
781
782pub async fn run_full_async(repo_root: &Path, args: &[&str]) -> Result<FullOutput> {
786 let output = output_guarded(repo_root, args).await?;
787 let status = status_of(&output)?;
788 Ok(FullOutput {
789 success: status.success,
790 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
791 stderr: status.stderr,
792 exit_code: status.exit_code,
793 })
794}
795
796pub(crate) async fn run_full_async_english(repo_root: &Path, args: &[&str]) -> Result<FullOutput> {
800 run_full_async_with(repo_root, args, false).await
801}
802
803fn verbose_ssh_command(cmd: &tokio::process::Command, repo_root: &Path) -> String {
811 let chosen = cmd
812 .as_std()
813 .get_envs()
814 .find(|(k, _)| *k == "GIT_SSH_COMMAND")
815 .and_then(|(_, v)| v.map(|v| v.to_string_lossy().into_owned()));
816 let base = chosen
817 .or_else(|| {
818 std::env::var("GIT_SSH_COMMAND")
819 .ok()
820 .filter(|v| !v.is_empty())
821 })
822 .or_else(|| {
823 git(repo_root, &["config", "--get", "core.sshCommand"])
824 .output()
825 .ok()
826 .filter(|o| o.status.success())
827 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
828 .filter(|v| !v.is_empty())
829 })
830 .or_else(|| {
831 std::env::var("GIT_SSH")
832 .ok()
833 .filter(|v| !v.is_empty())
834 .map(|v| gitpoulpi_core::repo_config::sh_quote_path(&v))
835 })
836 .unwrap_or_else(|| "ssh".to_string());
837 format!("{base} -v")
838}
839
840pub(crate) async fn run_full_async_with(
843 repo_root: &Path,
844 args: &[&str],
845 ssh_verbose: bool,
846) -> Result<FullOutput> {
847 let mut cmd = git_async(repo_root, args);
848 cmd.env("LC_ALL", "C").env("LANGUAGE", "C");
849 if ssh_verbose {
850 let ssh = verbose_ssh_command(&cmd, repo_root);
851 cmd.env("GIT_SSH_COMMAND", ssh);
852 }
853 crate::tree_kill::captured(&mut cmd);
854 let (child, mut guard) = crate::tree_kill::spawn_guarded(&mut cmd).map_err(spawn_failed)?;
855 let output = child.wait_with_output().await.map_err(spawn_failed)?;
856 guard.disarm();
857 let status = status_of(&output)?;
858 Ok(FullOutput {
859 success: status.success,
860 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
861 stderr: status.stderr,
862 exit_code: status.exit_code,
863 })
864}
865
866pub async fn run_streaming_stderr<F>(
875 repo_root: &Path,
876 args: &[&str],
877 mut on_stderr: F,
878) -> Result<()>
879where
880 F: FnMut(&str) + Send,
881{
882 use tokio::io::AsyncReadExt;
883
884 let mut cmd = git_async(repo_root, args);
885 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
886 let (mut child, mut tree) = crate::tree_kill::spawn_guarded(&mut cmd).map_err(spawn_failed)?;
888
889 let mut stdout = child.stdout.take().expect("stdout was piped");
890 let drain_stdout = tokio::spawn(async move {
891 let mut sink = Vec::new();
892 let _ = stdout.read_to_end(&mut sink).await;
893 });
894
895 let mut stderr = child.stderr.take().expect("stderr was piped");
896 let mut buf = [0u8; 4096];
897 let mut tail = String::new();
898 loop {
899 match stderr.read(&mut buf).await {
900 Ok(0) | Err(_) => break,
901 Ok(n) => {
902 let chunk = String::from_utf8_lossy(&buf[..n]);
903 tail.push_str(&chunk);
904 if tail.len() > 8192 {
908 let cut = tail.len() - 4096;
909 tail = tail[tail
910 .char_indices()
911 .find(|(i, _)| *i >= cut)
912 .map_or(0, |(i, _)| i)..]
913 .to_string();
914 }
915 on_stderr(&chunk);
916 }
917 }
918 }
919
920 let status = child
921 .wait()
922 .await
923 .map_err(|e| gitpoulpi_core::Error::Backend(format!("failed to wait for git: {e}")))?;
924 let _ = drain_stdout.await;
925 tree.disarm();
926
927 if !status.success() {
928 return Err(failed_with(args, status.code(), tail.trim()));
929 }
930 Ok(())
931}
932
933pub async fn run_status_async(repo_root: &Path, args: &[&str]) -> Result<StatusOutput> {
936 let output = output_guarded(repo_root, args).await?;
937 status_of(&output)
938}
939
940pub fn run_lenient(repo_root: &Path, args: &[&str]) -> Result<(bool, String)> {
944 let output = git(repo_root, args).output().map_err(spawn_failed)?;
945 Ok((
946 output.status.success(),
947 String::from_utf8_lossy(&output.stdout).into_owned(),
948 ))
949}
950
951pub fn run_bytes_with_stdin(repo_root: &Path, args: &[&str], stdin: &[u8]) -> Result<Vec<u8>> {
957 let (output, writer) = run_piped_stdin(git(repo_root, args), stdin.to_vec())?;
958 let output = checked(args, output)?;
959 join_writer(writer)?;
960 Ok(output.stdout)
961}
962
963pub fn run_z_fields(repo_root: &Path, args: &[&str]) -> Result<Vec<String>> {
965 let raw = run(repo_root, args)?;
966 Ok(raw
967 .split('\0')
968 .filter(|s| !s.is_empty())
969 .map(str::to_string)
970 .collect())
971}
972
973pub(crate) fn git_version() -> Option<(u32, u32)> {
976 static VERSION: OnceLock<Option<(u32, u32)>> = OnceLock::new();
977 *VERSION.get_or_init(|| {
978 run(Path::new("."), &["--version"])
979 .ok()
980 .and_then(|v| parse_git_version(&v))
981 })
982}
983
984pub(crate) fn parse_git_version(text: &str) -> Option<(u32, u32)> {
986 let mut parts = text.trim().strip_prefix("git version ")?.split('.');
987 Some((parts.next()?.parse().ok()?, parts.next()?.parse().ok()?))
988}
989
990pub(crate) fn git_at_least(major: u32, minor: u32) -> bool {
992 git_version().is_some_and(|v| v >= (major, minor))
993}
994
995pub(crate) struct BatchObject {
998 pub size: u64,
999 pub bytes: Option<Vec<u8>>,
1000}
1001
1002pub(crate) fn cat_file_batch_capped(
1008 repo_root: &Path,
1009 oids: &[String],
1010 cap: u64,
1011) -> Result<Vec<BatchObject>> {
1012 use std::io::{BufRead, BufReader, Read};
1013
1014 let mut out = Vec::with_capacity(oids.len());
1015 if oids.is_empty() {
1016 return Ok(out);
1017 }
1018 let mut child = git(repo_root, &["cat-file", "--batch"])
1019 .stdin(Stdio::piped())
1020 .stdout(Stdio::piped())
1021 .stderr(Stdio::null())
1022 .spawn()
1023 .map_err(spawn_failed)?;
1024 let mut stdin = child.stdin.take().expect("stdin was piped");
1025 let mut stdout = BufReader::new(child.stdout.take().expect("stdout was piped"));
1026 let io_err =
1027 |e: std::io::Error| gitpoulpi_core::Error::Backend(format!("git cat-file --batch: {e}"));
1028 for oid in oids {
1029 writeln!(stdin, "{oid}").map_err(io_err)?;
1030 stdin.flush().map_err(io_err)?;
1031 let mut header = String::new();
1032 stdout.read_line(&mut header).map_err(io_err)?;
1033 let mut words = header.split_whitespace();
1034 let size: u64 = match (words.next(), words.next(), words.next()) {
1035 (Some(_), Some("blob"), Some(size)) => size.parse().map_err(|_| {
1036 gitpoulpi_core::Error::Backend(format!("git cat-file gave `{}`", header.trim()))
1037 })?,
1038 _ => {
1039 return Err(gitpoulpi_core::Error::Backend(format!(
1040 "git cat-file --batch: no blob for {oid} (`{}`)",
1041 header.trim()
1042 )))
1043 }
1044 };
1045 let bytes = if size <= cap {
1046 let mut buf = vec![0u8; size as usize];
1047 stdout.read_exact(&mut buf).map_err(io_err)?;
1048 Some(buf)
1049 } else {
1050 std::io::copy(&mut (&mut stdout).take(size), &mut std::io::sink()).map_err(io_err)?;
1051 None
1052 };
1053 let mut newline = [0u8; 1];
1055 stdout.read_exact(&mut newline).map_err(io_err)?;
1056 out.push(BatchObject { size, bytes });
1057 }
1058 drop(stdin);
1059 let _ = child.wait();
1060 Ok(out)
1061}
1062
1063pub(crate) fn cat_file_batch_lenient(
1069 repo_root: &Path,
1070 specs: &[String],
1071 cap: u64,
1072) -> Vec<Option<Vec<u8>>> {
1073 use std::io::{BufRead, BufReader, Read};
1074
1075 let mut out: Vec<Option<Vec<u8>>> = Vec::with_capacity(specs.len());
1076 if specs.is_empty() {
1077 return out;
1078 }
1079 let Ok(mut child) = git(repo_root, &["cat-file", "--batch"])
1080 .stdin(Stdio::piped())
1081 .stdout(Stdio::piped())
1082 .stderr(Stdio::null())
1083 .spawn()
1084 else {
1085 return vec![None; specs.len()];
1086 };
1087 let mut stdin = child.stdin.take().expect("stdin was piped");
1088 let mut stdout = BufReader::new(child.stdout.take().expect("stdout was piped"));
1089 let mut ask = |spec: &str| -> std::io::Result<Option<Vec<u8>>> {
1090 writeln!(stdin, "{spec}")?;
1091 stdin.flush()?;
1092 let mut header = String::new();
1093 stdout.read_line(&mut header)?;
1094 let mut words = header.split_whitespace();
1095 let (_, kind, size) = (words.next(), words.next(), words.next());
1096 let (Some(kind), Some(size)) = (kind, size.and_then(|s| s.parse::<u64>().ok())) else {
1097 return Ok(None);
1099 };
1100 let bytes = if kind == "blob" && size <= cap {
1101 let mut buf = vec![0u8; size as usize];
1102 stdout.read_exact(&mut buf)?;
1103 Some(buf)
1104 } else {
1105 std::io::copy(&mut (&mut stdout).take(size), &mut std::io::sink())?;
1106 None
1107 };
1108 let mut newline = [0u8; 1];
1109 stdout.read_exact(&mut newline)?;
1110 Ok(bytes)
1111 };
1112 for spec in specs {
1113 match ask(spec) {
1114 Ok(bytes) => out.push(bytes),
1115 Err(_) => break,
1116 }
1117 }
1118 drop(stdin);
1119 let _ = child.wait();
1120 out.resize(specs.len(), None);
1121 out
1122}
1123
1124pub(crate) fn run_merge_file(repo_root: &Path, args: &[&str]) -> Result<Vec<u8>> {
1127 let output = git(repo_root, args).output().map_err(spawn_failed)?;
1128 match output.status.code() {
1129 Some(code) if (0..=127).contains(&code) => Ok(output.stdout),
1130 _ => Err(failed(args, &String::from_utf8_lossy(&output.stderr))),
1131 }
1132}
1133
1134const READ_RETRY_PAUSE: std::time::Duration = std::time::Duration::from_millis(100);
1136
1137pub(crate) fn read_with_retry<T>(op: impl FnMut() -> Result<T>) -> Result<T> {
1143 retry_once(op, || std::thread::sleep(READ_RETRY_PAUSE))
1144}
1145
1146fn retry_once<T>(mut op: impl FnMut() -> Result<T>, pause: impl FnOnce()) -> Result<T> {
1148 match op() {
1149 Ok(value) => Ok(value),
1150 Err(_) => {
1151 pause();
1152 op()
1153 }
1154 }
1155}
1156
1157#[cfg(test)]
1158mod retry_tests {
1159 use super::*;
1160
1161 fn died_by_signal() -> gitpoulpi_core::Error {
1162 failed_with(&["for-each-ref"], None, "")
1163 }
1164
1165 #[test]
1166 fn a_read_that_succeeds_runs_once() {
1167 let mut calls = 0;
1168 let mut paused = false;
1169 let out = retry_once(
1170 || {
1171 calls += 1;
1172 Ok("ok")
1173 },
1174 || paused = true,
1175 );
1176 assert_eq!(out.unwrap(), "ok");
1177 assert_eq!(calls, 1);
1178 assert!(!paused, "no pause without a failure");
1179 }
1180
1181 #[test]
1182 fn a_read_killed_once_is_retried_and_succeeds() {
1183 let mut calls = 0;
1184 let out = retry_once(
1185 || {
1186 calls += 1;
1187 if calls == 1 {
1188 Err(died_by_signal())
1189 } else {
1190 Ok("ok")
1191 }
1192 },
1193 || {},
1194 );
1195 assert_eq!(out.unwrap(), "ok");
1196 assert_eq!(calls, 2);
1197 }
1198
1199 #[test]
1200 fn a_read_that_fails_twice_returns_the_second_error_with_its_detail() {
1201 let mut calls = 0;
1202 let out: Result<()> = retry_once(
1203 || {
1204 calls += 1;
1205 Err(if calls == 1 {
1206 failed_with(&["for-each-ref"], Some(128), "first")
1207 } else {
1208 failed_with(&["for-each-ref"], None, "free(): double free detected")
1209 })
1210 },
1211 || {},
1212 );
1213 let err = out.unwrap_err();
1214 assert_eq!(calls, 2);
1215 let detail = err.detail().expect("detail");
1216 assert_eq!(detail.exit_code, None);
1217 assert!(detail.stderr.contains("double free"), "{}", detail.stderr);
1218 }
1219}
1220
1221#[cfg(test)]
1222mod failure_detail_tests {
1223 use super::*;
1224
1225 #[test]
1228 fn the_transport_allowlist_blocks_remote_helpers() {
1229 let dir = tempfile::tempdir().unwrap();
1230 let marker = dir.path().join("ran");
1231 let url = format!("ext::sh -c touch% {}", marker.display());
1232 assert!(run(dir.path(), &["ls-remote", &url]).is_err());
1233 assert!(!marker.exists(), "the helper command must not run");
1234 assert!(full_args(&["fetch"])
1235 .windows(2)
1236 .any(|w| w == ["-c", "protocol.allow=never"]));
1237 }
1238
1239 #[test]
1242 fn a_failed_command_hides_credentials_everywhere() {
1243 let err = failed_with(
1244 &["push", "https://me:topsecret@host/r.git"],
1245 Some(128),
1246 "fatal: Authentication failed for 'https://me:topsecret@host/r.git/'\n",
1247 );
1248 let all = format!("{err} {err:?}");
1249 assert!(!all.contains("topsecret"), "{all}");
1250 let detail = err.detail().expect("detail");
1251 assert_eq!(detail.exit_code, Some(128));
1252 assert_eq!(detail.operation, "push");
1253 assert!(detail.command.as_deref().unwrap().starts_with("git push"));
1254 assert!(detail.stderr.contains("Authentication failed"));
1255 }
1256}
1257
1258#[cfg(test)]
1259mod lfs_classifier_tests {
1260 use super::*;
1261 use gitpoulpi_core::domain::LfsUnavailableReason;
1262 use gitpoulpi_core::Error;
1263
1264 fn is_missing(stderr: &str) -> bool {
1265 matches!(
1266 classify_lfs_failure(stderr),
1267 Some(Error::LfsUnavailable {
1268 reason: LfsUnavailableReason::Missing
1269 })
1270 )
1271 }
1272
1273 #[test]
1276 fn the_recorded_missing_program_messages_are_recognized() {
1277 assert!(is_missing(
1278 "git-lfs filter-process: git-lfs: command not found\nfatal: a.bin: smudge filter lfs failed"
1279 ));
1280 assert!(is_missing(
1281 "git: 'lfs' is not a git command. See 'git --help'."
1282 ));
1283 assert!(is_missing(
1284 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. \
1285 If you no longer wish to use Git LFS, remove this hook by deleting the 'pre-push' file in the hooks directory."
1286 ));
1287 }
1288
1289 #[test]
1290 fn ordinary_failures_are_not_mistaken_for_a_missing_program() {
1291 assert!(!is_missing("fatal: not a git repository"));
1292 assert!(!is_missing(
1293 "error: pathspec 'lfs' did not match any file(s) known to git"
1294 ));
1295 assert!(!is_missing("remote: Git LFS: (0 of 1 files) 404 not found"));
1296 }
1297
1298 #[test]
1299 fn a_failed_command_carries_the_typed_error_or_the_plain_one() {
1300 assert!(matches!(
1301 failed(&["checkout", "x"], "git-lfs: command not found"),
1302 Error::LfsUnavailable { .. }
1303 ));
1304 assert!(
1305 matches!(failed(&["checkout", "x"], "boom"), Error::Git { message, .. } if message.contains("checkout x failed: boom"))
1306 );
1307 }
1308}
1309
1310#[cfg(test)]
1311mod resolve_tests {
1312 use super::*;
1313
1314 #[test]
1315 fn cmd_shim_resolves_to_the_mingw_binary_next_to_it() {
1316 let root = tempfile::tempdir().unwrap();
1317 let cmd = root.path().join("cmd");
1318 let bin = root.path().join("mingw64").join("bin");
1319 std::fs::create_dir_all(&cmd).unwrap();
1320 std::fs::create_dir_all(&bin).unwrap();
1321 std::fs::write(cmd.join("git.exe"), "").unwrap();
1322 let path = std::env::join_paths([cmd.clone()]).unwrap();
1323 assert_eq!(windows_unshimmed_git(Some(&path)), None);
1325 std::fs::write(bin.join("git.exe"), "").unwrap();
1326 assert_eq!(
1327 windows_unshimmed_git(Some(&path)),
1328 Some(bin.join("git.exe"))
1329 );
1330 let path = std::env::join_paths([bin]).unwrap();
1332 assert_eq!(windows_unshimmed_git(Some(&path)), None);
1333 }
1334}
1335
1336#[cfg(test)]
1337mod stdin_writer_tests {
1338 use super::*;
1339
1340 #[test]
1341 fn a_stdin_the_child_never_reads_is_reported_not_swallowed() {
1342 let dir = tempfile::tempdir().unwrap();
1343 let input = vec![b'x'; 4 << 20];
1346 assert!(run_bytes_with_stdin(dir.path(), &["--version"], &input).is_err());
1347 assert!(run_with_stdin(dir.path(), &["--version"], &"x".repeat(4 << 20)).is_err());
1348 }
1349}
1350
1351#[cfg(test)]
1352mod network_auth_tests {
1353 use super::*;
1354
1355 fn envs(cmd: &Command) -> Vec<(String, Option<String>)> {
1356 cmd.get_envs()
1357 .map(|(k, v)| {
1358 (
1359 k.to_string_lossy().into_owned(),
1360 v.map(|v| v.to_string_lossy().into_owned()),
1361 )
1362 })
1363 .collect()
1364 }
1365
1366 #[test]
1369 fn an_entry_replaces_the_global_mode_and_sits_before_the_subcommand() {
1370 let dir = tempfile::tempdir().unwrap();
1371 set_network_auth(
1372 dir.path(),
1373 Some(NetworkAuth {
1374 credential_helpers: Some(vec!["!h".into()]),
1375 credential_url_helpers: vec![("https://h".into(), "!u".into())],
1376 credential_username: Some("u".into()),
1377 no_prompt: true,
1378 reset_extra_header: true,
1379 ssh_command: Some("ssh -i k".into()),
1380 env: vec![("GRANT".into(), "g1".into())],
1381 }),
1382 );
1383 let mut cmd = Command::new("git");
1384 let extra = apply_network_auth(&mut cmd, dir.path());
1385 let all = full_args_with(&extra, &["fetch", "origin"]);
1386 let flat = all.join(" ");
1387 assert!(
1388 flat.contains(
1389 "-c credential.helper= -c credential.helper=!h \
1390 -c credential.https://h.helper=!u -c credential.username=u \
1391 -c core.askPass= -c http.extraHeader= fetch origin"
1392 ),
1393 "{flat}"
1394 );
1395 assert!(
1397 flat.starts_with("--no-pager -c protocol.allow=never"),
1398 "{flat}"
1399 );
1400 let env = envs(&cmd);
1401 let get = |name: &str| env.iter().find(|(k, _)| k == name).cloned();
1402 assert_eq!(
1403 get("GIT_SSH_COMMAND"),
1404 Some(("GIT_SSH_COMMAND".into(), Some("ssh -i k".into())))
1405 );
1406 assert_eq!(get("GRANT").and_then(|e| e.1), Some("g1".into()));
1407 assert_eq!(
1408 get("GIT_TERMINAL_PROMPT").and_then(|e| e.1),
1409 Some("0".into())
1410 );
1411 assert_eq!(get("GIT_ASKPASS"), Some(("GIT_ASKPASS".into(), None)));
1412 assert_eq!(get("SSH_ASKPASS"), Some(("SSH_ASKPASS".into(), None)));
1413
1414 set_network_auth(dir.path(), None);
1415 let mut cmd = Command::new("git");
1416 let extra = apply_network_auth(&mut cmd, dir.path());
1417 assert!(
1418 !extra.iter().any(|a| a.starts_with("core.askPass")),
1419 "an entry survived its removal: {extra:?}"
1420 );
1421 }
1422
1423 #[test]
1426 fn entries_are_keyed_by_repository_root() {
1427 let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
1428 set_network_auth(
1429 a.path(),
1430 Some(NetworkAuth {
1431 no_prompt: true,
1432 ..NetworkAuth::default()
1433 }),
1434 );
1435 assert!(network_auth_for(a.path()).is_some());
1436 assert!(network_auth_for(b.path()).is_none());
1437 let dotted = a.path().join(".");
1438 assert!(network_auth_for(&dotted).is_some());
1439 set_network_auth(a.path(), None);
1440 assert!(network_auth_for(a.path()).is_none());
1441 }
1442}