Merging in Git is the process of integrating changes from one branch into another. It’s a critical operation in collaborative workflows to combine the work of different contributors or merge feature branches into the main codebase.
Merging takes the changes made in one branch and applies them to another. The most common scenario is merging a feature branch into the main
branch after development is complete.
- Fast-Forward Merge: Applies changes directly when there’s a linear path between the branches.
- Three-Way Merge: Creates a merge commit when the branches have diverged.
-
Switch to the branch you want to merge into (e.g.,
main
):git checkout main
-
Merge the feature branch:
git merge feature_branch
If there are no conflicts, Git will fast-forward the branch pointer to include the changes.
A three-way merge is needed when the branches have diverged.
-
Switch to the branch you want to merge into:
git checkout main
-
Merge the feature branch:
git merge feature_branch
-
If there are conflicts, resolve them manually (see below).
A merge conflict occurs when changes in two branches affect the same part of a file.
-
Identify the conflicting files:
git status
-
Open the conflicting files and look for conflict markers:
<<<<<<< HEAD Your changes ======= Changes from the other branch >>>>>>> feature_branch
-
Edit the file to resolve the conflict and remove the markers.
-
Mark the conflict as resolved:
git add file_with_conflict
-
Complete the merge:
git commit
If you decide not to proceed with a merge:
git merge --abort
This will return the branch to its original state before the merge began.
To see merges in the commit history:
git log --oneline --graph
git checkout -b feature/new-feature
echo "New feature" > feature.txt
git add feature.txt
git commit -m "Add new feature"
git checkout main
git merge feature/new-feature
git branch -d feature/new-feature
- Pull Latest Changes: Before merging, ensure your branch is up to date with the target branch:
git pull origin main
- Test After Merging: Verify that the code works as expected after a merge.
- Communicate Conflicts: If conflicts arise, collaborate with the team to resolve them effectively.
Command | Description |
---|---|
git merge branch_name |
Merge the specified branch into the current branch. |
git merge --abort |
Abort a merge in progress. |
git log --oneline --graph |
View a graphical history of commits and merges. |
git status |
Identify conflicting files during a merge. |
Merging changes is a fundamental Git operation for integrating code from different branches. By understanding merge strategies and conflict resolution, you can ensure a smooth and efficient workflow.
Next Steps: Resolving Merge Conflicts