Working with Branches in Git

Recently I’ve been doing more git than I ever intended to, working with the Joind.in codebase, contributing and managing contributions to that. I quickly realised that I needed to make changes on branches, and since I’m new to git, it took a while to figure some of this out. I’m pretty confident now* so I thought I’d share how I work with branches in git.

Available Branches and The Current Branch

This is the easy bit:

$ git branch
* api
  master
$

The entry with the star next to it is the current branch, so here you can see that I have branches “master” and “api” and I’m currently working on the “api” branch. If you only have one branch it will usually be called “master”.

Creating and Changing Branches

My experience is with Subversion until now, and branching is really different in git (because it actually has branches rather than just copies, this is definitely a feature, but it is a different approach from how I had used them before). So you can switch your working copy around to look at different branches, which threw me a bit to begin with. To change branches, just checkout the one you want:

$ git checkout master
Switched to branch 'master'
$

If you actually wanted a new branch simply name it and ask checkout to create it if it doesn’t exist, by using the -b switch:

$ git checkout -b demo
Switched to a new branch 'demo'
$

So now my branch command shows me this:

$ git branch
  api
* demo
  master
$

Pushing Branches

This is very much an optional step. Many of my branches are private branches – meaning that I branch on the development server, finish the feature at hand, and then merge the changes into my master branch without pushing the branch to anywhere else. To share changes with others though, I sometimes like to push my changes up to github – which is my “origin” remote on my repo. So to push the demo branch we just made, I would simply do:

$git push origin demo
Total 0 (delta 0), reused 0 (delta 0)
To [email protected]:lornajane/joind.in.git
 * [new branch]      demo -> demo
$

If you use “git push” on its own, it will push all branches which exist on both the local repo and the origin – but will not push any private branches unless you specify that it should.

Resources

The http://help.github.com site, Github’s own documentation, is actually brilliant and has really helped me to get up to speed with working with my own code and contributions from others.

* The only problem I’ve had with code on github recently is that I merged totally the wrong changeset into the main project root. Which really isn’t the fault of the source control system :)

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.