-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Expand file tree
/
Copy pathdelete-gone-branches.sh
More file actions
executable file
·80 lines (63 loc) · 1.49 KB
/
delete-gone-branches.sh
File metadata and controls
executable file
·80 lines (63 loc) · 1.49 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/bin/bash
set -euo pipefail
usage() {
cat <<'EOF'
Usage: bash scripts/delete-gone-branches.sh [--apply]
Find local branches whose upstream is marked "[gone]" and delete them.
Options:
--apply Actually delete the branches with `git branch -D`
--help Show this help text
Without --apply, the script prints what it would delete.
EOF
}
apply=false
case "${1:-}" in
"")
;;
--apply)
apply=true
;;
--help|-h)
usage
exit 0
;;
*)
echo "Unknown option: $1" >&2
usage >&2
exit 1
;;
esac
git fetch --prune --quiet
mapfile -t gone_branches < <(
git for-each-ref --format='%(refname:short) %(upstream:track)' refs/heads |
while IFS= read -r line; do
branch=${line% *}
tracking=${line#"$branch "}
if [[ "$tracking" == "[gone]" ]]; then
printf '%s\n' "$branch"
fi
done
)
if [[ ${#gone_branches[@]} -eq 0 ]]; then
echo "No local branches with gone upstreams found."
exit 0
fi
current_branch="$(git branch --show-current)"
echo "Found ${#gone_branches[@]} branch(es) with gone upstreams:"
printf ' %s\n' "${gone_branches[@]}"
if [[ "$apply" != true ]]; then
echo
echo "Dry run only. Re-run with --apply to delete them."
exit 0
fi
deleted_count=0
for branch in "${gone_branches[@]}"; do
if [[ "$branch" == "$current_branch" ]]; then
echo "Skipping current branch: $branch"
continue
fi
git branch -D "$branch"
deleted_count=$((deleted_count + 1))
done
echo
echo "Deleted $deleted_count branch(es)."