The Lightweight Nature of Branches
In many older VCS, branching involved creating a full copy of the source code—which was slow and expensive. In Git, a branch is simply a lightweight, movable pointer to one of the commits in the repository. The default branch name is usually main. When you create a new branch, Git creates a new pointer; it does not duplicate any file content.
Each pointer is a tiny file (41 bytes) containing the 40-character SHA-1 checksum of the commit it points to.
Creating and Switching Branches
To create a new branch named testing:
git branch testing
However, creating a branch does not switch you to it. To start working on that branch, you must “check it out” or “switch” to it:
git switch testing
(Note: In older tutorials, you will see git checkout -b testing. Modern Git recommends git switch as it is more intuitive.)
The Mechanics of Merging
Merging is the process of bringing changes from one branch into another. There are two primary types of merges you will encounter.
1. Fast-Forward Merge
If the branch you are merging into is a direct ancestor of the branch you are merging (i.e., there have been no other commits on the base branch), Git simply moves the pointer forward. No new commit is created.
git switch main
git merge feature-x
2. Three-Way Merge
If the history has diverged (i.e., both main and feature-x have new, different commits), Git performs a three-way merge. It looks at three snapshots:
- The common ancestor (the “Base”).
- The tip of Branch A.
- The tip of Branch B.
Git creates a new “Merge Commit” that has two parents.
Introduction to Merge Conflicts
A conflict occurs when the same line of the same file was modified in both branches being merged. Git will stop and ask you to resolve the conflict manually.
<<<<<<< HEAD
printf("Hello from Main\n");
=======
printf("Hello from Feature\n");
>>>>>>> feature-x
You must edit the file, choose the correct version (or combine them), remove the markers, and then git add and git commit to complete the merge.
What actually happens when you create a new branch in Git?
Switching and Creating
# Create and immediately switch to 'dev' branch git switch dev
Visualizing Branches
Waiting for signal...