Merge
The merge command can sometimes confuse students early on. Remember these two merging concepts:
- We merge branches, not commits.
- We always merge to the current HEAD branch.
To merge, follow these two steps:
- Switch to or checkout the branch you want to merge the changes into (the receiving branch)
- Use the
git merge
command to merge changes from a specific branch into the current branch.
To merge the bugfix branch into master:
- Switch to the master branch
git switch master
(see how head moved!)
- And merge bugfix into master
git merge bugfix
This is called a Fast-Forward Merge
In other words, master just caught up on bugfix
(See how HEAD moved again!)
But not all merges are Fast-Forward
.
This is what happens when we (or a colleague) committed on master:
This is an extremely common situation!
Then you try to merge, but master cannot perform a fast-forward merge
We end up with a merge commit and git will ask you to enter a commit message:
Merge Conflicts
Depending on the specific changes your are trying to merge, Git may not be able to automatically perform the merging. This results in merge conflicts, which you need to manually resolve.
When git encounters a merge conflict, it warns you in the console that it could not merge automatically.
It also changes the contents of your files to indicate the conflicts that it wants you to resolve.
<<<<<<< HEAD
This is is code
in the branch RECEIVING
=======
This is conflicting code
from the branch I'm trying to merge
>>>>>>> bugfix
Code contained between <<<<<<< HEAD
and =======
belongs to the receiving branchit.
Code between =======
and >>>>>>> <branch-name>
belongs to the merging branch
Resolving Conflicts
Whenever you encounter merge conflicts, follow these steps to resolve them:
- Open the file or files with conflicts
- Edit the file(s) to remove the conflicts. Decide which branch's content you want to keep. Or even keep the content from both branches.
- Remove all conflict markers (
<<<<<<< HEAD
-=======
and>>>>>>> <branch-name>
) - Save the file(s), add it (them) (
git add <file(s)>
) and make a commit.
Deleting Branches
To delete the branch bugfix
:
git branch -d bugfix