Last active
November 18, 2021 11:52
-
-
Save aryelgois/907c31764d55ba086b4ff23a6d318c96 to your computer and use it in GitHub Desktop.
Synchronize local branches with remotes (remove gone branches and fast-forward the others)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Synchronize local branches with remotes. | |
# | |
# It removes gone branches and fast-forward the others. | |
echo 'Fetching remotes...' | |
git fetch --prune | |
echo | |
BRANCHES=$(git for-each-ref refs/heads/ --format='%(upstream:short):%(refname:short)~%(upstream:track)') | |
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) | |
BRANCHES_TO_FF=$(grep -v -e '~\[gone\]$' -e ":$CURRENT_BRANCH" <<< "$BRANCHES" | grep '^[^:].*~.') | |
if [[ -n $BRANCHES_TO_FF ]]; then | |
echo 'Fast-forwarding local branches...' | |
while read -r BRANCH; do | |
echo "Update $(tr '~' ' ' <<< "${BRANCH#*:}")" | |
git fetch . "${BRANCH%~*}" | |
echo | |
done <<< "$BRANCHES_TO_FF" | |
fi | |
if grep -q ".*:$CURRENT_BRANCH~." <<< "$BRANCHES"; then | |
echo 'Pulling current branch...' | |
git pull | |
echo | |
fi | |
GONE_BRANCHES=$(grep '~\[gone\]$' <<< "$BRANCHES" | sed -e 's/^.*://; s/~.*$//') | |
if [[ -n $GONE_BRANCHES ]]; then | |
echo 'Removing gone branches...' | |
# shellcheck disable=SC2086 | |
git branch -d $GONE_BRANCHES | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment