-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathgit-delete-gone-branches
executable file
·57 lines (49 loc) · 1.27 KB
/
git-delete-gone-branches
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
#!/usr/bin/env bash
app_name="$(basename "${BASH_SOURCE[0]}")"
app_dir="$(dirname "${BASH_SOURCE[0]}")"
print_help() {
expand -t 4 << EOF
Usage:
$app_name
Delete local branches that no longer exist on remote.
Options:
-?, --help
Show this help information and exit.
EOF
}
while [[ $# -gt 0 ]]; do
case "$1" in
-\?|--help)
print_help
exit 0
;;
-*)
echo "$app_name: [Error] Unknown option: $1" >&2
exit 1
;;
*)
echo "$app_name: [Error] Unexpected argument: $1" >&2
exit 1
;;
esac
done
git rev-parse --git-dir > /dev/null || exit $?
git fetch --all --prune &&
current_branch="$(git rev-parse --abbrev-ref HEAD)" &&
main_branch="$("${app_dir}/git-main-branch" --quiet)" &&
for branch in $(git for-each-ref --format '%(refname) %(upstream:track)' refs/heads | awk '$2 == "[gone]" {sub("refs/heads/", "", $1); print $1}'); do
if [[ $branch == $current_branch ]]; then
if [[ $branch != $main_branch ]]; then
if ! "${app_dir}/git-is-worktree-clean" -q; then
echo "$app_name: [Error] Cannot delete current branch: Working tree has changes." >&2
exit 1
fi
git switch "$main_branch" &&
git branch -D "$branch"
else
echo "$app_name: [Error] Cannot delete main branch '$main_branch'." >&2
fi
else
git branch -D "$branch"
fi
done