Git concepts: branch
A Git branch, much like a commit, is also a crucial concept in the Git version control system. To understand it fully, we need to delve into how Git treats and uses branches internally.
Essentially, a branch in Git is a movable pointer that always points to the most recent commit. When you create a branch, Git creates a pointer to the same commit you're currently on. This branch pointer moves along with each new commit you make.
By default, Git has a main branch called main
(or master
in older versions). Whenever you make a commit, the main
pointer moves forward automatically. When you create a new branch, say feature
, a new pointer is created at the current commit. As you make commits on this branch, only the 'feature' pointer moves forward, leaving 'master' untouched.
The branch name, such as main
or feature
, is just a human-readable label for the underlying commit pointer. In other words, a branch represents the tip of a series of commits - it's just a reference to a specific commit.
Branches are incredibly lightweight. They are simple files that contain a 40-character SHA-1 checksum of the commit it points to. Because of this, creating new branches is a very fast and simple operation.
Moreover, switching between branches ('checking out' branches in Git terms) is equally swift. When you checkout to a different branch, Git simply changes the HEAD
pointer to refer to the new branch, updates the working directory to match the snapshot of the commit the new branch is pointing at, and voila - you've switched the branch!
Branching enables isolated development environments within the repository. You can work on new features, bug fixes, experiments, etc., without affecting the main codebase. Once the work on a branch is complete and tested, it can be merged back into the main codebase.