Codingdomain.com

Git: Merging things together

Merging changes

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.

A branch with a completed feature.

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":

After the merge

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.

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

Aborting conflicts

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

Backporting commits

To selectively copy some bugfixes to another branch, there is a special command:

Cherry-picking a commit:
git checkout master      # switch to the destination
git log branchname        # find the commit to copy
git 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.

Useful parameters

Some notable parameters of the cherry-pick command are:

-e, --editEdit the commit message before applying it.
-xAutomatically add a notice to the commit message about the cherry-pick. This useful for public branches.
-n, --no-commitKeep the changes in the staging area, to allow more changes or cherry-picks in one commit.
-s, --signoffAdd 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.

blog comments powered by Disqus

Footnotes

The figures are used from the Pro Git book, chapter 3.2, which explains branches very well.