If you’re working on a new feature, or pushing a bug fix to your site, branching is a great way to ensure you don’t cause any issues with your main version.
In this article, we will cover the concepts of branching and merging; using Git as our version control system in the examples covered.
In this article, we are going to cover 3 commands –
merge. A branch is essentially a version of your app that can work on, for example a development or bug fix branch. Checkout is the process of switching from one branch to another, so you don’t make changes to the wrong version of your site. Finally, merge brings two different branches into one, effectively creating a single version of your site from two different versions.
Let’s now look at using these commands in the context of maintaining and improving our site.
Lets say that our website is live and online, but we would like to add a new feature, let’s say a shopping cart so our customers can start buying our product.
We will create a new branch called
$ git checkout -b cart Switched to a new branch 'cart'
This creates a new branch called cart and automatically switches to it, ready to start working on. That command is shorthand for the following:
$ git branch cart $ git checkout cart
So now we have two branches, our main branch, referred to as
master, and our newly created
We are now working in our cart branch, and unfortunately we found a bug on our live site. At this point, we should create a new branch:
$ git checkout -b bugfix Switched to a new branch 'bugfix'
We can work on our fix without disturbing the site, and commit it to our bugfix branch:
$ git commit -m "fixed the bug" [bugfix 54sdwe] fixed bug 1 file changed
And now push the branch to our remote repository:
$ git push -u origin buxfix * [new branch] bugfix -> bugfix Branch bugfix set up to track remote branch bugfix from origin
We have tested the fix and we are happy, so let’s merge this change into master. But first, we need to switch back to our master branch:
$ git checkout master Switched to branch 'master' Your branch is up-to-date with 'origin/master'
Now we can merge our bugfix:
$ git merge bugfix Updating fb3af6..54sdwe Fast-forward index.html | 1 1 file changed
And push to GitHub:
$ git push origin master Total 0 (delta 0), reused 0 (delta 0) to firstname.lastname@example.org:bhavik/website-project/repository.git fb3af6..54sdwe master -> master
Everything looks good, and the bug is now fixed and deployed. Let’s remove our bugfix branch:
$ git branch -d bugfix Deleted branch bugfix (was 54sdwe)
We will want to remove the branch from our remote repository as well.
$ git push origin --delete bugfix To email@example.com:bhavik/website-project/repository.git - [deleted] bugfix