-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgit-sync.sh
executable file
·69 lines (62 loc) · 1.77 KB
/
git-sync.sh
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
#!/bin/sh
_log() {
echo "-----> $*"
}
_prefixed() {
sed -e "s/^/ /"
}
_prune() {
# shellcheck disable=SC2039
local remote
remote="$1"
_log "Pruning $remote..."
git remote prune "$remote" | _prefixed
}
_merge_locally() {
# shellcheck disable=SC2039
local branch remote
remote="$1"
branch="$2"
_log "Merging $remote/$branch locally..."
git fetch "$remote" | _prefixed
git merge --no-edit "$remote/$branch" | _prefixed
}
_push_to_fork() {
# shellcheck disable=SC2039
local branch remote
remote="$1"
branch="$2"
if ! [ "$remote" = "origin" ]; then
_log "Pushing it to origin/$branch..."
git push origin "$branch" | _prefixed
fi
}
# shellcheck disable=SC2039
git-delete-local-merged() {
main_branch=$(basename "$(git symbolic-ref --short refs/remotes/origin/HEAD)")
# shellcheck disable=SC2039
local branches
_log "Removing merged branches..."
branches="$(git branch --merged | grep -v "^\*" | grep -v "$main_branch" | tr -d '\n')"
[ -n "$branches" ] && echo "$branches" | xargs git branch -d
_log "Removing squashed and merged branches..."
git for-each-ref refs/heads/ "--format=%(refname:short)" | while read -r branch; do
base="$(git merge-base "$main_branch" "$branch")"
hash="$(git rev-parse "$branch^{tree}")"
commit="$(git commit-tree "$hash" -p "$base" -m _)"
[[ $(git cherry "$main_branch" "$commit") == "-"* ]] && git branch -D "$branch"
done
}
# shellcheck disable=SC2039
git-sync() {
# shellcheck disable=SC2039
local branch remote
branch=$(git symbolic-ref --short HEAD)
remote=$(git remote | grep upstream || echo "origin")
_prune "$remote"
_merge_locally "$remote" "$branch"
_push_to_fork "$remote" "$branch"
git branch -u "$remote/$branch"
git-delete-local-merged
_log "All done!"
}