Skip to content

Instantly share code, notes, and snippets.

@Boldewyn
Last active December 22, 2016 10:37
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Boldewyn/8454951 to your computer and use it in GitHub Desktop.
Save Boldewyn/8454951 to your computer and use it in GitHub Desktop.
The `git get` command to replace `git pull` with a sophisticated rebase strategy
#!/bin/bash
#
# git get
#
# Place this script in your path, so that git(1) can find it. Presto!
# You can now type `git get` instead of `git pull` and enjoy the
# advantages of rebasing atop instead of merging remote changes.
#
# If you have local changes, use `git get --stash` to stash and
# pop afterwards your changes automatically.
#
# Use `git get <remote>` to fetch from a specific remote other than
# origin.
#
# Use `git get <remote> <remote-branch>` to specify a remote branch
# other than the one with the same name you're localy on.
#
# See http://notes.envato.com/developers/rebasing-merge-commits-in-git/
#
STASH=${1-}
if [[ $STASH == "--stash" || $STASH == "-s" ]]; then
shift
else
STASH=
fi
BRANCH="${2-$(git symbolic-ref --short -q HEAD)}"
if [[ $BRANCH == "" ]]; then
BRANCH=master
fi
ORIGIN="${1-$(git config --get "branch.$BRANCH.remote")}"
if [[ $ORIGIN == "" ]]; then
ORIGIN=origin
fi
echo $ORIGIN/$BRANCH
[ $STASH ] && {
CHECK=$(cat .git/refs/stash 2>/dev/null)
git stash save "git-get on $(date)"
}
git fetch $ORIGIN && \
git rebase -p --stat "$ORIGIN/$BRANCH"
[ $STASH ] && {
if [[ $(cat .git/refs/stash 2>/dev/null) != $CHECK ]]; then
# something got stashed above. Unstash it.
git stash pop -q
fi
}
@Boldewyn
Copy link
Author

After line 34, I could add a bit more logic to get the branch's real remote tracking branch and fetching/rebasing only that. Something like

TRACKING_BRANCH=$(git config --get "branch.$BRANCH.merge" | sed 's!refs/heads/!!')

with error checking.

@Boldewyn
Copy link
Author

Auto-detecting, if we need to merge: http://stackoverflow.com/a/5143914/113195

In a nutshell:

STASH=
if ! git diff-index --quiet HEAD; then
    STASH=1
fi

@Boldewyn
Copy link
Author

Rev. 4: Add better stash support and better origin detection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment