Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/zsh
- ## Author: Mikhaylov Anton aka anion155 (anion155@gmail.com)
- ## version: 0.1
- ## zsh-version: 5.2
- ##
- ## Script to sync one remote to another.
- ## Usefull when you are updating fork to master repository.
- ##
- ## What does script does?
- ## 1) Push everything from upstream rep to origin.
- ## 2) Delete all non-upstream branches from origin.
- ## All deleted branches will be saved as local refs.
- ##
- UPSTREAM=$1
- ORIGIN=$2
- function usage() {
- echo "Usage:"
- echo "$0 <upstream-remote> <target-remote>"
- echo ""
- echo "Example which ensures remote named 'maxandersen' have all the same branches and tags as 'origin'"
- echo "$0 origin upstream"
- exit 1
- }
- if [ -z "$UPSTREAM" -o -z "$ORIGIN" ]; then
- echo "Missing arguments.\n"
- usage
- fi
- remotes=( `git remote` )
- if (( ${remotes[(i)$ORIGIN]} > ${#remotes} || ${remotes[(i)$UPSTREAM]} > ${#remotes} )); then
- echo "Remotes isn't exists.\n"
- usage
- fi
- unset remotes
- function pushUpstream() {
- for brname in ${u_branches[@]}; do
- git push $ORIGIN $UPSTREAM/$brname:$brname 2>&1 | grep -v 'Everything up-to-date' | grep --color -E '^error:|\[rejected\]|$'
- [ ${pipestatus[1]} -ne 0 ] && echo
- done
- }
- function deleteOldBranches() {
- for brname in ${o_branches[@]}; do
- if (( ${u_branches[(i)$brname]} <= ${#u_branches} )); then
- continue
- fi
- if ! $SILENT_DELETE; then
- echo -n " Do you want to delete origin branch '$brname', it's not upstream? "
- read -k 1 "?(n) "; if [[ $REPLY =~ $'^[^yY]|[\n]$' ]]; then
- echo; continue
- fi; echo
- fi
- local commit=`git rev-parse --short $ORIGIN/$brname`
- echo -n " Deleting branch '$brname' at '$commit' from origin."
- if (( ${l_branches[(i)$brname]} > ${#l_branches} )); then
- echo -n " Local copy will be stored at '$brname' branch."
- git branch $brname $commit
- fi; echo
- git push $ORIGIN :$brname >& /dev/null
- done
- }
- function main() {
- echo "Syncyng '$ORIGIN' to '$UPSTREAM' remotes\n"
- local l_branches=( `git branch -l | sed 's/^\*//'` )
- local o_branches=( `git branch -r | grep -v HEAD | grep $ORIGIN | sed -e "s/$ORIGIN\///"` )
- local u_branches=( `git branch -r | grep -v HEAD | grep $UPSTREAM | sed -e "s/$UPSTREAM\///"` )
- echo "Fetch remotes..."
- git fetch $ORIGIN >/dev/null
- git fetch $UPSTREAM >/dev/null
- echo "done\n"
- echo "Push branches from upstream to origin..."
- pushUpstream
- echo "done\n"
- local SILENT_DELETE=true
- echo -n "Delete all non upstream branches from origin..."
- read -k 1 "? - Are you sure? (y) "; if ! [[ $REPLY =~ $'^[yY\n]$' ]]; then
- SILENT_DELETE=false
- fi; echo
- deleteOldBranches
- echo "done\n"
- }
- main
Add Comment
Please, Sign In to add comment