One of the advantages of small commits is that you can be picky about which ones you want to merge.
This problem particularly concerns long-lived branches, that have become out of date with the main branch resulting in too many conflicts to simply merge. This is a very common occurrence on very active open source projects.
When this occurs you want to be able to pick out individual commits and simply merge those into the main branch.
The environment has been configured with a repository containing a HTML list which has been developed in a separate branch. In this scenario we'll pick certain commits from this branch which we want to end up in master.
When the problem arises, cherry picking is an extremely useful technique that is often forgotten. It's important to note that cherry picking only works if you keep your commits small and focused, otherwise you'll include unwanted changes. This is an important aspect to remember on a daily basis when working with Git.
This scenario has been added to your scrapbook where you can review the examples and commands you executed.
Scenario 8 - Being Picky With Git
Step 1 - Cherry Picking
In this scenario we have a number of commits in the _newbranch which has created two html files. In this scenario we only care about changes to one of the files but if we merged the branch then we'd merge all five commits and the unwanted changes.
To merge individual commits we use the
git cherry-pick <hash-id|ref> command. This behaves in a similar way to merge, if no conflicts exist then the commit will be automatically merged.
Follow the steps below to merge the three commits we're interested in. We want to replay the commits in the order they happened in the original repository.
- Cherrypick the commit with the message "Initial commit, no items"
- Cherrypick the commit with the message "Initial list"
- Cherrypick the commit with the message "Adding final items to the list"
We've used HEAD previously to indicate the tip of the current branch. You can refer across branches using the syntax _
new_branch~3 refers to the second to-last commit in the branch, in this case it has the commit message "Initial commit, no items"