-
Notifications
You must be signed in to change notification settings - Fork 0
/
git-branch-prune-local
executable file
·75 lines (62 loc) · 1.51 KB
/
git-branch-prune-local
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
#!/bin/bash
{
set -euo pipefail
function show_help() {
cat <<HELP
Usage: git-branch-prune-local [ -h ]
Delete local branches where the upstream branch is gone.
Options:
-h Print this help text and exit.
HELP
}
if (( $# == 1 )) && [[ "$1" == "-h" ]]
then
show_help
exit 0
fi
if (( $# != 0 ))
then
echo 1>&2 "Error: Invalid option. Try '-h'."
exit 1
fi
if [ -n "$(git status --porcelain)" ]
then
echo ">>> Error: Please commit changes first." 1>&2
exit 1
fi
current_branch="$(git symbolic-ref -q HEAD)"
current_branch="${current_branch##refs/heads/}"
current_branch="${current_branch:-HEAD}"
function clean_up() {
if [ "$current_branch" != "HEAD" ] && git show-ref --quiet refs/heads/"$current_branch"
then
git checkout "$current_branch" &>/dev/null
fi
}
trap clean_up EXIT
branch=master
if ! git show-ref --quiet refs/heads/$branch
then
branch=main
if ! git show-ref --quiet refs/heads/$branch
then
echo ">>> Error: Can't switch to main or master?" 1>&2
exit 1
fi
fi
git checkout "$branch" &>/dev/null
IFS=$'\n'
# git remote prune origin # Only useful if origin is different than the 'fetch' below:
git fetch --prune --prune-tags --force
script_path="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
askyn="$script_path/askYN"
branches="$( git branch -vv | grep ': gone]' | awk '{print $1}' )"
for branch in $branches
do
if $askyn "Delete ${branch}?"
then
git branch -D "$branch"
fi
done
exit 0
}