Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,48 @@ pub async fn new_branch_base(dir: &Path, remote: &str, head: &str) -> Result<Str
merge_base(dir, remote, &commit_sha(head)?, &[default.as_str()]).await
}

/// Whether `ancestor` is an ancestor of `descendant`. Returns `Ok(false)` when
/// `ancestor` is not an ancestor or is absent from the local object store while
/// `descendant` is present.
pub async fn is_ancestor(dir: &Path, ancestor: &str, descendant: &str) -> Result<bool, GitError> {
let ancestor = commit_sha(ancestor)?;
let descendant = commit_sha(descendant)?;
let output = Command::new("git")
.arg("-C")
.arg(dir)
.args(["merge-base", "--is-ancestor", &ancestor, &descendant])
.output()
.await
.map_err(|error| GitError::Unavailable(error.to_string()))?;
match output.status.code() {
Some(0) => Ok(true),
Some(1) => Ok(false),
// `git merge-base --is-ancestor` exits 128 when an object is missing
// locally. Only treat that as `Ok(false)` when `descendant` resolves
// and `ancestor` is the missing commit (e.g. an un-fetched remote tip).
Some(128) => {
let failed = || GitError::Failed {
command: format!("merge-base --is-ancestor {ancestor} {descendant}"),
stderr: String::from_utf8_lossy(&output.stderr).trim().to_owned(),
};
if resolve(dir, &descendant).await.is_ok()
&& matches!(
resolve(dir, &ancestor).await,
Err(GitError::UnknownRevision(_))
)
{
Ok(false)
} else {
Err(failed())
}
}
_ => Err(GitError::Failed {
command: format!("merge-base --is-ancestor {ancestor} {descendant}"),
stderr: String::from_utf8_lossy(&output.stderr).trim().to_owned(),
}),
}
}

/// The patch from `base_commit_sha` to `head`, or to `index` when `head` is
/// `None`.
async fn diff(
Expand Down Expand Up @@ -791,4 +833,40 @@ mod tests {
staged
);
}

#[tokio::test]
async fn is_ancestor_distinguishes_linear_diverged_and_missing_commits() {
let repo = tempfile::tempdir().unwrap();
let dir = repo.path();
run(dir, &["init", "-q", "-b", "main"]);
run(dir, &["config", "user.email", "dev@example.com"]);
run(dir, &["config", "user.name", "dev"]);
std::fs::write(dir.join("a.txt"), "base\n").unwrap();
run(dir, &["add", "a.txt"]);
run(dir, &["commit", "-qm", "base"]);
let base = run(dir, &["rev-parse", "HEAD"]).trim().to_owned();

run(dir, &["checkout", "-qb", "side"]);
std::fs::write(dir.join("a.txt"), "side\n").unwrap();
run(dir, &["commit", "-qam", "side"]);
let side = run(dir, &["rev-parse", "HEAD"]).trim().to_owned();

run(dir, &["checkout", "-q", "main"]);
std::fs::write(dir.join("a.txt"), "main\n").unwrap();
run(dir, &["commit", "-qam", "main"]);
let main_tip = run(dir, &["rev-parse", "HEAD"]).trim().to_owned();

assert!(is_ancestor(dir, &base, &main_tip).await.unwrap());
assert!(is_ancestor(dir, &main_tip, &main_tip).await.unwrap());
assert!(!is_ancestor(dir, &side, &main_tip).await.unwrap());
assert!(!is_ancestor(dir, &"f".repeat(40), &main_tip).await.unwrap());
assert!(matches!(
is_ancestor(dir, &base, &"f".repeat(40)).await,
Err(GitError::Failed { .. })
));
assert!(matches!(
is_ancestor(dir, "main", &main_tip).await,
Err(GitError::NotSha(_))
));
}
}
10 changes: 9 additions & 1 deletion src/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,15 @@ async fn subjects(hook: Hook, here: &Path, remote: &str) -> anyhow::Result<(Vec<
let base = if is_zero(&pushed.remote_sha) {
git::new_branch_base(here, remote, &pushed.local_sha).await
} else {
Ok(pushed.remote_sha)
// On a force-push after a rebase or amend, `remote_sha` is
// not an ancestor of `local_sha` (or may be absent locally);
// diffing from it would include unrelated target-branch
// commits or fail, so fall back to the default-branch base.
match git::is_ancestor(here, &pushed.remote_sha, &pushed.local_sha).await {
Ok(true) => Ok(pushed.remote_sha),
Ok(false) => git::new_branch_base(here, remote, &pushed.local_sha).await,
Err(error) => Err(error),
}
};
let changes = match base {
Ok(base) => git::range_changes(here, &base, &pushed.local_sha).await,
Expand Down
53 changes: 53 additions & 0 deletions tests/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,59 @@ async fn each_pushed_branch_is_reviewed_against_the_commit_the_remote_has() {
);
}

#[tokio::test]
async fn force_push_of_rebased_or_missing_remote_tip_falls_back_to_default_branch_base() {
let checkout = Checkout::new().await;
let uploads = Uploads::default();
let origin = serve(uploads.clone(), "SERIOUS", false).await;

// Previously pushed feature commit A1 on top of the initial base.
let old_remote_tip = checkout
.commit("orders.rs", "fn main() { old_feature() }\n")
.await;

// Target branch `main` advances with an unrelated commit M1.
checkout.git(&["checkout", "-q", &checkout.base]).await;
let main_tip = checkout.commit("other.rs", "fn unrelated() {}\n").await;
checkout
.git(&["update-ref", "refs/remotes/origin/main", &main_tip])
.await;

// Feature branch is rebased onto M1 as A1', so `old_remote_tip` is no
// longer an ancestor of `rebased_head`.
let rebased_head = checkout
.commit("orders.rs", "fn main() { rebased() }\n")
.await;

let missing_remote_tip = "f".repeat(40);
let input = format!(
"refs/heads/feature {rebased_head} refs/heads/feature {old_remote_tip}\n\
refs/heads/other {rebased_head} refs/heads/other {missing_remote_tip}\n"
);
let output = checkout
.proofline(
&origin,
&[
"hook",
"run",
"pre-push",
"origin",
"https://github.com/acme/web.git",
],
&input,
)
.await;
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let uploads = uploads.lock().unwrap();
assert_eq!(uploads.len(), 2);
for upload in uploads.iter() {
assert_eq!(upload["base_commit_sha"], main_tip);
let patch = upload["patch"].as_str().unwrap();
assert!(patch.contains("+fn main() { rebased() }"), "{patch}");
assert!(!patch.contains("unrelated()"), "{patch}");
}
}

#[tokio::test]
#[ignore = "requires official pre-commit >=3.2.0 on PATH; run this suite with --include-ignored"]
async fn the_pre_commit_framework_preserves_selection_policy_and_existing_configuration() {
Expand Down