I’ve known for a while that you shouldn’t commit to your master branch in Git. I’ve seen random tweets about it, read a blog post or two when someone talked through their workflow, but it never really clicked why you wouldn’t want to commit to master all the time. Until yesterday.
The scenario: So, I was working on a website that has been live for a few months now. I’ve been regularly pushing fixes and new features by just committing to the master branch and pushing that: Add some new footer info, change a few css styles, add a few lines of jQuery, etc. No sweat. I’d just make the changes, commit and push them, and then they were live. The trouble reared its head yesterday as I was working on a fairly large new feature. The changes spanned about 5 different files, and nothing was ready to go live yet. My coworker messaged me saying—”I just added a table to a page, but it’s completely unstyled. Do you need to add some css?”
Here I was, with a ton of changes made to a pile of different files, my local master is about 10 commits ahead of my live master, and I need to push about 5 lines of css.
What did I do? In the end, I was able to use Github’s app to select and commit only the lines I needed in my css file, and run
git push origin XXXXXXXXXX:master with the latest commit id. The problem was that I ended up doing that all day. Pushing individual commits to the live server all day is really, really stupid.
What I should have done: A month ago, when I started working on that new big feature, I should have created a new branch for it. If I’d done this, pushing those table styles yesterday would have been really painless. Basically, I would have had three branches yesterday:
I would have worked in the
table_styles branch, writing all my css there, and then merged the changes into
master before pushing it live. When I was done merging, all I needed to do was delete the
table_styles branch, and I’m all set to continue working in
The takeaway advice: (Clearly) I’m no Git expert, but next time you commit to
master, ask yourself if what you’re working on shouldn’t be happening in a new branch, and get merged into
master when you’re done. My new practice is creating a new branch for every new thing I work on. This way, master will always be ready for quick hotfixes and minor changes.
I’m a complete noob, I know! Maybe I didn’t know before, or maybe it was just laziness, but yesterday was literally my first a-ha moment with this. If you’re just starting with Git, you should really get into the habit of using branches. The official guide will do a great job of showing you how to use branches, and I hope I’ve just done an ok job at showing you why you should.