Skip to content

Instantly share code, notes, and snippets.

@virtualstaticvoid
Last active September 1, 2022 13:28
Show Gist options
  • Save virtualstaticvoid/8bf43151a976f81281ef11ccc4af5a06 to your computer and use it in GitHub Desktop.
Save virtualstaticvoid/8bf43151a976f81281ef11ccc4af5a06 to your computer and use it in GitHub Desktop.
git-sync
#!/bin/bash
#
# Description:
#
# Synchronises the local repository with _all_ the configured remotes
#
# Optionally, it will safely perform a rebase of the checked out branch
# with it's corresponding tracking (remote) branch
#
# NOTE: remote branches which have been removed are pruned locally
#
# Usage:
#
# git sync
# git sync --rebase
#
# fail fast
set -e
if [[ ! -d .git ]]; then
printf "\033[1;31mERROR\033[0m: Run this script from the project root which contains the .git directory.\n"
exit 1
fi
# option to perform rebase after fetching updates
rebase=${1}
# check for remotes
remotes=$(git remote | head -1)
if [[ -z "$remotes" ]]; then
printf "\n\033[1;33mWARNING:\033[0m Skipping, no remotes defined.\n"
exit 1
fi
# fetch for all defined remotes
# and prune remote branches which have been removed
git fetch --all --prune 2>&1
# sometimes git needs to rebuild it's index
git status &> /dev/null
if [[ "$rebase" == "--rebase" ]]; then
# check for uncommitted changes
changes=$(git diff-index --name-only HEAD -- | tr -d '[:space:]')
if [[ -n "$changes" ]]; then
echo
printf "\033[1;31mERROR\033[0m: There are outstanding changes. Skipping rebase.\n"
echo
git status 2>&1
echo
exit 1
fi
# get tracking branch
tracking=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>&1 || echo "")
if [[ -n "$tracking" ]]; then
printf "\033[1;32mINFO\033[0m: Rebasing off \033[1m$tracking\033[0m branch.\n"
git rebase $tracking 2>&1
else
printf "\033[1;33mWARNING\033[0m: Skipping rebase, no configured tracking branch.\n"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment