use std::{path::Path, process::Stdio};
use tokio::io::AsyncWriteExt as _;
use super::{answered, command, WorktreeError};
const PLAIN: [&str; 7] = [
"--literal-pathspecs",
"--no-color",
"--no-ext-diff",
"--no-textconv",
"--no-renames",
"--no-relative",
"--unified=1",
];
pub(super) async fn squashed_into(
dir: &Path,
base: &str,
commit: &str,
) -> Result<bool, WorktreeError> {
let Some(fork) = answered(dir, "merge-base", ["merge-base", base, commit]).await? else {
return Ok(false);
};
let Some(wanted) = patch_ids(dir, "diff", &[fork.as_str(), commit], None)
.await?
.into_iter()
.next()
else {
return Ok(false);
};
let names = ["diff", "--name-only", "-z", "--no-renames", "--no-relative"];
let names = command(dir, [&names[..], &[fork.as_str(), commit]].concat(), &[])
.output()
.await
.map_err(WorktreeError::NoGit)?;
if !names.status.success() {
return Err(failed(dir, "diff", &names));
}
let mut stdin = format!("{fork}..{base}\n").into_bytes();
let names: Vec<&[u8]> = names
.stdout
.split(|&byte| byte == 0)
.filter(|name| !name.is_empty())
.collect();
if !names.iter().any(|name| name.contains(&b'\n')) {
stdin.extend_from_slice(b"--\n");
for name in names {
stdin.extend_from_slice(name);
stdin.push(b'\n');
}
}
let log = ["--stdin", "--no-merges", "--patch", "--format=commit %H"];
let found = patch_ids(dir, "log", &log, Some(stdin))
.await?
.contains(&wanted);
if found {
tracing::debug!(%fork, %commit, %base, "found the squash commit of a worktree's branch");
}
Ok(found)
}
fn failed(dir: &Path, action: &str, output: &std::process::Output) -> WorktreeError {
WorktreeError::Git {
action: action.to_owned(),
repository: dir.to_path_buf(),
detail: String::from_utf8_lossy(&output.stderr).trim().to_owned(),
}
}
async fn patch_ids(
dir: &Path,
subcommand: &str,
args: &[&str],
stdin: Option<Vec<u8>>,
) -> Result<Vec<String>, WorktreeError> {
let (reader, writer) = std::io::pipe().map_err(WorktreeError::NoGit)?;
let [literal, rest @ ..] = PLAIN;
let full = [&[literal, subcommand][..], &rest, args].concat();
let mut patches = command(dir, full, &[])
.stdin(match stdin {
Some(_) => Stdio::piped(),
None => Stdio::null(),
})
.stdout(writer)
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(WorktreeError::NoGit)?;
let ids = command(dir, ["patch-id", "--stable"], &[])
.stdin(reader)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(WorktreeError::NoGit)?;
if let (Some(input), Some(mut pipe)) = (stdin, patches.stdin.take()) {
let _ = pipe.write_all(&input).await;
}
let (ids, patched) = tokio::join!(ids.wait_with_output(), patches.wait_with_output());
let (ids, patched) = (
ids.map_err(WorktreeError::NoGit)?,
patched.map_err(WorktreeError::NoGit)?,
);
if !ids.status.success() {
return Err(failed(dir, "patch-id", &ids));
}
if !patched.status.success() {
return Err(failed(dir, subcommand, &patched));
}
Ok(String::from_utf8_lossy(&ids.stdout)
.lines()
.filter_map(|line| line.split_whitespace().next().map(str::to_owned))
.collect())
}