-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit_sync.sh
executable file
·102 lines (91 loc) · 2.48 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
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
#!/bin/bash
#
# Script to mirror and keep in sync two git repositories
# Protected branches should not be updated on the Mirror to avoid conflicts
# These script come without warranty of any kind. Use them at your own risk.
ORIGIN="git@github.com:YOURUSER/sourceRepo.git" # Origin repository url
MIRROR="git@github.com:YOURUSER/destinationRepo.git" # Mirror repository url
PROTECTED_BRANCHES=("main" "develop" "release") # Branches to keep in sync
ORIGIN_FOLDER="${ORIGIN##*/}"
CURRENT_FOLDER="$(pwd)"
function goToOriginFolder() {
cd ${CURRENT_FOLDER}/${ORIGIN_FOLDER}
}
function goToScriptFolder() {
cd ${CURRENT_FOLDER}
}
# Print all the branches in the local repository
function getCurrentBranches() {
goToOriginFolder
CURRENT_BRANCHES=$(git --no-pager branch -l | sed 's/*/ /' | awk '{print $1;}')
echo ""
echo "=== Current branches in ${ORIGIN_FOLDER} are:"
echo "${CURRENT_BRANCHES}"
goToScriptFolder
}
# Clone the origin repository and set the mirror repository
function setup() {
git clone --mirror ${ORIGIN}
goToOriginFolder
git remote add --mirror=fetch mirror ${MIRROR}
goToScriptFolder
}
# Sync the branches from the PROTECTED_BRANCHES array
function sync() {
goToOriginFolder
git fetch origin
goToScriptFolder
getCurrentBranches
goToOriginFolder
for current_branch in ${CURRENT_BRANCHES[@]}; do
if [[ " ${PROTECTED_BRANCHES[@]} " =~ " ${current_branch} " ]]; then
echo "* Syncing ${current_branch}"
git push mirror ${current_branch}
fi
done
goToScriptFolder
}
# Delete local branches not required to be synced
function deleteLocalBranches() {
local current_branch=""
goToOriginFolder
for current_branch in ${CURRENT_BRANCHES[@]}; do
if [[ ! " ${PROTECTED_BRANCHES[@]} " =~ " ${current_branch} " ]]; then
echo "* Deleting ${current_branch}"
git branch -D ${current_branch}
fi
done
goToScriptFolder
}
# Delete local branches not in the PROTECTED_BRANCHES array and then sync
function sync2() {
goToOriginFolder
git fetch origin
goToScriptFolder
getCurrentBranches
deleteLocalBranches
getCurrentBranches
goToOriginFolder
git push mirror --all
goToScriptFolder
}
function usage() {
echo "${0} current_branches|setup|sync|sync2"
}
case ${1} in
current_branches)
getCurrentBranches
;;
setup)
setup
;;
sync)
sync
;;
sync2)
sync2
;;
*)
usage
;;
esac