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 if updates_working_tree(args) {
420 cmd.env("LC_ALL", "C").env("LANGUAGE", "C");
421 }
422 cmd
423}
424
425pub(crate) fn git_async(repo_root: &Path, args: &[&str]) -> tokio::process::Command {
427 count_spawn();
428 let mut cmd = tokio::process::Command::new(git_program());
429 if let Some(p) = child_path() {
430 cmd.env("PATH", p);
431 }
432 let network_args = apply_network_auth(cmd.as_std_mut(), repo_root);
433 cmd.stdin(Stdio::null());
436 cmd.args(full_args_with(&network_args, args).iter().map(OsStr::new));
437 cmd.current_dir(repo_root);
438 for key in CLEARED_ENV {
439 cmd.env_remove(key);
440 }
441 if updates_working_tree(args) {
442 cmd.env("LC_ALL", "C").env("LANGUAGE", "C");
443 }
444 cmd
445}
446
447pub(crate) fn failed(args: &[&str], stderr: &str) -> gitpoulpi_core::Error {
452 failed_with(args, None, stderr)
453}
454
455pub(crate) fn failed_with(
460 args: &[&str],
461 exit_code: Option<i32>,
462 stderr: &str,
463) -> gitpoulpi_core::Error {
464 classify_lfs_failure(stderr).unwrap_or_else(|| {
465 let message = gitpoulpi_core::redact(&format!("git {} failed: {}", args.join(" "), stderr));
466 gitpoulpi_core::Error::git(
467 message,
468 gitpoulpi_core::ErrorDetail::from_git(args, exit_code, stderr),
469 )
470 })
471}
472
473pub fn classify_lfs_failure(stderr: &str) -> Option<gitpoulpi_core::Error> {
479 const MISSING: &[&str] = &[
480 "git-lfs: command not found",
482 "git-lfs: not found",
483 "'lfs' is not a git command",
485 "'git-lfs' was not found on your path",
487 "cannot run git-lfs",
489 ];
490 let lower = stderr.to_lowercase();
491 MISSING
492 .iter()
493 .any(|needle| lower.contains(needle))
494 .then_some(gitpoulpi_core::Error::LfsUnavailable {
495 reason: gitpoulpi_core::domain::LfsUnavailableReason::Missing,
496 })
497}
498
499pub(crate) fn spawn_failed(e: std::io::Error) -> gitpoulpi_core::Error {
500 gitpoulpi_core::Error::Backend(format!("failed to spawn git: {e}"))
501}
502
503fn utf8_stdout(stdout: Vec<u8>) -> Result<String> {
504 String::from_utf8(stdout)
505 .map_err(|e| gitpoulpi_core::Error::Backend(format!("git output was not utf-8: {e}")))
506}
507
508fn note_warnings(repo_root: &Path, output: &Output) {
512 let stderr = String::from_utf8_lossy(&output.stderr);
513 if stderr.contains("unable to rmdir") {
514 for warning in gitpoulpi_core::warnings::parse_rmdir_warnings(&stderr) {
515 gitpoulpi_core::warnings::record(repo_root, warning);
516 }
517 }
518}
519
520fn updates_working_tree(args: &[&str]) -> bool {
524 matches!(
525 args.first().copied(),
526 Some(
527 "checkout"
528 | "switch"
529 | "reset"
530 | "merge"
531 | "pull"
532 | "stash"
533 | "cherry-pick"
534 | "revert"
535 | "rebase"
536 | "restore"
537 | "read-tree"
538 | "am"
539 )
540 )
541}
542
543fn checked(repo_root: &Path, args: &[&str], output: Output) -> Result<Output> {
545 note_warnings(repo_root, &output);
546 if output.status.success() {
547 Ok(output)
548 } else {
549 Err(failed_with(
550 args,
551 output.status.code(),
552 &String::from_utf8_lossy(&output.stderr),
553 ))
554 }
555}
556
557fn status_of(repo_root: &Path, output: &Output) -> Result<StatusOutput> {
560 note_warnings(repo_root, output);
561 let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
562 if !output.status.success() {
563 if let Some(e) = classify_lfs_failure(&stderr) {
564 return Err(e);
565 }
566 }
567 Ok(StatusOutput {
568 success: output.status.success(),
569 stderr,
570 exit_code: output.status.code(),
571 })
572}
573
574pub(crate) fn run_abort(repo_root: &Path, args: &[&str]) -> Result<StatusOutput> {
582 let english = [("LC_ALL", "C"), ("LANGUAGE", "C")];
583 let first = run_status_with_env(repo_root, args, &english)?;
584 if first.success || not_uptodate_paths(&first.stderr).is_empty() {
585 return Ok(first);
586 }
587 let _ = run_status_with_env(repo_root, &["update-index", "-q", "--refresh"], &english);
590 run_status_with_env(repo_root, args, &english)
591}
592
593pub(crate) fn not_uptodate_paths(stderr: &str) -> Vec<String> {
595 let mut out = Vec::new();
596 for line in stderr.lines() {
597 let Some(at) = line.find("Entry '") else {
598 continue;
599 };
600 let rest = &line[at + "Entry '".len()..];
601 if let Some(end) = rest.find("' not uptodate") {
602 let path = rest[..end].to_string();
603 if !out.contains(&path) {
604 out.push(path);
605 }
606 }
607 }
608 out
609}
610
611pub(crate) fn abort_failed(args: &[&str], out: &StatusOutput) -> gitpoulpi_core::Error {
614 let paths = not_uptodate_paths(&out.stderr);
615 if paths.is_empty() {
616 failed_with(args, out.exit_code, &out.stderr)
617 } else {
618 gitpoulpi_core::Error::ConflictRefused(
619 gitpoulpi_core::domain::ConflictRefusal::LocalChanges { paths },
620 )
621 }
622}
623
624fn with_env(mut cmd: Command, env: &[(&str, &str)]) -> Command {
625 for (key, value) in env {
626 cmd.env(key, value);
627 }
628 cmd
629}
630
631fn join_writer(writer: std::thread::JoinHandle<std::io::Result<()>>) -> Result<()> {
632 writer
633 .join()
634 .map_err(|_| gitpoulpi_core::Error::Backend("git stdin writer panicked".into()))?
635 .map_err(|e| gitpoulpi_core::Error::Backend(format!("failed to write git stdin: {e}")))
636}
637
638fn run_piped_stdin(
646 mut cmd: Command,
647 input: Vec<u8>,
648) -> Result<(Output, std::thread::JoinHandle<std::io::Result<()>>)> {
649 let mut child = cmd
650 .stdin(Stdio::piped())
651 .stdout(Stdio::piped())
652 .stderr(Stdio::piped())
653 .spawn()
654 .map_err(spawn_failed)?;
655 let mut pipe = child.stdin.take().expect("stdin was piped");
656 let writer = std::thread::spawn(move || pipe.write_all(&input));
657 let output = child
658 .wait_with_output()
659 .map_err(|e| gitpoulpi_core::Error::Backend(format!("failed to wait for git: {e}")))?;
660 Ok((output, writer))
661}
662
663pub fn run(repo_root: &Path, args: &[&str]) -> Result<String> {
667 let output = git(repo_root, args).output().map_err(spawn_failed)?;
668 utf8_stdout(checked(repo_root, args, output)?.stdout)
669}
670
671pub fn run_in_english(repo_root: &Path, args: &[&str]) -> Result<String> {
674 let output = git(repo_root, args)
675 .env("LC_ALL", "C")
676 .env("LANGUAGE", "C")
677 .output()
678 .map_err(spawn_failed)?;
679 utf8_stdout(checked(repo_root, args, output)?.stdout)
680}
681
682#[cfg(feature = "submodule")]
686pub fn run_network(repo_root: &Path, args: &[&str]) -> Result<String> {
687 count_spawn();
688 let mut cmd = Command::new(git_program());
689 apply_git_env(&mut cmd);
690 let network_args = apply_network_auth(&mut cmd, repo_root);
691 cmd.args(full_args_with(&network_args, args).iter().map(OsStr::new));
692 cmd.current_dir(repo_root);
693 for key in CLEARED_ENV {
694 cmd.env_remove(key);
695 }
696 cmd.stdin(Stdio::null());
697 #[cfg(unix)]
698 {
699 use std::os::unix::process::CommandExt;
700 unsafe {
703 cmd.pre_exec(|| {
704 libc::setsid();
705 Ok(())
706 });
707 }
708 }
709 let output = cmd.output().map_err(spawn_failed)?;
710 utf8_stdout(checked(repo_root, args, output)?.stdout)
711}
712
713pub fn run_bytes(repo_root: &Path, args: &[&str]) -> Result<Vec<u8>> {
723 let output = git(repo_root, args).output().map_err(spawn_failed)?;
724 Ok(checked(repo_root, args, output)?.stdout)
725}
726
727pub fn run_lenient_bytes(repo_root: &Path, args: &[&str]) -> Result<Vec<u8>> {
730 let output = git(repo_root, args).output().map_err(spawn_failed)?;
731 if output.status.code() == Some(1) {
732 return Ok(output.stdout);
733 }
734 Ok(checked(repo_root, args, output)?.stdout)
735}
736
737pub fn run_with_stdin(repo_root: &Path, args: &[&str], stdin: &str) -> Result<String> {
741 run_with_env_and_stdin(repo_root, args, &[], stdin)
742}
743
744pub fn run_with_stdin_bytes(repo_root: &Path, args: &[&str], stdin: &[u8]) -> Result<String> {
746 let (output, writer) = run_piped_stdin(git(repo_root, args), stdin.to_vec())?;
747 let output = checked(repo_root, args, output)?;
748 join_writer(writer)?;
749 utf8_stdout(output.stdout)
750}
751
752pub fn run_with_env_and_stdin(
758 repo_root: &Path,
759 args: &[&str],
760 env: &[(&str, &str)],
761 stdin: &str,
762) -> Result<String> {
763 let cmd = with_env(git(repo_root, args), env);
764 let (output, writer) = run_piped_stdin(cmd, stdin.as_bytes().to_vec())?;
765 let output = checked(repo_root, args, output)?;
766 join_writer(writer)?;
767 utf8_stdout(output.stdout)
768}
769
770pub struct StatusOutput {
774 pub success: bool,
775 pub stderr: String,
776 pub exit_code: Option<i32>,
777}
778
779pub fn run_status(repo_root: &Path, args: &[&str]) -> Result<StatusOutput> {
783 status_of(
784 repo_root,
785 &git(repo_root, args).output().map_err(spawn_failed)?,
786 )
787}
788
789pub fn run_status_with_env(
793 repo_root: &Path,
794 args: &[&str],
795 env: &[(&str, &str)],
796) -> Result<StatusOutput> {
797 let output = with_env(git(repo_root, args), env)
798 .output()
799 .map_err(spawn_failed)?;
800 status_of(repo_root, &output)
801}
802
803async fn output_guarded(repo_root: &Path, args: &[&str]) -> Result<Output> {
808 let mut cmd = git_async(repo_root, args);
809 crate::tree_kill::captured(&mut cmd);
810 let cleanup = crate::cancel_cleanup::for_command(repo_root, args);
811 let (child, mut guard) = crate::tree_kill::spawn_guarded(&mut cmd).map_err(spawn_failed)?;
812 let output = child.wait_with_output().await.map_err(spawn_failed)?;
813 guard.disarm();
814 if let Some(mut cleanup) = cleanup {
815 cleanup.disarm();
816 }
817 Ok(output)
818}
819
820pub async fn run_async(repo_root: &Path, args: &[&str]) -> Result<String> {
823 let output = output_guarded(repo_root, args).await?;
824 utf8_stdout(checked(repo_root, args, output)?.stdout)
825}
826
827pub struct FullOutput {
830 pub success: bool,
831 pub stdout: String,
832 pub stderr: String,
833 pub exit_code: Option<i32>,
834}
835
836pub async fn run_full_async(repo_root: &Path, args: &[&str]) -> Result<FullOutput> {
840 let output = output_guarded(repo_root, args).await?;
841 let status = status_of(repo_root, &output)?;
842 Ok(FullOutput {
843 success: status.success,
844 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
845 stderr: status.stderr,
846 exit_code: status.exit_code,
847 })
848}
849
850pub(crate) async fn run_full_async_english(repo_root: &Path, args: &[&str]) -> Result<FullOutput> {
854 run_full_async_with(repo_root, args, false).await
855}
856
857fn verbose_ssh_command(cmd: &tokio::process::Command, repo_root: &Path) -> String {
865 let chosen = cmd
866 .as_std()
867 .get_envs()
868 .find(|(k, _)| *k == "GIT_SSH_COMMAND")
869 .and_then(|(_, v)| v.map(|v| v.to_string_lossy().into_owned()));
870 let base = chosen
871 .or_else(|| {
872 std::env::var("GIT_SSH_COMMAND")
873 .ok()
874 .filter(|v| !v.is_empty())
875 })
876 .or_else(|| {
877 git(repo_root, &["config", "--get", "core.sshCommand"])
878 .output()
879 .ok()
880 .filter(|o| o.status.success())
881 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
882 .filter(|v| !v.is_empty())
883 })
884 .or_else(|| {
885 std::env::var("GIT_SSH")
886 .ok()
887 .filter(|v| !v.is_empty())
888 .map(|v| gitpoulpi_core::repo_config::sh_quote_path(&v))
889 })
890 .unwrap_or_else(|| "ssh".to_string());
891 format!("{base} -v")
892}
893
894pub(crate) async fn run_full_async_with(
897 repo_root: &Path,
898 args: &[&str],
899 ssh_verbose: bool,
900) -> Result<FullOutput> {
901 let mut cmd = git_async(repo_root, args);
902 cmd.env("LC_ALL", "C").env("LANGUAGE", "C");
903 if ssh_verbose {
904 let ssh = verbose_ssh_command(&cmd, repo_root);
905 cmd.env("GIT_SSH_COMMAND", ssh);
906 }
907 crate::tree_kill::captured(&mut cmd);
908 let (child, mut guard) = crate::tree_kill::spawn_guarded(&mut cmd).map_err(spawn_failed)?;
909 let output = child.wait_with_output().await.map_err(spawn_failed)?;
910 guard.disarm();
911 let status = status_of(repo_root, &output)?;
912 Ok(FullOutput {
913 success: status.success,
914 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
915 stderr: status.stderr,
916 exit_code: status.exit_code,
917 })
918}
919
920pub async fn run_streaming_stderr<F>(
929 repo_root: &Path,
930 args: &[&str],
931 mut on_stderr: F,
932) -> Result<()>
933where
934 F: FnMut(&str) + Send,
935{
936 use tokio::io::AsyncReadExt;
937
938 let mut cmd = git_async(repo_root, args);
939 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
940 let (mut child, mut tree) = crate::tree_kill::spawn_guarded(&mut cmd).map_err(spawn_failed)?;
942
943 let mut stdout = child.stdout.take().expect("stdout was piped");
944 let drain_stdout = tokio::spawn(async move {
945 let mut sink = Vec::new();
946 let _ = stdout.read_to_end(&mut sink).await;
947 });
948
949 let mut stderr = child.stderr.take().expect("stderr was piped");
950 let mut buf = [0u8; 4096];
951 let mut tail = String::new();
952 loop {
953 match stderr.read(&mut buf).await {
954 Ok(0) | Err(_) => break,
955 Ok(n) => {
956 let chunk = String::from_utf8_lossy(&buf[..n]);
957 tail.push_str(&chunk);
958 if tail.len() > 8192 {
962 let cut = tail.len() - 4096;
963 tail = tail[tail
964 .char_indices()
965 .find(|(i, _)| *i >= cut)
966 .map_or(0, |(i, _)| i)..]
967 .to_string();
968 }
969 on_stderr(&chunk);
970 }
971 }
972 }
973
974 let status = child
975 .wait()
976 .await
977 .map_err(|e| gitpoulpi_core::Error::Backend(format!("failed to wait for git: {e}")))?;
978 let _ = drain_stdout.await;
979 tree.disarm();
980
981 if !status.success() {
982 return Err(failed_with(args, status.code(), tail.trim()));
983 }
984 Ok(())
985}
986
987pub async fn run_status_async(repo_root: &Path, args: &[&str]) -> Result<StatusOutput> {
990 let output = output_guarded(repo_root, args).await?;
991 status_of(repo_root, &output)
992}
993
994pub fn run_lenient(repo_root: &Path, args: &[&str]) -> Result<(bool, String)> {
998 let output = git(repo_root, args).output().map_err(spawn_failed)?;
999 Ok((
1000 output.status.success(),
1001 String::from_utf8_lossy(&output.stdout).into_owned(),
1002 ))
1003}
1004
1005pub fn run_bytes_with_stdin(repo_root: &Path, args: &[&str], stdin: &[u8]) -> Result<Vec<u8>> {
1011 let (output, writer) = run_piped_stdin(git(repo_root, args), stdin.to_vec())?;
1012 let output = checked(repo_root, args, output)?;
1013 join_writer(writer)?;
1014 Ok(output.stdout)
1015}
1016
1017pub fn run_z_fields(repo_root: &Path, args: &[&str]) -> Result<Vec<String>> {
1019 let raw = run(repo_root, args)?;
1020 Ok(raw
1021 .split('\0')
1022 .filter(|s| !s.is_empty())
1023 .map(str::to_string)
1024 .collect())
1025}
1026
1027pub(crate) fn git_version() -> Option<(u32, u32)> {
1030 static VERSION: OnceLock<Option<(u32, u32)>> = OnceLock::new();
1031 *VERSION.get_or_init(|| {
1032 run(Path::new("."), &["--version"])
1033 .ok()
1034 .and_then(|v| parse_git_version(&v))
1035 })
1036}
1037
1038pub(crate) fn parse_git_version(text: &str) -> Option<(u32, u32)> {
1040 let mut parts = text.trim().strip_prefix("git version ")?.split('.');
1041 Some((parts.next()?.parse().ok()?, parts.next()?.parse().ok()?))
1042}
1043
1044pub(crate) fn git_at_least(major: u32, minor: u32) -> bool {
1046 git_version().is_some_and(|v| v >= (major, minor))
1047}
1048
1049pub(crate) struct BatchObject {
1052 pub size: u64,
1053 pub bytes: Option<Vec<u8>>,
1054}
1055
1056pub(crate) fn cat_file_batch_capped(
1062 repo_root: &Path,
1063 oids: &[String],
1064 cap: u64,
1065) -> Result<Vec<BatchObject>> {
1066 use std::io::{BufRead, BufReader, Read};
1067
1068 let mut out = Vec::with_capacity(oids.len());
1069 if oids.is_empty() {
1070 return Ok(out);
1071 }
1072 let mut child = git(repo_root, &["cat-file", "--batch"])
1073 .stdin(Stdio::piped())
1074 .stdout(Stdio::piped())
1075 .stderr(Stdio::null())
1076 .spawn()
1077 .map_err(spawn_failed)?;
1078 let mut stdin = child.stdin.take().expect("stdin was piped");
1079 let mut stdout = BufReader::new(child.stdout.take().expect("stdout was piped"));
1080 let io_err =
1081 |e: std::io::Error| gitpoulpi_core::Error::Backend(format!("git cat-file --batch: {e}"));
1082 for oid in oids {
1083 writeln!(stdin, "{oid}").map_err(io_err)?;
1084 stdin.flush().map_err(io_err)?;
1085 let mut header = String::new();
1086 stdout.read_line(&mut header).map_err(io_err)?;
1087 let mut words = header.split_whitespace();
1088 let size: u64 = match (words.next(), words.next(), words.next()) {
1089 (Some(_), Some("blob"), Some(size)) => size.parse().map_err(|_| {
1090 gitpoulpi_core::Error::Backend(format!("git cat-file gave `{}`", header.trim()))
1091 })?,
1092 _ => {
1093 return Err(gitpoulpi_core::Error::Backend(format!(
1094 "git cat-file --batch: no blob for {oid} (`{}`)",
1095 header.trim()
1096 )))
1097 }
1098 };
1099 let bytes = if size <= cap {
1100 let mut buf = vec![0u8; size as usize];
1101 stdout.read_exact(&mut buf).map_err(io_err)?;
1102 Some(buf)
1103 } else {
1104 std::io::copy(&mut (&mut stdout).take(size), &mut std::io::sink()).map_err(io_err)?;
1105 None
1106 };
1107 let mut newline = [0u8; 1];
1109 stdout.read_exact(&mut newline).map_err(io_err)?;
1110 out.push(BatchObject { size, bytes });
1111 }
1112 drop(stdin);
1113 let _ = child.wait();
1114 Ok(out)
1115}
1116
1117pub(crate) fn cat_file_batch_lenient(
1123 repo_root: &Path,
1124 specs: &[String],
1125 cap: u64,
1126) -> Vec<Option<Vec<u8>>> {
1127 use std::io::{BufRead, BufReader, Read};
1128
1129 let mut out: Vec<Option<Vec<u8>>> = Vec::with_capacity(specs.len());
1130 if specs.is_empty() {
1131 return out;
1132 }
1133 let Ok(mut child) = git(repo_root, &["cat-file", "--batch"])
1134 .stdin(Stdio::piped())
1135 .stdout(Stdio::piped())
1136 .stderr(Stdio::null())
1137 .spawn()
1138 else {
1139 return vec![None; specs.len()];
1140 };
1141 let mut stdin = child.stdin.take().expect("stdin was piped");
1142 let mut stdout = BufReader::new(child.stdout.take().expect("stdout was piped"));
1143 let mut ask = |spec: &str| -> std::io::Result<Option<Vec<u8>>> {
1144 writeln!(stdin, "{spec}")?;
1145 stdin.flush()?;
1146 let mut header = String::new();
1147 stdout.read_line(&mut header)?;
1148 let mut words = header.split_whitespace();
1149 let (_, kind, size) = (words.next(), words.next(), words.next());
1150 let (Some(kind), Some(size)) = (kind, size.and_then(|s| s.parse::<u64>().ok())) else {
1151 return Ok(None);
1153 };
1154 let bytes = if kind == "blob" && size <= cap {
1155 let mut buf = vec![0u8; size as usize];
1156 stdout.read_exact(&mut buf)?;
1157 Some(buf)
1158 } else {
1159 std::io::copy(&mut (&mut stdout).take(size), &mut std::io::sink())?;
1160 None
1161 };
1162 let mut newline = [0u8; 1];
1163 stdout.read_exact(&mut newline)?;
1164 Ok(bytes)
1165 };
1166 for spec in specs {
1167 match ask(spec) {
1168 Ok(bytes) => out.push(bytes),
1169 Err(_) => break,
1170 }
1171 }
1172 drop(stdin);
1173 let _ = child.wait();
1174 out.resize(specs.len(), None);
1175 out
1176}
1177
1178pub(crate) fn run_merge_file(repo_root: &Path, args: &[&str]) -> Result<Vec<u8>> {
1181 let output = git(repo_root, args).output().map_err(spawn_failed)?;
1182 match output.status.code() {
1183 Some(code) if (0..=127).contains(&code) => Ok(output.stdout),
1184 _ => Err(failed(args, &String::from_utf8_lossy(&output.stderr))),
1185 }
1186}
1187
1188const READ_RETRY_PAUSE: std::time::Duration = std::time::Duration::from_millis(100);
1190
1191pub(crate) fn read_with_retry<T>(op: impl FnMut() -> Result<T>) -> Result<T> {
1197 retry_once(op, || std::thread::sleep(READ_RETRY_PAUSE))
1198}
1199
1200fn retry_once<T>(mut op: impl FnMut() -> Result<T>, pause: impl FnOnce()) -> Result<T> {
1202 match op() {
1203 Ok(value) => Ok(value),
1204 Err(_) => {
1205 pause();
1206 op()
1207 }
1208 }
1209}
1210
1211#[cfg(test)]
1212mod retry_tests {
1213 use super::*;
1214
1215 fn died_by_signal() -> gitpoulpi_core::Error {
1216 failed_with(&["for-each-ref"], None, "")
1217 }
1218
1219 #[test]
1220 fn a_read_that_succeeds_runs_once() {
1221 let mut calls = 0;
1222 let mut paused = false;
1223 let out = retry_once(
1224 || {
1225 calls += 1;
1226 Ok("ok")
1227 },
1228 || paused = true,
1229 );
1230 assert_eq!(out.unwrap(), "ok");
1231 assert_eq!(calls, 1);
1232 assert!(!paused, "no pause without a failure");
1233 }
1234
1235 #[test]
1236 fn a_read_killed_once_is_retried_and_succeeds() {
1237 let mut calls = 0;
1238 let out = retry_once(
1239 || {
1240 calls += 1;
1241 if calls == 1 {
1242 Err(died_by_signal())
1243 } else {
1244 Ok("ok")
1245 }
1246 },
1247 || {},
1248 );
1249 assert_eq!(out.unwrap(), "ok");
1250 assert_eq!(calls, 2);
1251 }
1252
1253 #[test]
1254 fn a_read_that_fails_twice_returns_the_second_error_with_its_detail() {
1255 let mut calls = 0;
1256 let out: Result<()> = retry_once(
1257 || {
1258 calls += 1;
1259 Err(if calls == 1 {
1260 failed_with(&["for-each-ref"], Some(128), "first")
1261 } else {
1262 failed_with(&["for-each-ref"], None, "free(): double free detected")
1263 })
1264 },
1265 || {},
1266 );
1267 let err = out.unwrap_err();
1268 assert_eq!(calls, 2);
1269 let detail = err.detail().expect("detail");
1270 assert_eq!(detail.exit_code, None);
1271 assert!(detail.stderr.contains("double free"), "{}", detail.stderr);
1272 }
1273}
1274
1275#[cfg(test)]
1276mod failure_detail_tests {
1277 use super::*;
1278
1279 #[test]
1282 fn the_transport_allowlist_blocks_remote_helpers() {
1283 let dir = tempfile::tempdir().unwrap();
1284 let marker = dir.path().join("ran");
1285 let url = format!("ext::sh -c touch% {}", marker.display());
1286 assert!(run(dir.path(), &["ls-remote", &url]).is_err());
1287 assert!(!marker.exists(), "the helper command must not run");
1288 assert!(full_args(&["fetch"])
1289 .windows(2)
1290 .any(|w| w == ["-c", "protocol.allow=never"]));
1291 }
1292
1293 #[test]
1296 fn a_failed_command_hides_credentials_everywhere() {
1297 let err = failed_with(
1298 &["push", "https://me:topsecret@host/r.git"],
1299 Some(128),
1300 "fatal: Authentication failed for 'https://me:topsecret@host/r.git/'\n",
1301 );
1302 let all = format!("{err} {err:?}");
1303 assert!(!all.contains("topsecret"), "{all}");
1304 let detail = err.detail().expect("detail");
1305 assert_eq!(detail.exit_code, Some(128));
1306 assert_eq!(detail.operation, "push");
1307 assert!(detail.command.as_deref().unwrap().starts_with("git push"));
1308 assert!(detail.stderr.contains("Authentication failed"));
1309 }
1310}
1311
1312#[cfg(test)]
1313mod lfs_classifier_tests {
1314 use super::*;
1315 use gitpoulpi_core::domain::LfsUnavailableReason;
1316 use gitpoulpi_core::Error;
1317
1318 fn is_missing(stderr: &str) -> bool {
1319 matches!(
1320 classify_lfs_failure(stderr),
1321 Some(Error::LfsUnavailable {
1322 reason: LfsUnavailableReason::Missing
1323 })
1324 )
1325 }
1326
1327 #[test]
1330 fn the_recorded_missing_program_messages_are_recognized() {
1331 assert!(is_missing(
1332 "git-lfs filter-process: git-lfs: command not found\nfatal: a.bin: smudge filter lfs failed"
1333 ));
1334 assert!(is_missing(
1335 "git: 'lfs' is not a git command. See 'git --help'."
1336 ));
1337 assert!(is_missing(
1338 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. \
1339 If you no longer wish to use Git LFS, remove this hook by deleting the 'pre-push' file in the hooks directory."
1340 ));
1341 }
1342
1343 #[test]
1344 fn ordinary_failures_are_not_mistaken_for_a_missing_program() {
1345 assert!(!is_missing("fatal: not a git repository"));
1346 assert!(!is_missing(
1347 "error: pathspec 'lfs' did not match any file(s) known to git"
1348 ));
1349 assert!(!is_missing("remote: Git LFS: (0 of 1 files) 404 not found"));
1350 }
1351
1352 #[test]
1353 fn a_failed_command_carries_the_typed_error_or_the_plain_one() {
1354 assert!(matches!(
1355 failed(&["checkout", "x"], "git-lfs: command not found"),
1356 Error::LfsUnavailable { .. }
1357 ));
1358 assert!(
1359 matches!(failed(&["checkout", "x"], "boom"), Error::Git { message, .. } if message.contains("checkout x failed: boom"))
1360 );
1361 }
1362}
1363
1364#[cfg(test)]
1365mod resolve_tests {
1366 use super::*;
1367
1368 #[test]
1369 fn cmd_shim_resolves_to_the_mingw_binary_next_to_it() {
1370 let root = tempfile::tempdir().unwrap();
1371 let cmd = root.path().join("cmd");
1372 let bin = root.path().join("mingw64").join("bin");
1373 std::fs::create_dir_all(&cmd).unwrap();
1374 std::fs::create_dir_all(&bin).unwrap();
1375 std::fs::write(cmd.join("git.exe"), "").unwrap();
1376 let path = std::env::join_paths([cmd.clone()]).unwrap();
1377 assert_eq!(windows_unshimmed_git(Some(&path)), None);
1379 std::fs::write(bin.join("git.exe"), "").unwrap();
1380 assert_eq!(
1381 windows_unshimmed_git(Some(&path)),
1382 Some(bin.join("git.exe"))
1383 );
1384 let path = std::env::join_paths([bin]).unwrap();
1386 assert_eq!(windows_unshimmed_git(Some(&path)), None);
1387 }
1388}
1389
1390#[cfg(test)]
1391mod stdin_writer_tests {
1392 use super::*;
1393
1394 #[test]
1395 fn a_stdin_the_child_never_reads_is_reported_not_swallowed() {
1396 let dir = tempfile::tempdir().unwrap();
1397 let input = vec![b'x'; 4 << 20];
1400 assert!(run_bytes_with_stdin(dir.path(), &["--version"], &input).is_err());
1401 assert!(run_with_stdin(dir.path(), &["--version"], &"x".repeat(4 << 20)).is_err());
1402 }
1403}
1404
1405#[cfg(test)]
1406mod network_auth_tests {
1407 use super::*;
1408
1409 fn envs(cmd: &Command) -> Vec<(String, Option<String>)> {
1410 cmd.get_envs()
1411 .map(|(k, v)| {
1412 (
1413 k.to_string_lossy().into_owned(),
1414 v.map(|v| v.to_string_lossy().into_owned()),
1415 )
1416 })
1417 .collect()
1418 }
1419
1420 #[test]
1423 fn an_entry_replaces_the_global_mode_and_sits_before_the_subcommand() {
1424 let dir = tempfile::tempdir().unwrap();
1425 set_network_auth(
1426 dir.path(),
1427 Some(NetworkAuth {
1428 credential_helpers: Some(vec!["!h".into()]),
1429 credential_url_helpers: vec![("https://h".into(), "!u".into())],
1430 credential_username: Some("u".into()),
1431 no_prompt: true,
1432 reset_extra_header: true,
1433 ssh_command: Some("ssh -i k".into()),
1434 env: vec![("GRANT".into(), "g1".into())],
1435 }),
1436 );
1437 let mut cmd = Command::new("git");
1438 let extra = apply_network_auth(&mut cmd, dir.path());
1439 let all = full_args_with(&extra, &["fetch", "origin"]);
1440 let flat = all.join(" ");
1441 assert!(
1442 flat.contains(
1443 "-c credential.helper= -c credential.helper=!h \
1444 -c credential.https://h.helper=!u -c credential.username=u \
1445 -c core.askPass= -c http.extraHeader= fetch origin"
1446 ),
1447 "{flat}"
1448 );
1449 assert!(
1451 flat.starts_with("--no-pager -c protocol.allow=never"),
1452 "{flat}"
1453 );
1454 let env = envs(&cmd);
1455 let get = |name: &str| env.iter().find(|(k, _)| k == name).cloned();
1456 assert_eq!(
1457 get("GIT_SSH_COMMAND"),
1458 Some(("GIT_SSH_COMMAND".into(), Some("ssh -i k".into())))
1459 );
1460 assert_eq!(get("GRANT").and_then(|e| e.1), Some("g1".into()));
1461 assert_eq!(
1462 get("GIT_TERMINAL_PROMPT").and_then(|e| e.1),
1463 Some("0".into())
1464 );
1465 assert_eq!(get("GIT_ASKPASS"), Some(("GIT_ASKPASS".into(), None)));
1466 assert_eq!(get("SSH_ASKPASS"), Some(("SSH_ASKPASS".into(), None)));
1467
1468 set_network_auth(dir.path(), None);
1469 let mut cmd = Command::new("git");
1470 let extra = apply_network_auth(&mut cmd, dir.path());
1471 assert!(
1472 !extra.iter().any(|a| a.starts_with("core.askPass")),
1473 "an entry survived its removal: {extra:?}"
1474 );
1475 }
1476
1477 #[test]
1480 fn entries_are_keyed_by_repository_root() {
1481 let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
1482 set_network_auth(
1483 a.path(),
1484 Some(NetworkAuth {
1485 no_prompt: true,
1486 ..NetworkAuth::default()
1487 }),
1488 );
1489 assert!(network_auth_for(a.path()).is_some());
1490 assert!(network_auth_for(b.path()).is_none());
1491 let dotted = a.path().join(".");
1492 assert!(network_auth_for(&dotted).is_some());
1493 set_network_auth(a.path(), None);
1494 assert!(network_auth_for(a.path()).is_none());
1495 }
1496}