Sunday, June 22, 2008

Working with remote Git branches

You are about to start a brand new module in your project. Your project is already in production. You cannot develop and test your new module while fixing minor bugs in your production line. You need branching.

So suppose we are on master branch and you have remote "origin" repository. And we need to create a new remote branch called "search" to track the development of the search module. the plan is to develop the search module on this branch "search" locally and push updates remotely for testing on a staging server or just to share the search module code with a colleague developer without polluting the master production branch with the unfinished yet search module.

First make sure your master branch are up to date.
$ git pull origin master
Then push your master branch to a new remote branch, notice that you enter the destination remote repository name first "origin" then the source which is local branch "master" then a column ":" and the path of the new remote branch we want to create "refs/heads/search"
$ git push origin master:refs/heads/search
After pushing and creating the remote "search" branch, we will examine the remote "origin.
$ git remote show origin
* remote origin
URL: ssh://ibrahim@kenana.org/git/portals.git
Remote branch(es) merged with 'git pull' while on branch master
master
New remote branches (next fetch will store in remotes/origin)
search
Tracked remote branches
master
Notice how there is a new remote branch and that next time we use "git fetch" the new remote branch "search" will be stored in remotes/origin.
$ git fetch
* refs/remotes/origin/search: storing branch 'search' of ssh://ibrahim-ahmed.com/git/portals
commit: 8bd83c4
Now we have all the remote origin branches stored locally in "refs/remotes/origin" including "search" branch, but there is no local branch yet to track it.

To make a branch out of the remote branch which is stored locally, we will use "git checkout", the "-b" search" is the argument we use to create a local branch. "--track" parameter is used to link the local branch "search" with the remote branch "origin/search"
$ git checkout --track -b search origin/search
Now you should be on "search" branch.
$ git branch
master
* search
Now you can edit, commit, pull and pull to your heart content. And when you need to fix something on remote/master which is used for production server, you just use the following to fix the bug, push to the remote master and then back again to your search module.
$ git checkout master
$ vim files_to_be_fixed
$ git commit -a -m "just fixed the bug"
$ git push origin master
$ git checkout search
Check SourceMage Git manual for further advanced usage examples.

1 comment:

dacc said...

Thanks for this post! Very helpful.