Skip to content

Commit 2794657

Browse files
authored
Script to clean up branches (#1218)
1 parent 85d6909 commit 2794657

1 file changed

Lines changed: 80 additions & 0 deletions

File tree

scripts/delete-gone-branches.sh

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#!/bin/bash
2+
3+
set -euo pipefail
4+
5+
usage() {
6+
cat <<'EOF'
7+
Usage: bash scripts/delete-gone-branches.sh [--apply]
8+
9+
Find local branches whose upstream is marked "[gone]" and delete them.
10+
11+
Options:
12+
--apply Actually delete the branches with `git branch -D`
13+
--help Show this help text
14+
15+
Without --apply, the script prints what it would delete.
16+
EOF
17+
}
18+
19+
apply=false
20+
21+
case "${1:-}" in
22+
"")
23+
;;
24+
--apply)
25+
apply=true
26+
;;
27+
--help|-h)
28+
usage
29+
exit 0
30+
;;
31+
*)
32+
echo "Unknown option: $1" >&2
33+
usage >&2
34+
exit 1
35+
;;
36+
esac
37+
38+
git fetch --prune --quiet
39+
40+
mapfile -t gone_branches < <(
41+
git for-each-ref --format='%(refname:short) %(upstream:track)' refs/heads |
42+
while IFS= read -r line; do
43+
branch=${line% *}
44+
tracking=${line#"$branch "}
45+
if [[ "$tracking" == "[gone]" ]]; then
46+
printf '%s\n' "$branch"
47+
fi
48+
done
49+
)
50+
51+
if [[ ${#gone_branches[@]} -eq 0 ]]; then
52+
echo "No local branches with gone upstreams found."
53+
exit 0
54+
fi
55+
56+
current_branch="$(git branch --show-current)"
57+
58+
echo "Found ${#gone_branches[@]} branch(es) with gone upstreams:"
59+
printf ' %s\n' "${gone_branches[@]}"
60+
61+
if [[ "$apply" != true ]]; then
62+
echo
63+
echo "Dry run only. Re-run with --apply to delete them."
64+
exit 0
65+
fi
66+
67+
deleted_count=0
68+
69+
for branch in "${gone_branches[@]}"; do
70+
if [[ "$branch" == "$current_branch" ]]; then
71+
echo "Skipping current branch: $branch"
72+
continue
73+
fi
74+
75+
git branch -D "$branch"
76+
deleted_count=$((deleted_count + 1))
77+
done
78+
79+
echo
80+
echo "Deleted $deleted_count branch(es)."

0 commit comments

Comments
 (0)