Repository navigation
Expand file tree
/
Copy pathgit-fp
More file actions
executable file
·46 lines (41 loc) · 1.92 KB
/
Copy pathgit-fp
File metadata and controls
executable file
·46 lines (41 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/bin/bash -e
# Git script for cleaning up stale local branches.
if echo "$*" | grep -Eq -- '--help\b|-h\b'; then
echo "usage: ${0##*/} [-h|--help]" 1>&2
echo "Clean up merged tracking branches and merged agent worktree branches." 1>&2
exit 1
fi
git fetch -p
# 1. Delete local branches whose upstream tracking branch no longer exists. A branch
# checked out in another worktree can't be deleted until that worktree is removed.
current=$(git symbolic-ref --quiet --short HEAD || true)
git for-each-ref --format='%(refname:short)%09%(upstream:track)%09%(worktreepath)' refs/heads/ |
while IFS=$'\t' read -r branch track wt; do
[ "$track" = "[gone]" ] || continue
if [ "$branch" = "$current" ]; then
echo "Skipping $branch: upstream is gone but it is checked out here" 1>&2
continue
fi
echo "Removing branch with gone upstream: $branch"
if [ -n "$wt" ] && ! git worktree remove "$wt"; then
echo " skipped: worktree has uncommitted changes or is locked" 1>&2
continue
fi
git branch -D "$branch" || echo " failed to delete $branch" 1>&2
done
# 2. Delete agent-created worktree branches already merged into upstream main.
# These have no upstream, so pass 1 never sees them.
main_ref=origin/main
git rev-parse --verify --quiet "$main_ref" >/dev/null || main_ref=main
git for-each-ref --format='%(refname:short)%09%(objectname)%09%(worktreepath)' refs/heads/ |
while IFS=$'\t' read -r branch sha wt; do
case "$branch" in agents/*) ;; *) continue ;; esac
[ -n "$wt" ] || continue
git merge-base --is-ancestor "$sha" "$main_ref" 2>/dev/null || continue
echo "Removing merged agent worktree branch: $branch"
if git worktree remove "$wt"; then
git branch -D "$branch"
else
echo " skipped: worktree has uncommitted changes or is locked" 1>&2
fi
done