Last active
December 8, 2020 16:44
-
-
Save ddbeck/485b853ee232f5057e9c9c07e74b4e8b to your computer and use it in GitHub Desktop.
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 | |
# If you save this as `git-sync` in your PATH, then you can run `git sync` | |
# shellcheck disable=SC2034 | |
USAGE="Synchronize the local and origin \`master\` branch with \`upstream\` remote's" | |
# shellcheck source=/dev/null | |
source "$(git --exec-path)/git-sh-setup" | |
# TODO: I ought to detect the default branch instead of hardcoding master | |
BRANCH="master" | |
if [ $# -ge 2 ]; then | |
echo "Too many arguments. Specify one and only one upstream branch to sync from." | |
exit 1 | |
fi | |
if [ $# -eq 1 ]; then | |
BRANCH=$1 | |
fi | |
ORIGIN="origin" | |
UPSTREAM="upstream" | |
ORIGIN_REF="origin/$BRANCH" | |
UPSTREAM_REF="$UPSTREAM/$BRANCH" | |
echo "Starting to sync from '$UPSTREAM_REF' to '$ORIGIN_REF'." | |
require_work_tree | |
require_clean_work_tree | |
if ! git ls-remote --exit-code --heads "$UPSTREAM" "$BRANCH" >/dev/null; then | |
die "error: cannot sync without '$UPSTREAM_REF'." | |
fi | |
if ! git ls-remote --exit-code --heads "$ORIGIN" "$BRANCH" >/dev/null; then | |
die "error: cannot sync without '$ORIGIN_REF'." | |
fi | |
if ! git show-ref --verify --quiet "refs/heads/$BRANCH"; then | |
die "error: cannot sync without '$BRANCH'." | |
fi | |
if ! git show-ref --verify --quiet "refs/remotes/$ORIGIN_REF"; then | |
die "error: cannot sync without '$ORIGIN_REF'." | |
fi | |
if ! git show-ref --verify --quiet "refs/remotes/$UPSTREAM_REF"; then | |
die "error: cannot sync without '$UPSTREAM_REF'." | |
fi | |
git switch --quiet "$BRANCH" && | |
git fetch "$UPSTREAM" && | |
git rebase "$UPSTREAM_REF" && | |
git push "$ORIGIN" "$BRANCH" && | |
git switch --quiet - | |
echo "Finished syncing from '$UPSTREAM_REF' to '$ORIGIN_REF'." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment