Skip to content

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

feat: graceful degradation when default branch unavailable (#531)

Maximilian Roos0c8f091f8f27
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 65e2d15a5..faf80ea9b 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -88,7 +88,7 @@ pub fn build_hook_context(
map.insert("worktree".into(), worktree);
// Default branch and main worktree path
- if let Ok(default_branch) = ctx.repo.default_branch() {
+ if let Some(default_branch) = ctx.repo.default_branch() {
map.insert("default_branch".into(), default_branch.clone());
// main_worktree_path: path to the worktree on the default branch
diff --git a/src/commands/config.rs b/src/commands/config.rs
index 99d5efe0e..cf2c47154 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -969,7 +969,9 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>
match key {
"default-branch" => {
- let branch_name = repo.default_branch()?;
+ let branch_name = repo.default_branch().ok_or_else(|| {
+ anyhow::anyhow!("Cannot determine default branch. Run 'wt config state default-branch set <branch>' to configure.")
+ })?;
crate::output::stdout(branch_name)?;
}
"previous-branch" => match repo.get_switch_previous() {
@@ -1037,6 +1039,12 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> any
match key {
"default-branch" => {
+ // Warn if the branch doesn't exist locally
+ if !repo.local_branch_exists(&value)? {
+ crate::output::print(warning_message(cformat!(
+ "Branch <bold>{value}</> does not exist locally"
+ )))?;
+ }
repo.set_default_branch(&value)?;
crate::output::print(success_message(cformat!(
"Set default branch to <bold>{value}</>"
@@ -1309,7 +1317,7 @@ pub fn handle_state_show(format: crate::cli::OutputFormat) -> anyhow::Result<()>
/// Output state as JSON
fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {
// Get default branch
- let default_branch = repo.default_branch().ok();
+ let default_branch = repo.default_branch();
// Get previous branch
let previous_branch = repo.get_switch_previous();
@@ -1414,8 +1422,8 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {
// Show default branch cache
writeln!(out, "{}", format_heading("DEFAULT BRANCH", None))?;
match repo.default_branch() {
- Ok(branch) => writeln!(out, "{}", format_with_gutter(&branch, None))?,
- Err(_) => writeln!(out, "{}", format_with_gutter("(not cached)", None))?,
+ Some(branch) => writeln!(out, "{}", format_with_gutter(&branch, None))?,
+ None => writeln!(out, "{}", format_with_gutter("(not available)", None))?,
}
writeln!(out)?;
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 1b60d8a0a..07a92dd8a 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -205,7 +205,7 @@ pub fn run_hook(
require_hooks(user_config, project_config, hook_type)?;
// Pre-commit hook can optionally use target branch context
// Custom vars take precedence (added last)
- let target_branch = repo.default_branch().ok();
+ let target_branch = repo.default_branch();
let mut extra_vars: Vec<(&str, &str)> = target_branch
.as_deref()
.into_iter()
@@ -603,7 +603,7 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hook
use super::command_executor::build_hook_context;
// Build extra vars based on hook type (same logic as run_hook approval)
- let default_branch = ctx.repo.default_branch().ok();
+ let default_branch = ctx.repo.default_branch();
let extra_vars: Vec<(&str, &str)> = match hook_type {
HookType::PreCommit => {
// Pre-commit uses default branch as target (for comparison context)
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index 813fa18af..f11395a03 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -716,10 +716,7 @@ pub fn collect(
// These operations don't depend on each other, only on worktree list.
// Running them in parallel reduces pre-skeleton time (e.g., ~46ms to ~28ms).
let (default_branch, branches_without_worktrees, remote_branches) = join!(
- || {
- repo.default_branch()
- .context("Failed to determine default branch")
- },
+ || repo.default_branch(),
|| {
if show_branches {
get_branches_without_worktrees(repo, &worktrees)
@@ -735,25 +732,25 @@ pub fn collect(
}
}
);
- // TODO: Make default_branch optional so wt list can gracefully degrade when detection fails.
- // Currently, ambiguous repos (multiple non-standard branches, no remote) fail entirely.
- // With symbolic-ref HEAD heuristic added, this is less common but still possible.
- // Required changes:
- // 1. Make default_branch Option<String> here
- // 2. find_home() already handles empty default_branch (falls back to first)
- // 3. Make main_worktree optional or use first worktree when default_branch is None
- // 4. Update TaskContext.require_default_branch() callers to handle None gracefully
- // (skip ahead/behind, integration status, etc. instead of failing)
- // 5. Show warning when default_branch couldn't be determined
- let default_branch = default_branch?;
+ // Show warning if user configured a default branch that doesn't exist locally
+ if let Some(configured) = repo.invalid_default_branch_config() {
+ let msg =
+ cformat!("Configured default branch <bold>{configured}</> does not exist locally");
+ crate::output::print(warning_message(msg))?;
+ let hint = cformat!("Run <bright-black>wt config state default-branch clear</> to reset");
+ crate::output::print(worktrunk::styling::hint_message(hint))?;
+ }
+
let branches_without_worktrees = branches_without_worktrees?;
let remote_branches = remote_branches?;
// Main worktree is the worktree on the default branch (if exists), else first non-prunable worktree.
// find_home returns None if all worktrees are prunable or the list is empty.
- let main_worktree = WorktreeInfo::find_home(&worktrees, &default_branch)
- .cloned()
- .ok_or_else(|| anyhow::anyhow!("No worktrees found"))?;
+ // TODO: show ellipsis or indicator when default_branch is None and columns are empty
+ let main_worktree =
+ WorktreeInfo::find_home(&worktrees, default_branch.as_deref().unwrap_or(""))
+ .cloned()
+ .ok_or_else(|| anyhow::anyhow!("No worktrees found"))?;
// Defer previous_branch lookup until after skeleton - set is_previous later
// (skeleton shows placeholder gutter, actual symbols appear when data loads)
@@ -953,8 +950,8 @@ pub fn collect(
// Effective target for integration checks: upstream if ahead of local, else local.
// This handles the case where a branch was merged remotely but user hasn't pulled yet.
// Deferred until after skeleton to avoid blocking initial render.
- // Uses cached integration_target() which computes the same value from default_branch().
- let integration_target = repo.integration_target()?;
+ // Uses cached integration_target() which returns None if default_branch unknown.
+ let integration_target = repo.integration_target();
// Batch-fetch ahead/behind counts to identify branches that are far behind.
// This allows skipping expensive merge-base operations for diverged branches, dramatically
@@ -962,7 +959,8 @@ pub fn collect(
//
// Uses `git for-each-ref --format='%(ahead-behind:...)'` (git 2.36+) which gets all
// counts in a single command. On older git versions, returns empty and all tasks run.
- if skip_expensive_for_stale {
+ // Skip if default_branch is unknown.
+ if skip_expensive_for_stale && let Some(ref db) = default_branch {
// Branches more than 50 commits behind skip expensive merge-base operations.
// 50 is low enough to catch truly stale branches while keeping info for
// recently-diverged ones. The "behind" count is the primary expense driver -
@@ -972,7 +970,7 @@ pub fn collect(
.and_then(|s| s.parse().ok())
.unwrap_or(50);
// batch_ahead_behind populates the Repository cache with all counts
- let ahead_behind = repo.batch_ahead_behind(&default_branch);
+ let ahead_behind = repo.batch_ahead_behind(db);
// Filter to stale branches (behind > threshold). The set indicates which
// branches should skip expensive tasks; counts come from the cache.
options.stale_branches = ahead_behind
@@ -1107,7 +1105,9 @@ pub fn collect(
|item_idx, item, ctx| {
// Compute/recompute status symbols as data arrives (both modes).
// This is idempotent and updates status as new data (like upstream) arrives.
- ctx.apply_to(item, integration_target.as_str());
+ if let Some(ref target) = integration_target {
+ ctx.apply_to(item, target.as_str());
+ }
// Progressive mode only: update UI
if let Some(ref mut table) = progressive_table {
@@ -1196,7 +1196,9 @@ pub fn collect(
{
// Use default context - no tasks ran, so no conflict/status info
let ctx = StatusContext::default();
- ctx.apply_to(item, integration_target.as_str());
+ if let Some(ref target) = integration_target {
+ ctx.apply_to(item, target.as_str());
+ }
}
}
@@ -1417,7 +1419,8 @@ pub fn populate_item(
};
// Get integration target for status symbol computation (cached in repo)
- let target = repo.integration_target()?;
+ // None if default branch cannot be determined - status symbols will be skipped
+ let target = repo.integration_target();
// Create channel for task results
let (tx, rx) = chan::unbounded::<Result<TaskResult, TaskError>>();
@@ -1472,7 +1475,9 @@ pub fn populate_item(
&mut errors,
&expected_results,
|_item_idx, item, ctx| {
- ctx.apply_to(item, &target);
+ if let Some(ref t) = target {
+ ctx.apply_to(item, t);
+ }
},
);
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rs
index 56f706d77..38a44a8e7 100644
--- a/src/commands/list/collect_progressive_impl.rs
+++ b/src/commands/list/collect_progressive_impl.rs
@@ -103,17 +103,17 @@ impl TaskContext {
/// Get the default branch (cached in Repository).
///
/// Used for informational stats (ahead/behind, branch diff).
- fn default_branch(&self, kind: TaskKind) -> Result<String, TaskError> {
- self.repo.default_branch().map_err(|e| self.error(kind, e))
+ /// Returns None if default branch cannot be determined.
+ fn default_branch(&self) -> Option<String> {
+ self.repo.default_branch()
}
/// Get the integration target (cached in Repository).
///
/// Used for integration checks (status symbols, safe deletion).
- fn integration_target(&self, kind: TaskKind) -> Result<String, TaskError> {
- self.repo
- .integration_target()
- .map_err(|e| self.error(kind, e))
+ /// Returns None if default branch cannot be determined.
+ fn integration_target(&self) -> Option<String> {
+ self.repo.integration_target()
}
}
@@ -400,7 +400,13 @@ impl Task for AheadBehindTask {
const KIND: TaskKind = TaskKind::AheadBehind;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx.default_branch(Self::KIND)?;
+ // When default_branch is None, return zero counts (cells show empty)
+ let Some(base) = ctx.default_branch() else {
+ return Ok(TaskResult::AheadBehind {
+ item_idx: ctx.item_idx,
+ counts: AheadBehind::default(),
+ });
+ };
let repo = &ctx.repo;
// Check cache first (populated by batch_ahead_behind if it ran).
@@ -434,7 +440,13 @@ impl Task for CommittedTreesMatchTask {
const KIND: TaskKind = TaskKind::CommittedTreesMatch;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx.integration_target(Self::KIND)?;
+ // When integration_target is None, return false (conservative: don't mark as integrated)
+ let Some(base) = ctx.integration_target() else {
+ return Ok(TaskResult::CommittedTreesMatch {
+ item_idx: ctx.item_idx,
+ committed_trees_match: false,
+ });
+ };
let repo = &ctx.repo;
// Use the item's commit instead of HEAD, since for branches without
// worktrees, HEAD is the main worktree's HEAD.
@@ -472,7 +484,13 @@ impl Task for HasFileChangesTask {
has_file_changes: true,
});
};
- let target = ctx.integration_target(Self::KIND)?;
+ // When integration_target is None, return true (conservative: assume has changes)
+ let Some(target) = ctx.integration_target() else {
+ return Ok(TaskResult::HasFileChanges {
+ item_idx: ctx.item_idx,
+ has_file_changes: true,
+ });
+ };
let repo = &ctx.repo;
let has_file_changes = repo
.has_added_changes(branch, &target)
@@ -509,7 +527,13 @@ impl Task for WouldMergeAddTask {
would_merge_add: true,
});
};
- let base = ctx.integration_target(Self::KIND)?;
+ // When integration_target is None, return true (conservative: assume would add)
+ let Some(base) = ctx.integration_target() else {
+ return Ok(TaskResult::WouldMergeAdd {
+ item_idx: ctx.item_idx,
+ would_merge_add: true,
+ });
+ };
let repo = &ctx.repo;
let would_merge_add = repo
.would_merge_add_to_target(branch, &base)
@@ -535,7 +559,13 @@ impl Task for IsAncestorTask {
const KIND: TaskKind = TaskKind::IsAncestor;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx.integration_target(Self::KIND)?;
+ // When integration_target is None, return false (conservative: don't mark as ancestor)
+ let Some(base) = ctx.integration_target() else {
+ return Ok(TaskResult::IsAncestor {
+ item_idx: ctx.item_idx,
+ is_ancestor: false,
+ });
+ };
let repo = &ctx.repo;
let is_ancestor = repo
.is_ancestor(&ctx.branch_ref.commit_sha, &base)
@@ -555,7 +585,13 @@ impl Task for BranchDiffTask {
const KIND: TaskKind = TaskKind::BranchDiff;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx.default_branch(Self::KIND)?;
+ // When default_branch is None, return empty diff (cells show empty)
+ let Some(base) = ctx.default_branch() else {
+ return Ok(TaskResult::BranchDiff {
+ item_idx: ctx.item_idx,
+ branch_diff: BranchDiffTotals::default(),
+ });
+ };
let repo = &ctx.repo;
let diff = repo
.branch_diff_stats(&base, &ctx.branch_ref.commit_sha)
@@ -597,7 +633,7 @@ impl Task for WorkingTreeDiffTask {
};
// Use default_branch (local default branch) for informational display
- let default_branch = ctx.default_branch(Self::KIND).ok();
+ let default_branch = ctx.default_branch();
let working_tree_diff_with_main = wt
.working_tree_diff_with_base(default_branch.as_deref(), is_dirty)
.map_err(|e| ctx.error(Self::KIND, e))?;
@@ -622,7 +658,13 @@ impl Task for MergeTreeConflictsTask {
const KIND: TaskKind = TaskKind::MergeTreeConflicts;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx.default_branch(Self::KIND)?;
+ // When default_branch is None, return false (no conflicts can be detected)
+ let Some(base) = ctx.default_branch() else {
+ return Ok(TaskResult::MergeTreeConflicts {
+ item_idx: ctx.item_idx,
+ has_merge_tree_conflicts: false,
+ });
+ };
let repo = &ctx.repo;
let has_merge_tree_conflicts = repo
.has_merge_conflicts(&base, &ctx.branch_ref.commit_sha)
@@ -645,7 +687,13 @@ impl Task for WorkingTreeConflictsTask {
const KIND: TaskKind = TaskKind::WorkingTreeConflicts;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx.default_branch(Self::KIND)?;
+ // When default_branch is None, return None (skip conflict check)
+ let Some(base) = ctx.default_branch() else {
+ return Ok(TaskResult::WorkingTreeConflicts {
+ item_idx: ctx.item_idx,
+ has_working_tree_conflicts: None,
+ });
+ };
// This task is only spawned for worktree items, so worktree path is always present.
let wt = ctx
.branch_ref
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 02b2ad943..49f4c58f9 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -173,8 +173,7 @@ impl RepositoryCliExt for Repository {
// Resolve target branch for integration reason display
// Skip if removing the default branch itself (avoids tautological "main (ancestor of main)")
- // Use .ok() to treat errors as unknown - safer than empty string for integration checks
- let default_branch = self.default_branch().ok();
+ let default_branch = self.default_branch();
let target_branch = match (&default_branch, &branch_name) {
(Some(db), Some(bn)) if db == bn => None,
_ => default_branch,
diff --git a/src/commands/select.rs b/src/commands/select.rs
index 8444c9533..98c65b7df 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -520,7 +520,7 @@ impl WorktreeSkimItem {
let Ok(repo) = Repository::current() else {
return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of main\n");
};
- let Ok(default_branch) = repo.default_branch() else {
+ let Some(default_branch) = repo.default_branch() else {
return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of main\n");
};
if self.item.counts().ahead == 0 {
@@ -618,7 +618,7 @@ impl WorktreeSkimItem {
));
return output;
};
- let Ok(default_branch) = repo.default_branch() else {
+ let Some(default_branch) = repo.default_branch() else {
output.push_str(&cformat!(
"{INFO_SYMBOL} <bold>{branch}</> has no commits\n"
));
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index 19abf107d..b42d480cf 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -266,8 +266,8 @@ fn get_git_status_segments(
// Get default branch for comparisons
let default_branch = match repo.default_branch() {
- Ok(b) => b,
- Err(_) => {
+ Some(b) => b,
+ None => {
// Can't determine default branch - just show current branch
return Ok(vec![StatuslineSegment::from_column(
wt.branch.as_deref().unwrap_or("HEAD").to_string(),
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 394ab788c..419a7ed1d 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -435,7 +435,11 @@ pub fn step_copy_ignored(
})?;
(path, branch.to_string())
}
- None => (repo.worktree_base()?, repo.default_branch()?.to_string()),
+ None => (
+ repo.worktree_base()?,
+ repo.default_branch()
+ .ok_or_else(|| anyhow::anyhow!("Cannot determine default branch"))?,
+ ),
};
let dest_path = match to {
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index e441a6294..f9d3a5d48 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -585,6 +585,20 @@ pub fn handle_switch(
let worktree_path_str = worktree_path.to_string_lossy();
let mut args = vec!["worktree", "add", worktree_path_str.as_ref()];
+ // Check for invalid configured default branch when creating without explicit --base.
+ // Show warning if user's configured default branch doesn't exist locally.
+ if create
+ && resolved_base.is_none()
+ && let Some(configured) = repo.invalid_default_branch_config()
+ {
+ crate::output::print(warning_message(cformat!(
+ "Configured default branch <bold>{configured}</> does not exist locally"
+ )))?;
+ crate::output::print(hint_message(cformat!(
+ "Run <bright-black>wt config state default-branch clear</> to reset"
+ )))?;
+ }
+
// Use the resolved base, or default to default branch if creating without a base.
// For bare repos with no branches yet (bootstrap case), allow None to create orphan branch.
let base_for_creation = if create {
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index 217d9d2dc..6e664e6dc 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -136,26 +136,63 @@ impl Repository {
///
/// Detection results are cached to `worktrunk.default-branch` for future calls.
/// Result is cached in the shared repo cache (shared across all worktrees).
- pub fn default_branch(&self) -> anyhow::Result<String> {
+ ///
+ /// Returns `None` if the default branch cannot be determined.
+ pub fn default_branch(&self) -> Option<String> {
self.cache
.default_branch
- .get_or_try_init(|| {
+ .get_or_init(|| {
// Fast path: check worktrunk's persistent cache (git config)
- if let Ok(branch) =
- self.run_command(&["config", "--get", "worktrunk.default-branch"])
- {
- let branch = branch.trim();
- if !branch.is_empty() {
- return Ok(branch.to_string());
+ let configured = self
+ .run_command(&["config", "--get", "worktrunk.default-branch"])
+ .ok()
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty());
+
+ // If configured, validate it exists locally
+ if let Some(ref branch) = configured {
+ if self.local_branch_exists(branch).unwrap_or(false) {
+ return Some(branch.clone());
}
+ // Configured branch doesn't exist - return None (don't fall back)
+ log::debug!(
+ "Configured default branch '{}' doesn't exist locally",
+ branch
+ );
+ return None;
+ }
+
+ // Not configured - detect and persist to git config
+ if let Ok(branch) = self.detect_default_branch() {
+ let _ = self.run_command(&["config", "worktrunk.default-branch", &branch]);
+ return Some(branch);
}
- // Detect and persist to git config for future processes
- let branch = self.detect_default_branch()?;
- let _ = self.run_command(&["config", "worktrunk.default-branch", &branch]);
- Ok(branch)
+ None
})
- .cloned()
+ .clone()
+ }
+
+ /// Check if user configured an invalid default branch.
+ ///
+ /// Returns `Some(branch_name)` if user set `worktrunk.default-branch` to a branch
+ /// that doesn't exist locally. Returns `None` if:
+ /// - No branch is configured (detection will be used)
+ /// - Configured branch exists locally
+ ///
+ /// Used to show warnings when the configured branch is invalid.
+ pub fn invalid_default_branch_config(&self) -> Option<String> {
+ let configured = self
+ .run_command(&["config", "--get", "worktrunk.default-branch"])
+ .ok()
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())?;
+
+ if self.local_branch_exists(&configured).unwrap_or(false) {
+ None
+ } else {
+ Some(configured)
+ }
}
/// Detect the default branch without using worktrunk's cache.
@@ -193,7 +230,15 @@ impl Repository {
/// Otherwise, queries the default branch.
/// This is a common pattern used throughout commands that accept an optional --target flag.
pub fn resolve_target_branch(&self, target: Option<&str>) -> anyhow::Result<String> {
- target.map_or_else(|| self.default_branch(), |b| self.resolve_worktree_name(b))
+ match target {
+ Some(b) => self.resolve_worktree_name(b),
+ None => self.default_branch().ok_or_else(|| {
+ GitError::Other {
+ message: "Cannot determine default branch. Specify target explicitly or run 'wt config state default-branch set <branch>'.".into(),
+ }
+ .into()
+ }),
+ }
}
/// Infer the default branch locally (without remote).
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index c63b566f2..b534f23c4 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -178,15 +178,17 @@ impl Repository {
/// This is the effective target for integration checks (status symbols, safe deletion).
/// May be upstream (e.g., "origin/main") if it's ahead of local, catching remotely-merged branches.
///
+ /// Returns None if the default branch cannot be determined.
+ ///
/// Result is cached in the shared repo cache (shared across all worktrees).
- pub fn integration_target(&self) -> anyhow::Result<String> {
+ pub fn integration_target(&self) -> Option<String> {
self.cache
.integration_target
- .get_or_try_init(|| {
+ .get_or_init(|| {
let default_branch = self.default_branch()?;
- Ok(self.effective_integration_target(&default_branch))
+ Some(self.effective_integration_target(&default_branch))
})
- .cloned()
+ .clone()
}
/// Parse a tree ref to get its SHA.
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index ecb2c8443..b3c18aca8 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -64,9 +64,9 @@ pub(super) struct RepoCache {
/// Whether this is a bare repository
pub(super) is_bare: OnceCell<bool>,
/// Default branch (main, master, etc.)
- pub(super) default_branch: OnceCell<String>,
+ pub(super) default_branch: OnceCell<Option<String>>,
/// Effective integration target (local default branch or upstream if ahead)
- pub(super) integration_target: OnceCell<String>,
+ pub(super) integration_target: OnceCell<Option<String>>,
/// Primary remote name (None if no remotes configured)
pub(super) primary_remote: OnceCell<Option<String>>,
/// Primary remote URL (None if no remotes configured or no URL)
@@ -145,7 +145,9 @@ fn base_path() -> &'static PathBuf {
/// let wt = repo.current_worktree();
///
/// // Repo-wide operations
-/// let default = repo.default_branch()?;
+/// if let Some(default) = repo.default_branch() {
+/// println!("Default branch: {}", default);
+/// }
///
/// // Worktree-specific operations
/// let branch = wt.branch()?;
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index 9e4a408f0..064b3ecd8 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -120,7 +120,12 @@ impl Repository {
.into()
})
}
- "^" => self.default_branch(),
+ "^" => self.default_branch().ok_or_else(|| {
+ GitError::Other {
+ message: "Cannot determine default branch. Specify target explicitly or run 'wt config state default-branch set <branch>'.".into(),
+ }
+ .into()
+ }),
_ => Ok(name.to_string()),
}
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 3d8666f22..308c15c25 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -506,7 +506,7 @@ fn handle_branch_only_output(
// Get default branch for integration check and reason display
// Falls back to HEAD if default branch can't be determined
- let default_branch = repo.default_branch().ok();
+ let default_branch = repo.default_branch();
let check_target = default_branch.as_deref().unwrap_or("HEAD");
let result = delete_branch_if_safe(&repo, branch_name, check_target, deletion_mode.is_force());
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index b36230e5a..b69b370ad 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -78,13 +78,40 @@ fn test_state_get_default_branch_no_remote(repo: TestRepo) {
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "main");
}
+#[rstest]
+fn test_state_get_default_branch_fails_when_undetermined(repo: TestRepo) {
+ // Rename main to something non-standard so default branch can't be determined
+ repo.git_command()
+ .args(["branch", "-m", "main", "xyz"])
+ .status()
+ .unwrap();
+ repo.git_command().args(["branch", "abc"]).status().unwrap();
+ repo.git_command().args(["branch", "def"]).status().unwrap();
+
+ // Now we have: xyz, abc, def - no common names, no init.defaultBranch
+ // wt config state default-branch get should fail with an error
+ let output = wt_state_cmd(&repo, "default-branch", "get", &[])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Cannot determine default branch"),
+ "Expected error message about cannot determine default branch, got: {}",
+ stderr
+ );
+}
+
#[rstest]
fn test_state_set_default_branch(repo: TestRepo) {
let output = wt_state_cmd(&repo, "default-branch", "set", &["develop"])
.output()
.unwrap();
assert!(output.status.success());
- assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"✓ Set default branch to develop");
+ assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"
+ ▲ Branch develop does not exist locally
+ ✓ Set default branch to develop
+ ");
// Verify it was set in worktrunk's cache
let output = repo
diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rs
index 1fcbfe0b4..b8eadf1b1 100644
--- a/tests/integration_tests/default_branch.rs
+++ b/tests/integration_tests/default_branch.rs
@@ -71,7 +71,7 @@ fn test_get_default_branch_no_remote(repo: TestRepo) {
// No remote configured, should infer from local branches
// Since there's only one local branch, it should return that
let result = Repository::at(repo.root_path()).unwrap().default_branch();
- assert!(result.is_ok());
+ assert!(result.is_some());
// The inferred branch should match the current branch
let inferred_branch = result.unwrap();
@@ -193,6 +193,57 @@ fn test_default_branch_no_remote_uses_init_config(repo: TestRepo) {
assert_eq!(branch, "primary");
}
+#[rstest]
+fn test_configured_default_branch_does_not_exist_returns_none(repo: TestRepo) {
+ // Configure a non-existent branch
+ repo.git_command()
+ .args(["config", "worktrunk.default-branch", "nonexistent-branch"])
+ .status()
+ .unwrap();
+
+ // Should return None when configured branch doesn't exist locally
+ let result = Repository::at(repo.root_path()).unwrap().default_branch();
+ assert!(
+ result.is_none(),
+ "Expected None when configured branch doesn't exist, got: {:?}",
+ result
+ );
+}
+
+#[rstest]
+fn test_invalid_default_branch_config_returns_configured_value(repo: TestRepo) {
+ // Configure a non-existent branch
+ repo.git_command()
+ .args(["config", "worktrunk.default-branch", "nonexistent-branch"])
+ .status()
+ .unwrap();
+
+ // Should report the invalid configuration
+ let invalid = Repository::at(repo.root_path())
+ .unwrap()
+ .invalid_default_branch_config();
+ assert_eq!(invalid, Some("nonexistent-branch".to_string()));
+}
+
+#[rstest]
+fn test_invalid_default_branch_config_returns_none_when_valid(repo: TestRepo) {
+ // Configure the existing "main" branch
+ repo.git_command()
+ .args(["config", "worktrunk.default-branch", "main"])
+ .status()
+ .unwrap();
+
+ // Should return None since the configured branch exists
+ let invalid = Repository::at(repo.root_path())
+ .unwrap()
+ .invalid_default_branch_config();
+ assert!(
+ invalid.is_none(),
+ "Expected None when configured branch exists, got: {:?}",
+ invalid
+ );
+}
+
#[rstest]
fn test_get_default_branch_no_remote_fails_when_no_match(repo: TestRepo) {
// Rename main to something non-standard
@@ -206,13 +257,36 @@ fn test_get_default_branch_no_remote_fails_when_no_match(repo: TestRepo) {
// Now we have: xyz, abc, def - no common names, no init.defaultBranch
// In normal repos (not bare), symbolic-ref HEAD isn't used because HEAD
// points to the current branch, not the default branch.
- // Should fail with an error
+ // Should return None when default branch cannot be determined
let result = Repository::at(repo.root_path()).unwrap().default_branch();
- assert!(result.is_err());
- let err = result.unwrap_err().to_string();
assert!(
- err.contains("Could not infer default branch"),
- "Expected error about inferring default branch, got: {}",
- err
+ result.is_none(),
+ "Expected None when default branch cannot be determined, got: {:?}",
+ result
+ );
+}
+
+#[rstest]
+fn test_resolve_caret_fails_when_default_branch_unavailable(repo: TestRepo) {
+ // Rename main to something non-standard so default branch can't be determined
+ repo.git_command()
+ .args(["branch", "-m", "main", "xyz"])
+ .status()
+ .unwrap();
+ repo.git_command().args(["branch", "abc"]).status().unwrap();
+ repo.git_command().args(["branch", "def"]).status().unwrap();
+
+ // Now resolving "^" should fail with an error
+ let git_repo = Repository::at(repo.root_path()).unwrap();
+ let result = git_repo.resolve_worktree_name("^");
+ assert!(
+ result.is_err(),
+ "Expected error when resolving ^ without default branch"
+ );
+ let err_msg = result.unwrap_err().to_string();
+ assert!(
+ err_msg.contains("Cannot determine default branch"),
+ "Error should mention cannot determine default branch, got: {}",
+ err_msg
);
}
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index aa22d27b0..6467bdacd 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -2402,3 +2402,35 @@ fn test_list_skips_expensive_for_stale_branches_only(repo: TestRepo) {
cmd
});
}
+
+/// Tests that wt list works correctly when the configured default branch doesn't exist.
+///
+/// When a user sets `wt config state default-branch set develop` but the `develop`
+/// branch doesn't exist locally, `wt list` should show a warning and degrade gracefully
+/// (empty cells for columns needing default branch) rather than failing with git errors.
+#[rstest]
+fn test_list_with_nonexistent_default_branch(repo: TestRepo) {
+ // Set default branch to a non-existent branch
+ repo.run_git(&["config", "worktrunk.default-branch", "nonexistent"]);
+
+ // wt list should show a warning and degrade gracefully (empty columns for
+ // main-related data) when configured default branch doesn't exist locally
+ assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
+}
+
+/// Tests that wt list --full works correctly when the configured default branch doesn't exist.
+///
+/// The --full flag enables expensive tasks like BranchDiff and WorkingTreeConflicts.
+/// These should also degrade gracefully when default_branch is None.
+#[rstest]
+fn test_list_full_with_nonexistent_default_branch(repo: TestRepo) {
+ // Set default branch to a non-existent branch
+ repo.run_git(&["config", "worktrunk.default-branch", "nonexistent"]);
+
+ // wt list --full should also work, with expensive tasks returning defaults
+ assert_cmd_snapshot!({
+ let mut cmd = list_snapshots::command(&repo, repo.root_path());
+ cmd.arg("--full");
+ cmd
+ });
+}
diff --git a/tests/snapshots/integration__integration_tests__list__list_full_with_nonexistent_default_branch.snap b/tests/snapshots/integration__integration_tests__list__list_full_with_nonexistent_default_branch.snap
new file mode 100644
index 000000000..9dac7db81
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__list_full_with_nonexistent_default_branch.snap
@@ -0,0 +1,40 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--full"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ main…± Path Remote⇅ CI Commit Age Message
+@ main ⋯ . a1e809f5 1d Initial commit
+
+○ Showing 1 worktree
+
+----- stderr -----
+▲ Configured default branch nonexistent does not exist locally
+↳ Run wt config state default-branch clear to reset
diff --git a/tests/snapshots/integration__integration_tests__list__list_with_nonexistent_default_branch.snap b/tests/snapshots/integration__integration_tests__list__list_with_nonexistent_default_branch.snap
new file mode 100644
index 000000000..1d9953a60
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__list_with_nonexistent_default_branch.snap
@@ -0,0 +1,39 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+@ main ⋯ . a1e809f5 1d Initial commit
+
+○ Showing 1 worktree
+
+----- stderr -----
+▲ Configured default branch nonexistent does not exist locally
+↳ Run wt config state default-branch clear to reset