Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Propagate failed Git predicates instead of treating them as missing refs (#4562)

Maximilian Roos023cb0a82d18
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 783b56044..aeab8a07c 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -757,11 +757,13 @@ fn creation_method(
// branch (#4481). When the cached default no longer resolves, return None
// and create from HEAD.
let base_branch = if create {
- resolved_base.or_else(|| {
- repo.resolve_target_branch(None)
- .ok()
- .filter(|b| repo.ref_exists(b).unwrap_or(false))
- })
+ match resolved_base {
+ Some(base) => Some(base),
+ None => match repo.resolve_target_branch(None) {
+ Ok(base) if repo.ref_exists(&base)? => Some(base),
+ _ => None,
+ },
+ }
} else {
None
};
@@ -1197,8 +1199,7 @@ fn execute_switch(
} => {
// Check if local branch exists BEFORE git worktree add (for DWIM detection)
let branch_handle = repo.branch(&branch);
- let local_branch_existed =
- !create_branch && branch_handle.exists_locally().unwrap_or(false);
+ let local_branch_existed = !create_branch && branch_handle.exists_locally()?;
// Build git worktree add command. Options come first, then
// `--` separates them from the path and any positional ref,
diff --git a/src/git/repository/branch.rs b/src/git/repository/branch.rs
index 08a3c8213..975054f5c 100644
--- a/src/git/repository/branch.rs
+++ b/src/git/repository/branch.rs
@@ -86,14 +86,7 @@ impl<'a> Branch<'a> {
/// Check if this branch exists locally.
pub fn exists_locally(&self) -> anyhow::Result<bool> {
- Ok(self
- .repo
- .run_command(&[
- "rev-parse",
- "--verify",
- &format!("refs/heads/{}", self.name),
- ])
- .is_ok())
+ self.repo.ref_exists(&format!("refs/heads/{}", self.name))
}
/// Check if this branch exists (local or remote).
diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rs
index 4c6520f59..f46fb7f3e 100644
--- a/src/git/repository/branches.rs
+++ b/src/git/repository/branches.rs
@@ -91,16 +91,15 @@ impl Repository {
/// Accepts any valid commit-ish: branch names, tags, HEAD, commit SHAs,
/// and relative refs like HEAD~2.
pub fn ref_exists(&self, reference: &str) -> anyhow::Result<bool> {
- // Use rev-parse to check if the reference resolves to a valid commit
- // The ^{commit} suffix ensures we get the commit object, not a tag
- Ok(self
- .run_command(&[
- "rev-parse",
- "--verify",
- "--end-of-options",
- &format!("{}^{{commit}}", reference),
- ])
- .is_ok())
+ // Quiet verification uses status 1 for a missing commit-ish. Other
+ // failures, including native interruption, are not evidence of absence.
+ self.run_command_check(&[
+ "rev-parse",
+ "--verify",
+ "--quiet",
+ "--end-of-options",
+ &format!("{reference}^{{commit}}"),
+ ])
}
/// Access the local-branch inventory, scanning on first call.
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index 2ab7fe6e1..9ab8fdf71 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -963,6 +963,17 @@ mod snapshot_resolve_tests {
use super::*;
use crate::testing::TestRepo;
+ #[test]
+ fn failed_ancestor_query_is_not_cached_as_false() {
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+ let head = test.git_output(&["rev-parse", "HEAD"]);
+ let missing = "1111111111111111111111111111111111111111";
+ assert!(super::super::sha_cache::is_ancestor(&repo, missing, &head).is_none());
+ assert!(repo.is_ancestor_by_sha(missing, &head).is_err());
+ assert!(super::super::sha_cache::is_ancestor(&repo, missing, &head).is_none());
+ }
+
/// Exercises the `git rev-parse` fallback when the snapshot doesn't
/// carry the ref (e.g. `HEAD`, tags, raw SHAs). The protective
/// `--verify --end-of-options` is on this call site too — keep this
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 24a439fd9..4179984a7 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -1992,10 +1992,11 @@ impl Repository {
Ok(output.stdout)
}
- /// Run a git command and return whether it succeeded (exit code 0).
+ /// Run a Git predicate: status 0 is true, 1 is false, and other statuses fail.
///
- /// This is useful for commands that use exit codes for boolean results,
- /// like `git merge-base --is-ancestor`.
+ /// Use for commands with this exit-code contract, such as
+ /// `git merge-base --is-ancestor` and `git rev-parse --verify --quiet`.
+ /// A failed query must not be treated or cached as a negative answer.
///
/// # Examples
/// ```no_run
@@ -2006,7 +2007,12 @@ impl Repository {
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn run_command_check(&self, args: &[&str]) -> anyhow::Result<bool> {
- Ok(self.run_command_output(args)?.status.success())
+ let output = self.run_command_output(args)?;
+ match output.status.code() {
+ Some(0) => Ok(true),
+ Some(1) => Ok(false),
+ _ => Err(CommandError::from_failed_output("git", args, &output).into()),
+ }
}
/// Abbreviate a commit SHA for display, honoring `core.abbrev` and
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index a60d4006f..9e86dc2bf 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -11,6 +11,77 @@ use std::fs;
use std::path::{Path, PathBuf};
use tempfile::TempDir;
+/// A failed existence check must stop creation, not pretend a ref is absent.
+#[cfg(unix)]
+#[rstest]
+fn test_switch_create_propagates_ref_query_failure(repo: TestRepo) {
+ use std::os::unix::fs::PermissionsExt;
+
+ let scratch = crate::common::test_tempdir();
+ let script = scratch.path().join("git");
+ let reached = scratch.path().join("reached");
+ let real_git = which::which("git").unwrap();
+ let mut path = vec![scratch.path().to_path_buf()];
+ path.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
+ let path = std::env::join_paths(path).unwrap();
+
+ for (reference, explicit_base) in [
+ ("main", true),
+ ("main", false),
+ ("refs/heads/new-branch", true),
+ ] {
+ fs::write(&reached, "").unwrap();
+ fs::write(
+ &script,
+ format!(
+ r#"#!/bin/sh
+if [ "$1" = rev-parse ]; then
+ for arg in "$@"; do
+ if [ "$arg" = '{reference}' ] || [ "$arg" = '{reference}^{{commit}}' ]; then
+ echo reached > {reached}
+ echo 'simulated query failure' >&2
+ exit 128
+ fi
+ done
+fi
+exec {real_git} "$@"
+"#,
+ reached = shell_escape::unix::escape(reached.to_string_lossy()),
+ real_git = shell_escape::unix::escape(real_git.to_string_lossy()),
+ ),
+ )
+ .unwrap();
+ fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
+ let mut cmd = repo.wt_command();
+ cmd.env("PATH", &path)
+ .args(["switch", "--create", "new-branch", "--yes"]);
+ if explicit_base {
+ cmd.args(["--base", "main"]);
+ }
+ let output = cmd.output().unwrap();
+ assert_eq!(
+ fs::read_to_string(&reached).unwrap(),
+ "reached\n",
+ "{reference}: {output:?}"
+ );
+ assert!(!output.status.success(), "{reference}: {output:?}");
+ assert!(
+ String::from_utf8_lossy(&output.stderr).contains("simulated query failure"),
+ "{reference}: {output:?}"
+ );
+ let probe = repo
+ .git_command()
+ .args(["show-ref", "--verify", "--quiet", "refs/heads/new-branch"])
+ .run()
+ .unwrap();
+ assert_eq!(
+ probe.status.code(),
+ Some(1),
+ "no branch may be created after a failed query"
+ );
+ }
+}
+
// Snapshot helpers
fn snapshot_switch(test_name: &str, repo: &TestRepo, args: &[&str]) {
diff --git a/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap b/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap
index 03c61a769..5fa6b3741 100644
--- a/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap
@@ -67,9 +67,10 @@ exit_code: 0
▲ Failed to batch-fetch commit details: fatal: bad object 0000000000000000000000000000000000000001
○ Showing 5 worktrees, 3 ahead
-▲ 6 tasks failed:
+▲ 7 tasks failed:
  (detached): ahead/behind counts (fatal: Not a valid commit name 0000000000000000000000000000000000000001)
  (detached): trees-match check (fatal: Needed a single revision)
+  (detached): ancestor check (fatal: Not a valid commit name 0000000000000000000000000000000000000001)
  (detached): branch diff (fatal: Not a valid commit name 0000000000000000000000000000000000000001)
  (detached): working-tree diff (fatal: bad object HEAD)
  (detached): merge-conflict check (fatal: bad object HEAD)