Git Workflow

By Alan Crissey
This content is more than two years old and may be a bit out of date.

It’s taken me a really, REALLY long time to get the hang of Git. Like an absurd amount of time, considering how long I’ve been building websites. The terminology is a bit weird to me, but over time I feel I’ve finally started to get it. And I’ve learned a few simple things that make working in it every day a bit easier.

Let Your Branches Grow

Only work off of branches. How ever big or small your change, creating a branch keeps things flexible. This makes it much easier to switch back to master to do other work if you need to. And if you find yourself still on master with your new changes and you forgot to create a new branch, no worries:

git add .
git stash
git checkout -b {your_new_branch_name}
git stash apply

And you’re good.

Embrace the Rebase

For a long time I heard or read the term 'rebase' but didn’t know what it really meant. It sounded like some crazy complicated thing that would further confuse me. But I finally learned how to use it properly and it’s made merging branches back into master so much easier.

Since the master branch may be changing over time, I've made it a habit to always rebase my branch to master before I merge it, or even do it periodically as I’m working on my branch, depending on the amount of time that’s passed. This will also alert you of any merge conflicts that may arise before you’ve actually merged your branch.

In its simplest form:

git checkout master
git pull
git checkout {your_branch_name}
git rebase master

If there aren’t any conflicts, you’re good to go. Your branch’s changes have been moved up to be the latest, as if you’d just created the branch. If your branch is on a remote, you’ll have to use --force the next time you push since you’re rewriting history. Some may be completely against rewriting history, but I believe branches are a place where this should happen.

Keep Pull Requests Sane

My last bit of advice is cleaning up your pull requests before you make them. Chances are if you’ve been working on your branch a while, it has dozens of commits, many of which are no longer relevant. Whoever reviews the pull request has to sift through the changes in those commits, and each commit will also end up in the history of the master branch once it’s merged in. That’s messy.

So this is what I do after rebasing my branch:

git reset --soft master

This uncommits your changes against the master branch, with your changes intact. Now you can recommit all of your changes in an organized, deliberate way. I use a tool called gitx so I can see the changes I made in each file to make this a bit easier, but you can use any tool that displays history. Once you finish making your new set of commits, you’ll have to use --force next time you push but again, this is a point where I believe rewriting history is a good thing.