In previous blog post in this series, we discussed about concept of git branching. We saw how and why it is easy to create a new branch in Git compared to other versioning tools. We also discussed concept of HEAD in more depth and how it is useful to keep track of current status. In this blog post, we are going to explore more on the branching concept.
View current branch in Git and Visual Studio
This can be viewed simply by running either ‘git branch’ or ‘git log’ command. If we run first command, the current branch is highlighted by an asterisk(*) just next to it. Similarly, if we run second command, it will be highlighted by position of HEAD:
If we open our project in Visual Studio, Go to team explorer and then see branches, we would see something like below:
We can find that current branch is highlighted in more bold color.
Switch current branch in Visual Studio
Let’s say we want to switch back to master branch to work on some issue. In this case, we can checkout master branch by either double-click on it or by right click and then select checkout:
Once it switches, now master branch is highlighted in bold to inform that HEAD is now pointing to master branch.
Create new branch in Visual Studio
We have already learned how to create new branch using command line in previous post. If we need to create new branch in Visual Studio, we can do same from the new branch option:
It will ask us few things like name of new branch, base branch you want to copy from and if you want to checkout new branch at the same time:
The equivalent of creating new branch and simultaneously switching to it in git command line is using ‘git checkout -b <new-branch-name>’.
Do note that you can not switch to another branch if you have uncommitted changes or stashed changes that conflict with the branch you’re checking out, Git won’t let you switch branches. It’s best to have a clean working state when you switch branches.
Delete a branch in Git and Visual Studio
To delete a branch inside Visual Studio, we can simply right click the branch and then select delete:
Do note that we can delete current checked out branch. We can only delete other branches either by git or Visual Studio:
Visual Studio enforce this behavior by disabling the delete option from current checked out branch.
The equivalent for deleting branch using git command line is ‘git branch -d <branch-name>’ . One can also use -D which is equivalent of –delete –force: