4. Branching and Merging
What is a branch?
In Git, a branch represents an independent line of development. Think of it as a way to request a fresh working directory, staging area, and project history. New commits are recorded in the history for the current branch, which results in a fork in the history of the project.
The default branch in Git is named master
. As you make commits, you're given a pointer that moves forward with each new commit. When you create a branch, you're essentially creating a new pointer to the same commit you're on. As you make changes on this branch, the pointer will move forward, independent of other branches.
Branches are useful for:
Developing features
Fixing bugs
Experimenting without affecting the main codebase
Creating branches (git branch
, git checkout
)
git branch
, git checkout
)git branch
is used to manage branches:
To view all branches:
To create a new branch:
git checkout
is used to switch between branches:
To switch to an existing branch:
To create a new branch and switch to it in one command:
In recent versions of Git, you can use git switch
as a more intuitive way to change branches:
To switch to an existing branch:
To create and switch to a new branch:
Merging branches (git merge
)
git merge
)Merging is the process of integrating changes from one branch into another. It's how you combine the separate lines of development created by git branch back into a single branch.
To merge a branch into the current branch:
There are two types of merges:
Fast-forward merge: If the current branch is directly behind the branch you're trying to merge, Git will move the current branch forward to match the merged branch. This type of merge keeps a linear commit history.
Three-way merge: If the branches have diverged, Git will create a new commit that has two parent commits, effectively joining the two branches. This type of merge introduces a new commit and is used when a fast-forward merge is not possible.
Dealing with merge conflicts
Sometimes, when you try to merge branches, changes conflict with each other, and Git can't determine which change should take precedence. This results in a merge conflict.
When a conflict occurs, Git will mark the problematic area in the file:
To resolve the conflict:
Open the file in a text editor.
Decide which version to keep or manually merge the changes.
Remove the conflict markers (
<<<<<<<
,=======
,>>>>>>>
).Save the file.
Stage the file with
git add filename
.Commit the changes with
git commit
.
It's essential to test the merged code to ensure that the conflict resolution didn't introduce any bugs. Some tools and IDEs provide graphical interfaces to help resolve merge conflicts, making the process more intuitive.
Last updated