Add worktree rm [-d,--delete-branch] to delete git branch

This commit is contained in:
2026-10-28 14:33:31 +00:00
parent e2ae3f4932
commit 150f50c9fa
2 changed files with 17 additions and 2 deletions

View File

@@ -21,6 +21,9 @@ __worktree_active_branches() {
local -a branches
branches=(${(fo)"$(git worktree list --porcelain 2>/dev/null | \
awk '/^worktree /{ wt++ } wt>1 && /^branch refs\/heads\//{ sub(/^branch refs\/heads\//, ""); print }')"})
# Skip branches already given elsewhere on the command line.
local -a typed=(${words[1,CURRENT-1]} ${words[CURRENT+1,-1]})
branches=(${branches:|typed})
_describe 'branch' branches
}
@@ -72,7 +75,8 @@ _worktree() {
(rm|remove)
_arguments \
'(-f --force)'{-f,--force}'[Force removal even with modified or untracked files]' \
'*:: :__worktree_active_branches'
'(-d --delete-branch)'{-d,--delete-branch}'[Also delete the branch]' \
'*: :__worktree_active_branches'
;;
(sync)
_arguments '*:: :__worktree_active_branches'

View File

@@ -91,7 +91,8 @@ worktree() {
worktree find [-i] <glob>
Manage git worktrees by branch name. A new branch starts from <start-point>,
e.g. other/main, or origin/main by default."
e.g. other/main, or origin/main by default. remove -d also deletes the branch,
which must be merged unless -f is given."
return 0
fi
@@ -289,11 +290,13 @@ e.g. other/main, or origin/main by default."
rm|remove)
local force=0
local delete_branch=0
local branches=()
local arg
for arg in "${@:2}"; do
case "$arg" in
-f|--force) force=1 ;;
-d|--delete-branch) delete_branch=1 ;;
*) branches+=("$arg") ;;
esac
done
@@ -346,6 +349,14 @@ e.g. other/main, or origin/main by default."
rmdir "$parent" 2>/dev/null || break
parent=${parent:h}
done
if (( delete_branch )); then
# An unmerged branch is only deleted with --force.
if (( force )); then
git branch -D "$branch" || failed=1
else
git branch -d "$branch" || failed=1
fi
fi
done
return $failed
;;