Skip to content

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

refactor: flatten nesting and make default-branch prune guard explicit (#1492)

Maximilian Roos4992a2018ad4
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 285606bc4..44d0eb206 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -131,13 +131,7 @@ impl RepositoryCliExt for Repository {
None => {
// No worktree found - check if the branch exists locally
let branch_handle = self.branch(branch);
- if branch_handle.exists_locally()? {
- Resolved::BranchOnly {
- branch: branch.to_string(),
- pruned: false,
- }
- } else {
- // Check if branch exists on a remote
+ if !branch_handle.exists_locally()? {
let remotes = branch_handle.remotes()?;
if !remotes.is_empty() {
return Err(GitError::RemoteOnlyBranch {
@@ -152,6 +146,10 @@ impl RepositoryCliExt for Repository {
}
.into());
}
+ Resolved::BranchOnly {
+ branch: branch.to_string(),
+ pruned: false,
+ }
}
}
}
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 402fad19b..65469ab79 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -1422,11 +1422,9 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->
let mut removed: Vec<Candidate> = Vec::new(); // non-dry-run tracks removals
let mut deferred_current: Option<Candidate> = None; // current worktree removed last
let mut skipped_young: Vec<String> = Vec::new();
- // Track branches seen via worktree entries so we don't double-count.
- // Pre-seed with the default branch to prevent it from being pruned
- // (it's trivially "integrated" into itself).
- let mut seen_branches: std::collections::HashSet<String> =
- default_branch.iter().cloned().collect();
+ // Track branches seen via worktree entries so we don't double-count
+ // in the orphan branch scan below.
+ let mut seen_branches: std::collections::HashSet<String> = std::collections::HashSet::new();
/// Try to remove a candidate immediately. Returns Ok(true) if removed,
/// Ok(false) if skipped (preparation error), Err on execution error.
@@ -1601,6 +1599,11 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->
if seen_branches.contains(&branch) {
continue;
}
+ // Never prune the default branch — it's trivially "integrated" into
+ // itself, which would cause a tautological deletion.
+ if default_branch.as_deref() == Some(branch.as_str()) {
+ continue;
+ }
let (effective_target, reason) = repo.integration_reason(&branch, &integration_target)?;
if let Some(reason) = reason {
// Apply min-age guard: check reflog creation timestamp
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index 1f86b40b3..28e87f9fd 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -1,6 +1,8 @@
//! Integration tests for `wt step prune`
-use crate::common::{TestRepo, make_snapshot_cmd, repo};
+use crate::common::{
+ BareRepoTest, TestRepo, make_snapshot_cmd, repo, setup_temp_snapshot_settings,
+};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
@@ -494,3 +496,47 @@ fn test_prune_stale_plus_young(mut repo: TestRepo) {
None
));
}
+
+/// Default branch without a worktree should not be pruned despite being
+/// trivially "integrated" into itself (tautological SameCommit).
+#[test]
+fn test_prune_skips_default_branch_orphan() {
+ use crate::common::TestRepoBase;
+
+ let test = BareRepoTest::new();
+
+ // Create main worktree with a commit, then remove it so main becomes orphan
+ let main_wt = test.create_worktree("main", "main");
+ test.commit_in(&main_wt, "initial commit");
+ std::fs::remove_dir_all(&main_wt).unwrap();
+ test.git_command(test.bare_repo_path())
+ .args(["worktree", "prune"])
+ .output()
+ .unwrap();
+
+ // Create a feature branch (integrated, at same commit as main)
+ let feature_wt = test.create_worktree("feature", "feature");
+
+ let settings = setup_temp_snapshot_settings(test.temp_path());
+ settings.bind(|| {
+ let mut cmd = test.wt_command();
+ cmd.args(["step", "prune", "--yes"])
+ .current_dir(&feature_wt)
+ // Far-future epoch: branches appear old enough to pass min-age guard
+ .env("WORKTRUNK_TEST_EPOCH", "1893456000");
+
+ assert_cmd_snapshot!("prune_skips_default_branch_orphan", cmd);
+ });
+
+ // Verify main branch still exists
+ let output = test
+ .git_command(test.bare_repo_path())
+ .args(["branch", "--list", "main"])
+ .output()
+ .unwrap();
+ let branches = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ branches.contains("main"),
+ "Default branch 'main' should not have been pruned"
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_skips_default_branch_orphan.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_skips_default_branch_orphan.snap
new file mode 100644
index 000000000..dae3008c0
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_skips_default_branch_orphan.snap
@@ -0,0 +1,43 @@
+---
+source: tests/integration_tests/step_prune.rs
+info:
+ program: wt
+ args:
+ - step
+ - prune
+ - "--yes"
+ env:
+ CLICOLOR_FORCE: ""
+ 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"
+ LANG: C
+ LC_ALL: C
+ NO_COLOR: ""
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1893456000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Removing feature worktree & branch in background (same commit as main, _)
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
+✓ Pruned 1 worktree & branch