use std::collections::BTreeMap;
use std::io::{self, Read};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
use humansize::{DECIMAL, format_size};
use super::{GitError, Step, StepKind, StepOutcome};
const GIT: &str = "git";
const POLL_START: Duration = Duration::from_micros(100);
const POLL_CEILING: Duration = Duration::from_millis(25);
#[derive(Debug)]
struct Completed {
code: Option<i32>,
stdout: String,
stderr: String,
timed_out: bool,
}
pub(super) fn ensure_git_available(timeout: Duration) -> Result<(), GitError> {
let mut command = Command::new(GIT);
command.arg("--version");
match run_command(&mut command, Instant::now() + timeout) {
Ok(_) => Ok(()),
Err(source) if source.kind() == io::ErrorKind::NotFound => Err(GitError::NotInstalled),
Err(source) => Err(GitError::Spawn { source }),
}
}
#[cfg(windows)]
pub(crate) fn for_git(path: &Path) -> std::borrow::Cow<'_, Path> {
use std::path::{Component, Prefix};
let mut components = path.components();
let Some(Component::Prefix(prefix)) = components.next() else {
return std::borrow::Cow::Borrowed(path);
};
let mut simplified = match prefix.kind() {
Prefix::VerbatimDisk(letter) => std::path::PathBuf::from(format!(r"{}:\", letter as char)),
Prefix::VerbatimUNC(server, share) => {
std::path::PathBuf::from(format!(r"\\{}\{}\", server.display(), share.display()))
}
_ => return std::borrow::Cow::Borrowed(path),
};
simplified.extend(components.skip_while(|part| matches!(part, Component::RootDir)));
std::borrow::Cow::Owned(simplified)
}
#[cfg(not(windows))]
pub(crate) fn for_git(path: &Path) -> std::borrow::Cow<'_, Path> {
std::borrow::Cow::Borrowed(path)
}
const NO_HOOKS: &str = "core.hooksPath=";
pub(super) fn run_step(
path: &Path,
git_dir: &Path,
kind: StepKind,
remote: Option<String>,
args: &[&str],
deadline: Instant,
) -> Step {
let mut recorded = vec![
GIT.to_owned(),
"-c".to_owned(),
NO_HOOKS.to_owned(),
format!("--git-dir={}", for_git(git_dir).display()),
];
recorded.extend(args.iter().map(|arg| (*arg).to_owned()));
let mut command = Command::new(GIT);
command.current_dir(path).args(&recorded[1..]);
let outcome = match run_command(&mut command, deadline) {
Ok(completed) if completed.timed_out => StepOutcome::TimedOut,
Ok(completed) if completed.code == Some(0) => StepOutcome::Succeeded {
summary: summarize(kind, &completed),
},
Ok(completed) => StepOutcome::Failed {
code: completed.code,
message: first_lines(&completed.stderr, &completed.stdout),
},
Err(source) => StepOutcome::Failed {
code: None,
message: source.to_string(),
},
};
Step {
kind,
remote,
command: recorded,
outcome,
}
}
pub(super) fn git_stdout(work_tree: &Path, args: &[&std::ffi::OsStr], timeout: Duration) -> Option<String> {
let mut command = Command::new(GIT);
command.arg("-C").arg(for_git(work_tree).as_os_str()).args(args);
let completed = run_command(&mut command, Instant::now() + timeout).ok()?;
(completed.code == Some(0) && !completed.timed_out).then_some(completed.stdout)
}
pub(super) fn git_bytes(work_tree: &Path, args: &[&str], timeout: Duration) -> Option<Vec<u8>> {
let mut child = Command::new(GIT)
.arg("-C")
.arg(for_git(work_tree).as_os_str())
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.env("GIT_TERMINAL_PROMPT", "0")
.spawn()
.ok()?;
let mut stdout = child.stdout.take()?;
let reader = std::thread::spawn(move || {
let mut bytes = Vec::new();
stdout.read_to_end(&mut bytes).map(|_| bytes)
});
let (code, timed_out) = wait_with_deadline(&mut child, Instant::now() + timeout).ok()?;
let bytes = reader.join().ok()?.ok()?;
(code == Some(0) && !timed_out).then_some(bytes)
}
fn run_command(command: &mut Command, deadline: Instant) -> io::Result<Completed> {
let mut child = command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.env("GIT_TERMINAL_PROMPT", "0")
.spawn()?;
let stdout = reader(child.stdout.take());
let stderr = reader(child.stderr.take());
let (code, timed_out) = wait_with_deadline(&mut child, deadline)?;
Ok(Completed {
code,
stdout: stdout.map(join_reader).unwrap_or_default(),
stderr: stderr.map(join_reader).unwrap_or_default(),
timed_out,
})
}
fn reader<R: Read + Send + 'static>(stream: Option<R>) -> Option<std::thread::JoinHandle<String>> {
stream.map(|mut stream| {
std::thread::spawn(move || {
let mut text = String::new();
let _ = stream.read_to_string(&mut text);
text
})
})
}
fn join_reader(handle: std::thread::JoinHandle<String>) -> String {
handle.join().unwrap_or_default()
}
fn wait_with_deadline(child: &mut Child, deadline: Instant) -> io::Result<(Option<i32>, bool)> {
let mut wait = POLL_START;
loop {
if let Some(status) = child.try_wait()? {
return Ok((status.code(), false));
}
if Instant::now() >= deadline {
child.kill()?;
let status = child.wait()?;
return Ok((status.code(), true));
}
std::thread::sleep(wait);
wait = (wait * 2).min(POLL_CEILING);
}
}
fn summarize(kind: StepKind, completed: &Completed) -> String {
let output = format!("{}{}", completed.stdout, completed.stderr);
match kind {
StepKind::WorktreePrune => count_summary(&output, "Removing", "stale worktree"),
StepKind::RemotePrune => count_summary(&output, "prune", "gone branch"),
StepKind::RemoteList => completed.stdout.clone(),
StepKind::Gc => String::new(),
StepKind::CountObjects => count_objects_summary(&completed.stdout),
}
}
fn count_summary(output: &str, needle: &str, noun: &str) -> String {
let count = output.lines().filter(|line| line.contains(needle)).count();
if count == 0 {
return String::new();
}
format!("{count} {} pruned", plural(count, noun))
}
fn count_objects_summary(stdout: &str) -> String {
let fields: BTreeMap<&str, u64> = stdout
.lines()
.filter_map(|line| line.split_once(':'))
.filter_map(|(key, value)| value.trim().parse().ok().map(|value| (key.trim(), value)))
.collect();
let field = |name: &str| fields.get(name).copied().unwrap_or(0);
let (loose, packed, packs) = (field("count"), field("in-pack"), field("packs"));
format!(
"gc withheld; {loose} loose {} ({}), {packed} packed in {packs} {} ({})",
plural_u64(loose, "object"),
format_size(field("size") * 1024, DECIMAL),
plural_u64(packs, "pack"),
format_size(field("size-pack") * 1024, DECIMAL),
)
}
fn first_lines(stderr: &str, stdout: &str) -> String {
let source = if stderr.trim().is_empty() { stdout } else { stderr };
let message: Vec<&str> = source
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.take(2)
.collect();
if message.is_empty() {
"git failed without saying why".to_owned()
} else {
message.join("; ")
}
}
fn plural(count: usize, noun: &str) -> String {
if count == 1 {
noun.to_owned()
} else {
format!("{noun}s")
}
}
fn plural_u64(count: u64, noun: &str) -> String {
plural(usize::try_from(count).unwrap_or(usize::MAX), noun)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_count_what_a_worktree_prune_reported() {
let output = "Removing worktrees/one: gitdir file points to non-existent location\n\
Removing worktrees/two: gitdir file points to non-existent location\n";
assert_eq!(
count_summary(output, "Removing", "stale worktree"),
"2 stale worktrees pruned"
);
}
#[test]
fn should_say_nothing_when_git_pruned_nothing() {
assert_eq!(count_summary("", "Removing", "stale worktree"), "");
}
#[test]
fn should_read_the_object_counts_a_dry_run_reports_instead_of_repacking() {
let stdout = "count: 12\nsize: 48\nin-pack: 340\npacks: 2\nsize-pack: 1234\ngarbage: 0\n";
let summary = count_objects_summary(stdout);
assert!(summary.contains("12 loose objects"), "{summary}");
assert!(summary.contains("340 packed in 2 packs"), "{summary}");
}
#[test]
#[cfg(unix)]
fn should_kill_a_command_that_outlives_its_deadline() {
let mut command = Command::new("sleep");
command.arg("30");
let started = Instant::now();
let completed =
run_command(&mut command, Instant::now() + Duration::from_millis(200)).expect("sleep exists on unix");
assert!(completed.timed_out, "the deadline must be enforced, not merely noticed");
assert!(
started.elapsed() < Duration::from_secs(5),
"the child was killed rather than waited out: {:?}",
started.elapsed()
);
}
#[test]
#[cfg(unix)]
fn should_not_report_a_timeout_for_a_command_that_finished() {
let mut command = Command::new("true");
let completed = run_command(&mut command, Instant::now() + Duration::from_secs(30)).expect("true exists");
assert!(!completed.timed_out);
assert_eq!(completed.code, Some(0));
}
#[test]
#[cfg(windows)]
fn should_hand_git_a_path_it_understands() {
use std::path::Path;
assert_eq!(
for_git(Path::new(r"\\?\C:\Users\r\project\.git")).as_ref(),
Path::new(r"C:\Users\r\project\.git")
);
assert_eq!(
for_git(Path::new(r"\\?\UNC\server\share\project\.git")).as_ref(),
Path::new(r"\\server\share\project\.git")
);
assert_eq!(
for_git(Path::new(r"C:\already\fine")).as_ref(),
Path::new(r"C:\already\fine")
);
}
}