Merging is the operation that integrates the changes from one Git branch into another. This is how the work completed in a feature branch (e.g., new-feature) is brought back into the stable main branch.
1. The Merge Process
Merging requires two steps:
- Switch to the Target Branch: You must first move to the branch where you want the changes to end up. If you are merging a feature into
main, you must be on themainbranch. - Run the Merge Command: You execute
git mergeand specify the source branch (the one with the new changes).
Execution Example
Assume you have completed work on a branch named feature/login.
- Switch to the main branch:
git checkout main - Merge the feature branch into main:
git merge feature/login
2. Types of Merges
Git performs different types of merges automatically, depending on the commit history:
Fast-Forward Merge
- When it happens: If the target branch (
main) has not diverged (had any new commits) since the source branch (feature) was created. - Result: Git simply moves the target branch pointer forward to the last commit of the source branch. No new merge commit is created. This keeps the history linear.
Three-Way Merge (Recursive Merge)
- When it happens: If both the target branch and the source branch have new commits since the time they split (they have diverged).
- Result: Git identifies a common ancestor commit (the point where they diverged) and uses the changes from both branches to create a brand new commit, called a Merge Commit. This commit records the act of combining the two histories.
3. Dealing with Merge Conflicts
A Merge Conflict occurs when Git cannot automatically figure out how to combine changes because the same lines of code were modified differently in both branches being merged.
Steps to Resolve a Conflict
1. Identify the Conflict: When you run git merge, Git will stop and inform you which files have conflicts. Running git status will show these files.
Edit the File: Open the conflicted files. Git inserts conflict markers: <<<<<<<, =======, and >>>>>>>.
<<<<<<< HEAD (or main)
This is the line on the current branch.
========
This is the line on the branch being merged.
>>>>>>> feature/login
2. Resolve: Manually edit the file, removing the conflict markers and keeping only the code you want.
3. Stage the Resolution: After editing, use git add to mark the file as resolved.Bashgit add conflicted-file.js
4. Complete the Merge: Run git commit to create the merge commit (Git provides a default message which you should keep or edit).Bashgit commit
4. Deleting Branches
After successfully merging a feature branch into main, you should usually delete the feature branch to keep your repository clean.
Deleting a Local Branch
The -d flag deletes a local branch only if it has already been merged.
git branch -d feature/login
To force delete a branch (even if it’s unmerged—use with caution):
git branch -D feature/login
