Monday, January 18, 2010

Getting started with Git Part 2: Branching and Tracking

Part 1 of Getting started with Git can be found here.

Now that we've pulled and pushed code with a remote repository it's time get more advanced. One of the more elegant features of Git or any source control is the ability to branch code and work without fear of breaking the original source. With Git's local and remote repositories, the options become even more robust.


Branching Locally:


git branch BRANCHNAME

This command will create a branch called BRANCHNAME in your local repository. After it's created you can use git checkout BRANCHNAME to move between branches and your original master branch in the local repository.

You'll want to create branches when you're making drastic changes to the code that won't be easily rolled back. For example, I was working on our game engine and I wanted to implement the just released 2.1a version of the Box2D physics engine. Doing so would break all our code and it would take a couple of days at least to get it all back up and running. I branched so I could work with the working build while I was fixing up the broken one.

Working With Remote Branches:


Now, what if you want to push this local branch to the remote repository for the rest of your team to see? You can use this push command to create a new branch on the server

git push git@github.com:OWNERNAME/REPOSITORYNAME.git LOCALBRANCH:REMOTEBRANCH

What if someone else creates a branch that you want to keep track of? You can use this command to create a local branch and checkout their code into this new branch.

git branch --track LOCALBRANCH origin/REMOTEBRANCH

The --track argument tells git that any push and pull on this local branch should go to that remote branch. In fact, once you have tracking set up on a branch, simply typing git push or git pull will make Git automatically push or pull for that branch without you having to specify the remote address and which branches you want to work with.

No comments: