You've been working diligently on your new feature in its own branch. Now, it's time to integrate those brilliant changes back into the main line of development, typically your main (or master) branch. This process is called merging.
Merging takes the commit history from one branch and applies it to another. Git is smart enough to figure out how to combine these histories, especially when the branches haven't diverged too much.
The most common scenario is merging a feature branch back into main. Before you merge, it's a good practice to ensure your main branch is up-to-date with any changes that might have happened there since you created your feature branch. This helps minimize merge conflicts.
git checkout main
git pull origin mainNow, you're ready to merge your feature branch into main. Make sure you are on the branch you want to merge into (usually main).
git checkout mainThen, you'll use the git merge command, specifying the name of the branch you want to bring in.
git merge your-feature-branch-nameIf there are no conflicts, Git will often perform a 'fast-forward' merge. This means that main simply moves its pointer forward to the latest commit on your feature branch, as if your feature branch's commits were made directly on main. If main had new commits since you branched, Git will create a new 'merge commit' to tie the two histories together.
graph TD
A[Initial Commit] --> B{Feature Branch}
A --> C[Main Branch]
B --> D[Feature Commit 1]
D --> E[Feature Commit 2]
C --> F[Main Commit 1]
F --> G[Merge Commit]
E --> G
Merge conflicts can occur when Git can't automatically figure out how to combine changes from two branches. This happens when the same lines of code have been modified in different ways on both branches. Git will pause the merge and let you know there's a conflict. You'll need to manually resolve these conflicts by choosing which changes to keep.
Once you've resolved any conflicts, you'll stage the changes and complete the merge.
git add .
git commitAfter a successful merge, your feature branch's changes are now part of the main branch. You might choose to delete your feature branch if it's no longer needed, keeping your repository clean.
git branch -d your-feature-branch-name