Codingdomain.com

Git: Branches

Working in parallel

So far, all commits appeared in a single line. It is possible to have multiple lines of development, each line for a separate feature. This is called a branch, and it can be used to develop multiple features at the same, or making fixes for older editions of the software while working on the next version.

When a branch is started, the chain of commits is no longer grows in a straight line, but in two:

Commits diverge in branches

To keep track of all commits, each branch is referenced by a label. The "mainline" branch is called master.

A label references a commit

In Git, branches are often used to develop separate features. Only once the feature is stable, it will be integrated with the main line of development.

Starting a branch

Branches are started with the following commands:

Making a branch, and committing it in:
git branch iss53      # create the branch (see figure 1)
git checkout iss53    # switch to it

...                  # edit a file

git commit -a        # commit the change in the new branch (see figure 2)

The following will happen:

1: A new branch is created 2: A commit is added to the branch

Returning to the master branch

With the git checkout command, we can switch back to the master branch.

Switching back to master:
git checkout master

Each time you switch between branches, the files in your working copy are replaced with the versions from the particular branch you checkout.

From the master branch, another commit can be created.

Adding a commit in the master branch:
edit file2.html
git commit -a

And notice how things start to diverge:

Result after making a new commit in the master branch

Keeping overview

To keep an overview, the following commands are recommended:

Keeping an overview of branches:
git branch                         # shows a list of local branches
git log --all --graph --decorate   # show commits as graph with labels

I can recommend making an alias of that one:

Useful aliases for branches:
git config --global  alias.log-graph "log --all --graph --decorate"

Notice how that command displays the branch label at the final commit. Git deals with branches this way; they are just a label pointing to the last commit of the chain.

Convenience tip

Instead of typing:
git branch name
git checkout name

you can do this at once with:
git checkout -b name

Next: merging

When a feature is completed, the next task is merging a branch.

blog comments powered by Disqus

Footnotes

The figures are used from the Pro Git book, chapter 3.2, which explains branches very well.