Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(git): clearer error when default branch has no commits (#2990)
Worktrunk Bot8e9d268db836
diff --git a/src/git/error.rs b/src/git/error.rsindex b09f12ad9..cb6b430b8 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -424,6 +424,14 @@ pub enum GitError {StaleDefaultBranch {branch: String,},+ /// The default branch resolves to a worktree whose HEAD is unborn (no+ /// commits yet) — e.g. a freshly `git init`'d repo. Distinct from+ /// [`StaleDefaultBranch`](Self::StaleDefaultBranch): the cache is+ /// correct, so the cache-reset hint would be misleading; the branch+ /// simply has nothing to diff or merge against yet.+ UnbornDefaultBranch {+ branch: String,+ },// Worktree errorsNotInWorktree {@@ -610,6 +618,10 @@ impl GitError {cformat!("Default branch <bold>{branch}</> does not exist locally")}+ GitError::UnbornDefaultBranch { branch } => {+ cformat!("Default branch <bold>{branch}</> has no commits yet")+ }+GitError::NotInWorktree { action } => match action {Some(action) => format!("Cannot {action}: not in a worktree"),None => "Not in a worktree".to_string(),@@ -890,6 +902,18 @@ impl GitError {)}+ GitError::UnbornDefaultBranch { branch } => {+ let title = self.title();+ write!(+ f,+ "{}\n{}",+ error_message(&title),+ hint_message(cformat!(+ "Make an initial commit on <underline>{branch}</> first, or pass an explicit target."+ ))+ )+ }+GitError::NotInWorktree { .. } => {let title = self.title();write!(diff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex b00e5a347..18e6429dd 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -411,6 +411,9 @@ impl Repository {let branch = self.resolve_target_branch(target)?;if !self.branch(&branch).exists()? {if target.is_none() {+ if self.is_unborn_branch(&branch) {+ return Err(GitError::UnbornDefaultBranch { branch }.into());+ }return Err(GitError::StaleDefaultBranch { branch }.into());}return Err(GitError::BranchNotFound {@@ -437,6 +440,9 @@ impl Repository {let reference = self.resolve_target_branch(target)?;if !self.ref_exists(&reference)? {if target.is_none() {+ if self.is_unborn_branch(&reference) {+ return Err(GitError::UnbornDefaultBranch { branch: reference }.into());+ }return Err(GitError::StaleDefaultBranch { branch: reference }.into());}return Err(GitError::ReferenceNotFound { reference }.into());@@ -444,6 +450,22 @@ impl Repository {Ok(reference)}+ /// True when `branch` is checked out as an unborn HEAD (no commits yet)+ /// in some worktree — e.g. a freshly `git init`'d repo before its first+ /// commit. Such a branch has no `refs/heads/<branch>` ref, so the+ /// `require_target_*` existence checks fail even though the cached+ /// default branch is correct. Used to surface+ /// [`GitError::UnbornDefaultBranch`] (no cache-reset hint) instead of+ /// [`GitError::StaleDefaultBranch`] (which would wrongly suggest the+ /// cache is bad).+ fn is_unborn_branch(&self, branch: &str) -> bool {+ self.list_worktrees().is_ok_and(|worktrees| {+ worktrees+ .iter()+ .any(|wt| wt.branch.as_deref() == Some(branch) && !wt.has_commits())+ })+ }+/// Infer the default branch locally (without remote).////// Uses local heuristics when no remote is available:diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rsindex 18c64fa41..d239b5579 100644--- a/tests/integration_tests/repository.rs+++ b/tests/integration_tests/repository.rs@@ -684,6 +684,46 @@ fn test_require_target_ref_surfaces_stale_default_branch() {);}+/// A freshly `git init`'d repo whose default branch is unborn (no commits+/// yet) surfaces `UnbornDefaultBranch`, not `StaleDefaultBranch`. The cache+/// is correct — `main` simply has nothing to diff against — so the+/// cache-reset hint of `StaleDefaultBranch` would mislead. Reproduces #2989.+///+/// Both validators are checked: `require_target_ref` (rebase/squash/diff) and+/// `require_target_branch` (merge/push). The rendered message must read "has+/// no commits yet" and omit the cache-reset hint.+#[test]+fn test_require_target_surfaces_unborn_default_branch() {+ use worktrunk::git::{Diagnostic, GitError};+ // TestRepo::new() runs `git init -b main` with no commits, so HEAD is unborn.+ let repo = TestRepo::new();+ let r = Repository::at(repo.root_path().to_path_buf()).unwrap();+ r.set_config("worktrunk.default-branch", "main").unwrap();++ // Fresh Repository so the OnceCell re-reads the persisted value.+ let r2 = Repository::at(repo.root_path().to_path_buf()).unwrap();+ for err in [+ r2.require_target_ref(None).unwrap_err(),+ r2.require_target_branch(None).unwrap_err(),+ ] {+ let gerr = err.downcast_ref::<GitError>().expect("GitError");+ assert!(+ matches!(gerr, GitError::UnbornDefaultBranch { branch } if branch == "main"),+ "expected UnbornDefaultBranch, got {gerr:?}"+ );+ let rendered = gerr.render();+ assert!(+ rendered.contains("has no commits yet")+ && rendered.contains("Make an initial commit on"),+ "unexpected render: {rendered}"+ );+ assert!(+ !rendered.contains("Reset the cached value"),+ "render should omit the stale-cache hint: {rendered}"+ );+ }+}+/// `unset_config_value` propagates errors from corrupt git config/// rather than returning `Ok(false)` (the exit-code-5 "key absent" case).#[test]