Skip to content

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

Exclude remote-only branches from wt remove completions (#108)

Maximilian Roos53ecc3584e88
diff --git a/src/cli.rs b/src/cli.rs
index bd9e81ce4..3de00902f 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -1295,7 +1295,7 @@ Arguments resolve by path first, then branch name. [Shortcuts](@/switch.md#short
)]
Remove {
/// Worktree or branch (@ for current)
- #[arg(add = crate::completion::worktree_branch_completer())]
+ #[arg(add = crate::completion::local_branches_completer())]
worktrees: Vec<String>,
/// Keep branch after removal
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index c193ce542..3c76ec8a2 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -82,7 +82,7 @@ impl RepositoryCliExt for Repository {
let worktree_path = match self.worktree_for_branch(branch_name)? {
Some(path) => path,
None => {
- // No worktree found - check if the branch exists
+ // No worktree found - check if the branch exists locally
if self.local_branch_exists(branch_name)? {
// Branch exists but no worktree - return BranchOnly to attempt branch deletion
return Ok(RemoveResult::BranchOnly {
@@ -91,6 +91,15 @@ impl RepositoryCliExt for Repository {
force_delete,
});
}
+ // Check if branch exists on a remote
+ let remotes = self.remotes_with_branch(branch_name)?;
+ if !remotes.is_empty() {
+ return Err(GitError::RemoteOnlyBranch {
+ branch: branch_name.into(),
+ remote: remotes[0].clone(),
+ }
+ .into());
+ }
return Err(GitError::NoWorktreeFound {
branch: branch_name.into(),
}
diff --git a/src/completion.rs b/src/completion.rs
index 76d55826f..2afc3e68d 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -31,19 +31,30 @@ pub fn maybe_handle_env_completion() -> bool {
pub fn branch_value_completer() -> ArgValueCompleter {
ArgValueCompleter::new(BranchCompleter {
suppress_with_create: false,
+ exclude_remote_only: false,
})
}
-/// Branch completion for positional arguments that represent worktrees (switch/remove).
+/// Branch completion for positional arguments that represent worktrees (switch).
pub fn worktree_branch_completer() -> ArgValueCompleter {
ArgValueCompleter::new(BranchCompleter {
suppress_with_create: true,
+ exclude_remote_only: false,
+ })
+}
+
+/// Branch completion for remove command - excludes remote-only branches.
+pub fn local_branches_completer() -> ArgValueCompleter {
+ ArgValueCompleter::new(BranchCompleter {
+ suppress_with_create: false,
+ exclude_remote_only: true,
})
}
#[derive(Clone, Copy)]
struct BranchCompleter {
suppress_with_create: bool,
+ exclude_remote_only: bool,
}
impl ValueCompleter for BranchCompleter {
@@ -55,7 +66,7 @@ impl ValueCompleter for BranchCompleter {
// Filter branches by prefix - clap doesn't filter ArgValueCompleter results
let prefix = current.to_string_lossy();
- complete_branches(self.suppress_with_create)
+ complete_branches(self.suppress_with_create, self.exclude_remote_only)
.into_iter()
.filter(|candidate| {
candidate
@@ -67,7 +78,10 @@ impl ValueCompleter for BranchCompleter {
}
}
-fn complete_branches(suppress_with_create: bool) -> Vec<CompletionCandidate> {
+fn complete_branches(
+ suppress_with_create: bool,
+ exclude_remote_only: bool,
+) -> Vec<CompletionCandidate> {
if suppress_with_create && suppress_switch_branch_completion() {
return Vec::new();
}
@@ -83,6 +97,9 @@ fn complete_branches(suppress_with_create: bool) -> Vec<CompletionCandidate> {
branches
.into_iter()
+ .filter(|branch| {
+ !exclude_remote_only || !matches!(branch.category, BranchCategory::Remote(_))
+ })
.map(|branch| {
let time_str = format_relative_time_short(branch.timestamp);
let help = match branch.category {
diff --git a/src/git/error.rs b/src/git/error.rs
index 3c5528aa4..005ec209a 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -59,6 +59,10 @@ pub enum GitError {
NoWorktreeFound {
branch: String,
},
+ RemoteOnlyBranch {
+ branch: String,
+ remote: String,
+ },
WorktreePathOccupied {
branch: String,
path: PathBuf,
@@ -183,6 +187,13 @@ impl std::fmt::Display for GitError {
)
}
+ GitError::RemoteOnlyBranch { branch, remote } => {
+ cwrite!(
+ f,
+ "{ERROR_EMOJI} <red>Branch <bold>{branch}</> exists only on remote ({remote}/{branch})</>\n\n{HINT_EMOJI} <dim>Use <bright-black>wt switch {branch}</> to create a local worktree</>"
+ )
+ }
+
GitError::WorktreePathOccupied {
branch,
path,
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index fba5d8dc0..d90aadd27 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -660,29 +660,30 @@ fn test_complete_switch_base_flag_after_branch() {
}
#[test]
-fn test_complete_remove_shows_branches() {
+fn test_complete_remove_excludes_remote_only_branches() {
let mut temp = TestRepo::new();
temp.commit("initial");
// Create worktree (creates "feature/new" branch)
temp.add_worktree("feature/new");
- // Create another branch without worktree
+ // Create another local branch without worktree
Command::new("git")
.args(["branch", "hotfix/bug"])
.current_dir(temp.root_path())
.output()
.unwrap();
- // Test completion for remove (should show ALL branches)
+ // Test completion for remove (should show local branches, exclude remote-only)
let output = temp.completion_cmd(&["wt", "remove", ""]).output().unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
let branches: Vec<&str> = stdout.lines().collect();
- // Should include both branches
+ // Should include branches with worktrees
assert!(branches.iter().any(|b| b.contains("feature/new")));
+ // Should include local branches without worktrees (can still delete the branch)
assert!(branches.iter().any(|b| b.contains("hotfix/bug")));
}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 18249f6b9..2e94c8ce8 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -145,6 +145,44 @@ fn test_remove_nonexistent_worktree() {
snapshot_remove("remove_nonexistent_worktree", &repo, &["nonexistent"], None);
}
+#[test]
+fn test_remove_remote_only_branch() {
+ let repo = setup_remove_repo();
+
+ // Create a remote-only branch by pushing a branch then deleting it locally
+ Command::new("git")
+ .args(["branch", "remote-feature"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ Command::new("git")
+ .args(["push", "origin", "remote-feature"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ Command::new("git")
+ .args(["branch", "-D", "remote-feature"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ Command::new("git")
+ .args(["fetch", "origin"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Try to remove a branch that only exists on remote - should get helpful error
+ snapshot_remove(
+ "remove_remote_only_branch",
+ &repo,
+ &["remote-feature"],
+ None,
+ );
+}
+
#[test]
fn test_remove_by_name_dirty_target() {
let mut repo = setup_remove_repo();
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_remote_only_branch.snap b/tests/snapshots/integration__integration_tests__remove__remove_remote_only_branch.snap
new file mode 100644
index 000000000..47f0f8734
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_remote_only_branch.snap
@@ -0,0 +1,28 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - remote-feature
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ 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: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1735776000"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+❌ Branch remote-feature exists only on remote (origin/remote-feature)
+
+💡 Use wt switch remote-feature to create a local worktree