/
git-elegant-prune-repository
69 lines (60 loc) · 2.06 KB
/
git-elegant-prune-repository
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
#!/usr/bin/env bash
set -e
command-purpose() {
cat <<MESSAGE
Removes useless local branches.
MESSAGE
}
command-synopsis() {
cat <<MESSAGE
usage: git elegant prune-repository
MESSAGE
}
command-description() {
cat<<MESSAGE
Identifies useless branches within the current repository and removes them. A
branch is useless if it either has configured an unavailable upstream branch (1)
or does not have new commits comparing to \`master\` branch (2).
1 - Usually, a local branch has this state when an appropriate remote branch was
merged to a remote target branch and was removed. Since these manipulations were
made on server side, the local branch is still present, but useless.
2 - This kind of branches appears when a branch is created for some purposes but
does not have any commits nowadays. So, it is useless.
Approximate commands flow is
\`\`\`bash
==>> git elegant prune-repository
git checkout master
git fetch --all
git rebase
git branch --delete --force task-24
git branch --delete --force 2349
git branch --delete --force task-1
\`\`\`
The command works even if the remotes are unavailable.
MESSAGE
}
--is-there-upstream-for() {
git rev-parse --abbrev-ref ${1}@{upstream} >/dev/null 2>&1
}
default() {
git-verbose checkout ${MASTER}
if --is-there-upstream-for ${MASTER}; then
git-verbose fetch --all || info-text "As the remotes can't be fetched, the current local version is used."
git-verbose rebase
fi
for branch in $(git for-each-ref --format "%(refname:short)" refs/heads/**); do
if [[ ${branch} == ${MASTER} ]]; then continue; fi
if [[ -n $(git config --get branch.${branch}.merge) ]]; then
if --is-there-upstream-for ${branch}; then
# the branch has existing upstream; keep it
continue
fi
else
if [[ ! $(git merge-base ${MASTER} ${branch}) == $(git rev-parse ${branch}) ]]; then
# the branch has new commits; keep it
continue
fi
fi
git-verbose branch --delete --force ${branch}
done
}