Git: Merging things together
Once a new feature in a branch is completed, the next task is merging it into the "mainline". This happens with the git merge command.
By developing features in separate branches, the mainline can remain relatively stable; only finished parts are integrated.
The merge command
In this case, the iss53 needs to be integrated to the master branch:
- Merging the iss53 branch:
git checkout master git merge iss53
The result is the combination of both branches, displayed as "C6":
Cleaning things up
The branch label is still appears in the picture above. It's possible to continue working on the branch, and merge the new commits later. Git will know where to continue merging next time.
Otherwise, just delete the branch label:
- Deleting a branch:
git branch -d iss53
Dealing with conflicts
In case Git can't merge two branches together automatically, it asks to resolve conflicting changes manually.
- All succesfully merged parts will be added to the staging area.
- The conflicting parts are left in the working tree to fix.
These files contain both changes; with <<< markers to identify them. After correcting the files, the remaining changes have to be staged and committed.
- Telling git about resolved changes:
git add corrected-files git commit
# commit the merge
At any time, you can abort the merge, by forcefully switching back to the last valid commit:
- Aborting a merge conflict:
git reset --hard HEAD
To selectively copy some bugfixes to another branch, there is a special command:
- Cherry-picking a commit:
git checkout master
# switch to the destinationgit log branchname
# find the commit to copygit cherry-pick commit
# apply the commit
The changes of the commit will be applied to the current branch.
Note that the commits will be duplicated. When both branches are merged, Git deals with this automatically.
Some notable parameters of the cherry-pick command are:
|-e, --edit||Edit the commit message before applying it.|
|-x||Automatically add a notice to the commit message about the cherry-pick. This useful for public branches.|
|-n, --no-commit||Keep the changes in the staging area, to allow more changes or cherry-picks in one commit.|
|-s, --signoff||Add a signoff line, this is required for the Linux kernel (more info).|
Generally, the recommended syntax would be:
- Recommended cherry-pick usage:
git cherry-pick -x commit
Coming up next
When switching between branches, local changes sometimes need to be put aside. An easy tool for that is git stash.
The figures are used from the Pro Git book, chapter 3.2, which explains branches very well.