Git Lifecycle: Rebase Instead of Merge Workflow

git rebase notes

$ git remote update

...pulls down the latest changes from origin to local repository but doesn't change files or where the master branch points. For sake of argument the following assumes some commits were pulled down.

$ git status

Make sure there are no any outstanding changes. If this is the case, you should see a message something like:

Your branch is behind 'origin/master' by 2 commits, and can be fast-forwarded.

The mention of "fast-forward" means that if you merge with origin/master at this point, it won't really be a merge because you don't have any local changes, it will just merge the new commits from origin into your local files. I pretty much try never to merge unless it is a fast-forward merge.

$  git merge origin/master

This updates with the latest changes. Prefer git merge to git reset --hard here because the merge will be more forgiving if you really did have local changes you forgot about. The reset will blow them away. The merge will either fail, or merge your changes (not what's wanted but can be fixed before pushing) depending on if they were committed. Either way things are recoverable and your changes aren't lost.

Now make the changes...

$  git commit

You can have any number of commits here. If there are mutltiple, try squashing or rearranging them with:

$  git rebase --interactive HEAD^^^^

where the ^^^^ indicates how far back in history you want to look when deciding what to do. Each carat is one revision back. You can also do ~4 instead of ^^^^ where the number after the tilde is the number of commits to go back. There is no harm here if you go back farther than you needed to.

$  git remote update

Get the latest from origin because a push will fail if there are any commits you don't already have.

$  git status

Assuming the remote update pulled-down something, you get a message something like:

Your branch and 'origin/master' have diverged, # and have 1 and 1 different
commit(s) each, respectively.
$  git rebase origin/master

This is where you would normally merge. Doing a rebase instead makes for a cleaner git commit tree. The rebase can have conflicts just as a merge can. If you have conflicts, you fix them using git add on the conflicting files to mark them as resolved, then do:

$  git rebase --continue

It's possible you may have to resolve conflicts multiple times if there were multiple changes pulled down from master or you are rebasing multiple commits.

$  gitk --all
Looking in gitk at this point, your commits should be on a single straight line off of origin/master.

$  git push origin master

Alternatively, ...

...if you have changes that are not committed and you want to rebase them on top of origin master, do this:

$ git stash
$ git merge origin/master (or git rebase --hard origin/master)
$ git stash pop