1use std::process::{Command, Stdio};
4
5fn retrying<T>(mut attempt: impl FnMut() -> std::io::Result<T>) -> std::io::Result<T> {
17 let mut delay = std::time::Duration::from_millis(10);
18 for tries_left in [2u8, 1, 0] {
19 match attempt() {
20 Err(e) if tries_left > 0 && transient(&e) => {
21 std::thread::sleep(delay);
22 delay *= 3;
23 }
24 other => return other,
25 }
26 }
27 unreachable!("the zero-tries arm returns")
28}
29
30fn transient(e: &std::io::Error) -> bool {
35 if matches!(
36 e.kind(),
37 std::io::ErrorKind::Interrupted | std::io::ErrorKind::WouldBlock
38 ) {
39 return true;
40 }
41 matches!(e.raw_os_error(), Some(4 | 11 | 26 | 35))
42}
43
44pub fn stdout(args: &[&str]) -> Option<String> {
47 let mut cmd = Command::new("git");
48 cmd.args(args).stderr(Stdio::null());
49 let out = retrying(|| cmd.output()).ok()?;
50 if !out.status.success() {
51 return None;
52 }
53 Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
54}
55
56pub fn stdout_in(dir: &std::path::Path, args: &[&str]) -> Option<String> {
62 let mut cmd = Command::new("git");
63 cmd.arg("-C").arg(dir).args(args).stderr(Stdio::null());
64 let out = retrying(|| cmd.output()).ok()?;
65 if !out.status.success() {
66 return None;
67 }
68 Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
69}
70
71pub fn succeeds_in(dir: &std::path::Path, args: &[&str]) -> bool {
75 let mut cmd = Command::new("git");
76 cmd.arg("-C")
77 .arg(dir)
78 .args(args)
79 .stdin(Stdio::null())
80 .stdout(Stdio::null())
81 .stderr(Stdio::null());
82 retrying(|| cmd.status())
83 .map(|s| s.success())
84 .unwrap_or(false)
85}
86
87pub fn stdout_piped(args: &[&str], stdin: &str) -> Option<String> {
91 use std::io::Write;
92 let mut cmd = Command::new("git");
93 cmd.args(args)
94 .stdin(Stdio::piped())
95 .stdout(Stdio::piped())
96 .stderr(Stdio::null());
97 let mut child = retrying(|| cmd.spawn()).ok()?;
98 child.stdin.take()?.write_all(stdin.as_bytes()).ok()?;
99 let out = child.wait_with_output().ok()?;
100 out.status
101 .success()
102 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
103}
104
105pub fn stdout_piped_raw(args: &[&str], stdin: &str) -> Option<Vec<u8>> {
112 use std::io::Write;
113 let mut cmd = Command::new("git");
114 cmd.args(args)
115 .stdin(Stdio::piped())
116 .stdout(Stdio::piped())
117 .stderr(Stdio::null());
118 let mut child = retrying(|| cmd.spawn()).ok()?;
119 child.stdin.take()?.write_all(stdin.as_bytes()).ok()?;
120 let out = child.wait_with_output().ok()?;
121 out.status.success().then_some(out.stdout)
122}
123
124pub fn stdout_piped_in(dir: &std::path::Path, args: &[&str], stdin: &[u8]) -> Option<String> {
131 use std::io::Write;
132 let mut cmd = Command::new("git");
133 cmd.arg("-C")
134 .arg(dir)
135 .args(args)
136 .stdin(Stdio::piped())
137 .stdout(Stdio::piped())
138 .stderr(Stdio::null());
139 let mut child = retrying(|| cmd.spawn()).ok()?;
140 child.stdin.take()?.write_all(stdin).ok()?;
141 let out = child.wait_with_output().ok()?;
142 out.status
143 .success()
144 .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
145}
146
147pub fn stdout_raw(args: &[&str]) -> Option<Vec<u8>> {
150 let mut cmd = Command::new("git");
151 cmd.args(args).stderr(Stdio::null());
152 let out = retrying(|| cmd.output()).ok()?;
153 out.status.success().then_some(out.stdout)
154}
155
156pub fn stdout_raw_or_why(args: &[&str]) -> Result<Vec<u8>, String> {
160 let mut cmd = Command::new("git");
161 cmd.args(args);
162 let out = retrying(|| cmd.output()).map_err(|e| format!("cannot run git: {e}"))?;
163 if out.status.success() {
164 return Ok(out.stdout);
165 }
166 let said = String::from_utf8_lossy(&out.stderr).trim().to_string();
167 Err(if said.is_empty() {
168 format!("exit {}", out.status.code().unwrap_or(-1))
169 } else {
170 said
171 })
172}
173
174pub struct Output {
176 pub code: i32,
177 pub stdout: String,
178 pub stderr: String,
179}
180
181pub fn output(args: &[&str]) -> Option<Output> {
191 let mut cmd = Command::new("git");
192 cmd.args(args);
193 full_output(cmd)
194}
195
196pub fn output_in(dir: &std::path::Path, args: &[&str]) -> Option<Output> {
200 let mut cmd = Command::new("git");
201 cmd.arg("-C").arg(dir).args(args);
202 full_output(cmd)
203}
204
205fn full_output(mut cmd: Command) -> Option<Output> {
206 cmd.stdin(Stdio::null());
207 let out = retrying(|| cmd.output()).ok()?;
208 Some(Output {
209 code: out.status.code()?,
212 stdout: String::from_utf8_lossy(&out.stdout).trim().to_string(),
213 stderr: String::from_utf8_lossy(&out.stderr).trim().to_string(),
214 })
215}
216
217#[derive(Debug)]
223pub enum Probe {
224 Exit(i32),
226 TimedOut(u64),
228 Failed,
230}
231
232pub fn probe(args: &[&str], budget_secs: u64) -> Probe {
243 probe_env(args, budget_secs, &[])
244}
245
246#[derive(Clone, Copy, Debug, PartialEq)]
248pub enum Ssh {
249 User,
253 Batch,
255}
256
257pub fn remote_env(ssh: Ssh) -> (Vec<&'static str>, Vec<(&'static str, &'static str)>) {
269 let args = vec![
270 "-c",
271 "http.lowSpeedLimit=1",
272 "-c",
273 "http.lowSpeedTime=10",
274 "-c",
275 "credential.interactive=never",
276 ];
277 let mut env = vec![
278 ("GIT_TERMINAL_PROMPT", "0"),
279 ("GIT_ASKPASS", ""),
280 ("GCM_INTERACTIVE", "never"),
281 ];
282 if ssh == Ssh::Batch {
283 env.push((
284 "GIT_SSH_COMMAND",
285 "ssh -o BatchMode=yes -o ConnectTimeout=10",
286 ));
287 }
288 (args, env)
289}
290
291pub fn configured_ssh() -> Ssh {
293 let set = |v: &str| std::env::var_os(v).is_some_and(|v| !v.is_empty());
294 if set("GIT_SSH_COMMAND") || set("GIT_SSH") || succeeds(&["config", "--get", "core.sshCommand"])
295 {
296 Ssh::User
297 } else {
298 Ssh::Batch
299 }
300}
301
302pub fn probe_remote(args: &[&str], budget_secs: u64) -> Probe {
304 let (pre, env) = remote_env(configured_ssh());
305 let mut all: Vec<&str> = pre;
306 all.extend_from_slice(args);
307 probe_env(&all, budget_secs, &env)
308}
309
310pub fn probe_env(args: &[&str], budget_secs: u64, env: &[(&str, &str)]) -> Probe {
312 probe_run(args, budget_secs, env, false).0
313}
314
315pub fn probe_remote_stdout(args: &[&str], budget_secs: u64) -> (Probe, String) {
324 let (pre, env) = remote_env(configured_ssh());
325 let mut all: Vec<&str> = pre;
326 all.extend_from_slice(args);
327 probe_run(&all, budget_secs, &env, true)
328}
329
330fn probe_run(
331 args: &[&str],
332 budget_secs: u64,
333 env: &[(&str, &str)],
334 capture: bool,
335) -> (Probe, String) {
336 let mut cmd = Command::new("git");
337 cmd.args(args)
338 .envs(env.iter().copied())
339 .stdin(Stdio::null())
340 .stdout(if capture {
341 Stdio::piped()
342 } else {
343 Stdio::null()
344 })
345 .stderr(Stdio::null());
346 if budget_secs == 0 && !capture {
347 return match retrying(|| cmd.status()) {
348 Ok(s) => (
349 s.code().map(Probe::Exit).unwrap_or(Probe::Failed),
350 String::new(),
351 ),
352 Err(_) => (Probe::Failed, String::new()),
353 };
354 }
355 let Ok(mut child) = retrying(|| cmd.spawn()) else {
356 return (Probe::Failed, String::new());
357 };
358 let drained = child.stdout.take().map(|mut out| {
362 let (tx, rx) = std::sync::mpsc::channel();
363 std::thread::spawn(move || {
364 use std::io::Read;
365 let mut text = String::new();
366 let read = out.read_to_string(&mut text);
368 drop(read);
369 let sent = tx.send(text);
371 drop(sent);
372 });
373 rx
374 });
375 let read_out = |drained: &Option<std::sync::mpsc::Receiver<String>>| -> Option<String> {
379 match drained {
380 None => Some(String::new()),
381 Some(rx) => rx.recv_timeout(std::time::Duration::from_secs(2)).ok(),
382 }
383 };
384 let budget = if budget_secs == 0 { 3600 } else { budget_secs };
388 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(budget);
389 loop {
390 match child.try_wait() {
391 Ok(Some(s)) => {
392 return match read_out(&drained) {
393 Some(text) => (s.code().map(Probe::Exit).unwrap_or(Probe::Failed), text),
394 None => (Probe::Failed, String::new()),
395 };
396 }
397 Ok(None) => {}
398 Err(_) => return (Probe::Failed, String::new()),
399 }
400 if std::time::Instant::now() >= deadline {
401 let _ = child.kill();
402 let _ = child.wait();
403 return (Probe::TimedOut(budget), String::new());
404 }
405 std::thread::sleep(std::time::Duration::from_millis(25));
406 }
407}
408
409pub fn succeeds(args: &[&str]) -> bool {
411 let mut cmd = Command::new("git");
412 cmd.args(args)
413 .stdin(Stdio::null())
414 .stdout(Stdio::null())
415 .stderr(Stdio::null());
416 retrying(|| cmd.status())
417 .map(|s| s.success())
418 .unwrap_or(false)
419}
420
421pub fn stdout_paths(args: &[&str]) -> Option<Vec<String>> {
434 let (first, rest) = args.split_first()?;
435 let mut argv = Vec::with_capacity(args.len() + 1);
436 argv.push(*first);
437 argv.push("-z");
438 argv.extend_from_slice(rest);
439 stdout_raw(&argv).map(|raw| split_nul_paths(&raw))
440}
441
442pub(crate) fn split_nul_paths(raw: &[u8]) -> Vec<String> {
447 raw.split(|&b| b == 0)
448 .filter(|s| !s.is_empty())
449 .map(|s| String::from_utf8_lossy(s).into_owned())
450 .collect()
451}
452
453#[cfg(test)]
454mod retry_tests {
455 use super::*;
456
457 #[test]
459 fn transient_covers_the_fork_pressure_kinds_and_nothing_else() {
460 for code in [4, 11, 26, 35] {
461 assert!(
462 transient(&std::io::Error::from_raw_os_error(code)),
463 "raw {code} is a loaded-machine hiccup"
464 );
465 }
466 assert!(transient(&std::io::Error::from(
467 std::io::ErrorKind::Interrupted
468 )));
469 assert!(!transient(&std::io::Error::from(
470 std::io::ErrorKind::NotFound
471 )));
472 assert!(!transient(&std::io::Error::from_raw_os_error(13))); }
474
475 #[test]
478 fn retrying_gives_up_after_three_transient_failures() {
479 let mut calls = 0;
480 let r: std::io::Result<()> = retrying(|| {
481 calls += 1;
482 Err(std::io::Error::from_raw_os_error(11))
483 });
484 assert!(r.is_err());
485 assert_eq!(calls, 3);
486 }
487
488 #[test]
491 fn a_hard_error_is_not_retried() {
492 let mut calls = 0;
493 let r: std::io::Result<()> = retrying(|| {
494 calls += 1;
495 Err(std::io::Error::from(std::io::ErrorKind::NotFound))
496 });
497 assert!(r.is_err());
498 assert_eq!(calls, 1);
499 }
500
501 #[test]
503 fn one_hiccup_then_an_answer_is_an_answer() {
504 let mut calls = 0;
505 let r = retrying(|| {
506 calls += 1;
507 if calls == 1 {
508 Err(std::io::Error::from_raw_os_error(4))
509 } else {
510 Ok(42)
511 }
512 });
513 assert_eq!(r.unwrap(), 42);
514 assert_eq!(calls, 2);
515 }
516}
517
518#[cfg(test)]
519mod tests {
520 use super::*;
521
522 #[test]
523 fn probe_remote_stdout_returns_what_git_printed_and_the_exit_code() {
524 let _cwd = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
529 let dir =
530 std::env::temp_dir().join(format!("greengate-probe-stdout-{}", std::process::id()));
531 let _ = std::fs::remove_dir_all(&dir);
532 std::fs::create_dir_all(&dir).expect("mkdir");
533 let run = |args: &[&str]| {
534 let out = Command::new("git")
535 .arg("-C")
536 .arg(&dir)
537 .args(args)
538 .output()
539 .expect("git");
540 assert!(out.status.success(), "{args:?}");
541 String::from_utf8_lossy(&out.stdout).trim().to_string()
542 };
543 run(&["init", "-q", "--initial-branch=main", "."]);
544 run(&[
545 "-c",
546 "user.email=t@e",
547 "-c",
548 "user.name=t",
549 "-c",
550 "core.hooksPath=/dev/null",
551 "commit",
552 "-q",
553 "--allow-empty",
554 "-m",
555 "x",
556 ]);
557 let sha = run(&["rev-parse", "HEAD"]);
558 let url = dir.to_string_lossy().to_string();
559
560 let (probe, out) = probe_remote_stdout(&["ls-remote", &url, "refs/heads/main"], 30);
561 assert!(matches!(probe, Probe::Exit(0)), "{probe:?} {out}");
562 assert!(out.starts_with(&sha), "{out}");
563
564 let (probe, out) = probe_remote_stdout(&["ls-remote", &url, "refs/heads/nope"], 30);
566 assert!(matches!(probe, Probe::Exit(0)), "{probe:?} {out}");
567 assert!(out.trim().is_empty());
568
569 let (probe, out) = probe_remote_stdout(&["ls-remote", "/nonexistent/repo.git"], 30);
571 assert!(matches!(probe, Probe::Exit(c) if c != 0));
572 assert!(out.is_empty());
573 let _ = std::fs::remove_dir_all(&dir);
574 }
575
576 #[test]
577 fn splits_on_nul_and_drops_the_trailing_empty_segment() {
578 assert_eq!(
579 split_nul_paths(b"src/main.rs\0Cargo.toml\0"),
580 vec!["src/main.rs", "Cargo.toml"]
581 );
582 }
583
584 #[test]
585 fn empty_input_is_no_paths() {
586 assert_eq!(split_nul_paths(b""), Vec::<String>::new());
587 }
588
589 #[test]
596 fn a_non_ascii_path_is_not_reinterpreted_as_its_quoted_form() {
597 let mut raw = "é.json".as_bytes().to_vec();
598 raw.push(0);
599 let got = split_nul_paths(&raw);
600 assert_eq!(got, vec!["é.json".to_string()]);
601 assert_ne!(got[0], "\"\\303\\251.json\"", "must not be the quoted form");
602 }
603}
604
605pub fn current_branch() -> Option<&'static str> {
613 static BRANCH: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
614 BRANCH
615 .get_or_init(|| stdout(&["symbolic-ref", "--quiet", "--short", "HEAD"]))
616 .as_deref()
617}
618
619pub fn has_remote() -> bool {
623 static REMOTE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
624 *REMOTE.get_or_init(|| stdout(&["remote"]).is_some_and(|r| !r.is_empty()))
625}
626
627#[cfg(test)]
628mod probe_tests {
629 use super::*;
630
631 #[test]
634 fn a_long_ls_remote_is_drained_while_the_child_runs() {
635 let dir = std::env::temp_dir().join(format!("greengate-probe-{}", std::process::id()));
636 let _ = std::fs::remove_dir_all(&dir); let path = dir.display().to_string();
638 let git = |args: &[&str]| {
639 let mut all = vec!["-C", path.as_str()];
640 all.extend_from_slice(args);
641 let mut cmd = Command::new("git");
642 cmd.args(&all).env("GIT_CONFIG_GLOBAL", "/dev/null");
643 for (k, _) in std::env::vars_os() {
644 if k.to_string_lossy().starts_with("GIT_") {
645 cmd.env_remove(&k);
646 }
647 }
648 cmd.env("GIT_CONFIG_GLOBAL", "/dev/null");
649 cmd.output().expect("git")
650 };
651 std::fs::create_dir_all(&dir).expect("mkdir");
652 assert!(git(&["init", "-q", "--bare"]).status.success());
653 let commit = {
654 let out = Command::new("git")
655 .args([
656 "-C",
657 path.as_str(),
658 "commit-tree",
659 "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
660 "-m",
661 "x",
662 ])
663 .env("GIT_AUTHOR_NAME", "t")
664 .env("GIT_AUTHOR_EMAIL", "t@t")
665 .env("GIT_COMMITTER_NAME", "t")
666 .env("GIT_COMMITTER_EMAIL", "t@t")
667 .env("GIT_CONFIG_GLOBAL", "/dev/null")
668 .output()
669 .expect("commit-tree");
670 String::from_utf8_lossy(&out.stdout).trim().to_string()
671 };
672 assert_eq!(commit.len(), 40, "a commit");
673 let refs: String = (0..3000)
674 .map(|i| format!("{commit} refs/pull/{i}/head-with-a-long-name-to-fill-the-pipe\n"))
675 .collect();
676 std::fs::write(dir.join("packed-refs"), refs).expect("packed-refs");
677 let started = std::time::Instant::now();
678 let (probe, out) = probe_remote_stdout(&["ls-remote", path.as_str()], 20);
679 assert!(matches!(probe, Probe::Exit(0)), "{probe:?}");
680 assert_eq!(out.lines().count(), 3000);
681 assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed());
682 std::fs::remove_dir_all(&dir).expect("clean");
683 }
684
685 #[test]
688 fn a_stdout_held_open_after_the_child_exits_is_a_failure_not_an_empty_answer() {
689 let started = std::time::Instant::now();
690 let (probe, out) =
692 probe_remote_stdout(&["-c", "alias.holdit=!(sleep 4 &); true", "holdit"], 20);
693 assert!(matches!(probe, Probe::Failed), "{probe:?}");
694 assert_eq!(out, "");
695 assert!(started.elapsed().as_secs() < 4, "{:?}", started.elapsed());
696 }
697}