Skip to content

Instantly share code, notes, and snippets.

@sattellite
Last active August 14, 2019 11:49
Show Gist options
  • Save sattellite/1856bb878c2f553f85041b6b6ccb074b to your computer and use it in GitHub Desktop.
Save sattellite/1856bb878c2f553f85041b6b6ccb074b to your computer and use it in GitHub Desktop.
Syncing local repo with remote
#!/bin/bash
# Put this file to $PATH and then call it `git sync`
set -e
LANG=C
NC='\033[0m'
RED="${NC}\033[0;31m"
YLW="${NC}\033[1;33m"
WHI="${NC}\033[1;37m"
GRN="${NC}\033[1;32m"
log() {
local text=$@
echo -e "${WHI}[${GRN}SYNC${WHI}] ${text}${NC}"
}
err() {
local text=$@
echo -e "${WHI}[${RED}ERRO${WHI}] ${text}${NC}"
}
# Function to do nothing
noop() {
local a=1
}
readonly curbr=$(git symbolic-ref --short HEAD)
readonly stashmsg="beforesync $(date +'%F %T')"
log "Current branch is ${curbr}..."
declare -x failed=false
declare -x uptodate=true
log "Stashing all changes..."
git stash push --include-untracked --quiet -m "${stashmsg}"
log "Fetching all changes from remote..."
git remote update origin --prune
log "Syncing all tracked branches..."
for branch in $(git for-each-ref --format='%(refname:short)' refs/heads); do
# If not failed state
if [ "${failed}" == "false" ]; then
upstream=$(git rev-parse --abbrev-ref $branch@{upstream} 2>/dev/null)
# If branch is tracked
if [ $? -eq 0 ]; then
# https://stackoverflow.com/a/3278427/1489324
LOCAL=$(git rev-parse ${branch})
REMOTE=$(git rev-parse "${branch}@{upstream}")
BASE=$(git merge-base ${branch} "${branch}@{upstream}")
if [ $LOCAL = $REMOTE ]; then
#log "Branch \"$branch\" is up-to-date"
noop
elif [ $LOCAL = $BASE ]; then
uptodate=false
log "Syncing branch \"${branch}\"..."
git checkout ${branch} --quiet;
git pull --quiet;
# If failed checkout or fetch or merge branch
if [ $? -ne 0 ]; then
failed=true
err "Failed merge branch \"${branch}\""
err "You need in hand mode merge branches:"
err " ${branch}"
#else
# log "Synced branch \"${branch}\""
fi
fi
fi
# If failed state
else
err " ${branch}"
fi
done
if [ "${failed}" == "true" ]; then
err "Then apply stash \"${stashmsg}\""
err "At the end return tqo \"${curbr}\" branch"
exit 1
fi
if [ "${uptodate}" == "true" ]; then
log "All branches is up-to-date"
fi
log "Returning to branch \"${curbr}\"..."
git checkout ${curbr} --quiet
readonly stashid=$(git stash list | grep "$stashmsg" | cut -d: -f1)
if [ ! -z "${stashid}" -a "${stashid}" != " " ]; then
log "Applying previously stashed changes..."
git stash pop --quiet
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment