Thursday, July 21, 2016

Git Branches for the Impatient


You are working in a small colocated development team and decided to use branches to implement new features or fix errors. Here the cookbook to create, edit, merge and delete local and remote branches in Git (version 2.x).
Git branches have two important qualities
- A branch is like an idea. Once you implemented the idea, feature or fix you just delete the branch,
- The history of the branch commits is still visible upon deletion of the branch.

You should use meaningful names for your branch name and associated commit messages. Put the ticket number into the branch name and messages for future searches. 

A lot of servers support keywords such "fix #42" to automatically close the ticket 42.

The described approach is optimal for small teams. The approach is compatible to pull requests if you introduce later such a workflow. If you are working colocated you do not need pull requests. I prefer pair programming and pair check-in sessions.

For a short introduction how to start using Git in software projects see previous blog "Git Local Repositories for the Impatient".

Create the Branch

Create new branch feat_#42 locally
git checkout -b feat_#42

Create the remote branch with the same name and initiate tracking
git push -u origin feat_#42

Work on the Branch

Do some changes and commit them regularly
git commit -a -m “commit message describing activities for feat_#42“

Push the changes to repository
git push

Now you can test the branch from the central repository and deploy it to a continuous integration server or a test environment.

Merge the Branch

Switch to master and synchronize with repository, the -p parameter means --prune
git checkout master
git fetch --all -p
git pull

Merge to master. The option --no-ff will always keep branch information
git merge --no-ff feat_#42

Or if you want a single commit for the complete branch
git merge —squash —no-ff feat_#42

Push the changes
git push

Delete the Branch

Delete the remote branch (also git branch -dr origin/feat_#42)
git push origin --delete feat_#42

Delete the local branch
git branch -d feat_#42

You are done. Now you are ready to implement the next feature.

View local and remote Branches

If you want to view branches use the following commands for the local branches

git branch
git branch --no-merged

If you want to view remote branches

git branch -r

git branch -r --no-merged

Checkout remote Branch

The -p parameter means --prune

git fetch --all -p

git checkout #feat_42

More Information

You can find a lot of information on Stack Overflow. Beware that the Git commands have changed over time. Select new posts to find the best answers. The nitty-gritty details can be found in the official Git documentation.

Beware that for example gitolite does not support special characters such as # in branch names. Use them only in the commit messages. These same characters work in bitbucket

No comments:

Post a Comment