forked from imsky/git-fresh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit-fresh
executable file
·105 lines (88 loc) · 2.4 KB
/
git-fresh
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env bash
usage () {
echo "Usage: git fresh [-frsF] [remote] [root]"
echo "-f: Delete stale local and remote branches"
echo "-r: Rebase current branch against remote root"
echo "-s: Apply stashed changes after run"
echo "-F: Reset local root to remote root, wipe workspace"
echo "remote: remote name, origin by default"
echo "root: root branch, master by default"
exit 1;
}
error () {
echo "Error on line $1"
}
while getopts "fsrF" opt; do
case $opt in
f)
FORCE_DELETE_STALE=true
;;
s)
APPLY_STASH=true
;;
r)
REBASE=true
;;
F)
FORCE_LOCAL_RESET=true
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
trap 'error $LINENO' ERR
CURRENT=$(git rev-parse --abbrev-ref HEAD)
REMOTE=${1:-origin}
ROOT=${2:-master}
git remote update
git remote prune $REMOTE
STASH_STAMP=git-fresh-$(date +%s)
git stash save $STASH_STAMP
git checkout $ROOT 2> /dev/null
if [[ "$FORCE_LOCAL_RESET" = true ]]; then
git clean -dfx
git reset --hard $REMOTE/$ROOT
else
git rebase -q $REMOTE/$ROOT
fi
SMART_STALE=$(git branch -a --merged | tr -d "\*" | tr -s " " | grep -Ev ">|$ROOT" | cat)
LOCAL_STALE=$(grep -v "remotes/" <<< "$SMART_STALE" | cat)
REMOTE_STALE=$(grep "remotes/" <<< "$SMART_STALE" | cat)
REMOTE_STALE=${REMOTE_STALE//remotes\/$REMOTE\/}
if [[ ! -z "${SMART_STALE// }" ]]; then
if [[ ! -z "${LOCAL_STALE// }" ]]; then
if [[ "$FORCE_DELETE_STALE" = true ]]; then
echo -n $LOCAL_STALE | xargs git branch -d 2> /dev/null
else
echo "Local stale branches found:" $(echo -n $LOCAL_STALE | tr "\n" " ")
fi
fi
if [[ ! -z "${REMOTE_STALE// }" ]]; then
if [[ "$FORCE_DELETE_STALE" = true ]]; then
echo -n $REMOTE_STALE | xargs git push $REMOTE --delete
else
echo "Remote stale branches found:" $(echo -n $REMOTE_STALE | tr "\n" " ")
fi
fi
if [[ "$FORCE_DELETE_STALE" != true ]]; then
echo "Delete stale branches with: git fresh -f"
fi
fi
if [[ ! -z $(git rev-parse --verify --quiet "$CURRENT") ]]; then
git checkout $CURRENT 2> /dev/null
if [[ "$REBASE" = true ]]; then
git rebase $REMOTE/$ROOT
fi
else
echo "$CURRENT branch was stale, staying on $ROOT"
fi
if [[ ! -z $(git stash list | grep $STASH_STAMP | cat) ]]; then
if [[ "$APPLY_STASH" = true ]]; then
git stash pop
else
echo "Stashed changes present, apply with: git stash pop"
fi
fi
git gc --auto --prune=now