The Chalkboard


Using Cherry Pick in Git

Last Updated: [2023-03-29 Wed 07:07]

Introduction

When making changes to release branches, you want to ensure that only your approved changes are patched. Here we’re going to take a change that’s in your development branch and apply it to a release branch using the cherry-pick function in git.

Preparation

Firstly, you’ll want to ensure the latest code in your local repo matches the origin code in GitHub. For this, we need to fetch the latest commits from the origin.

git fetch

Now we need the ID(s) of the commit(s) we want to patch from the development branch. Run git log and locate your commit and copy the hash ID(s).

Alternatively, you can go to the commits page on GitHub and click the handy dandy copy commit ID to clipboard button.

If you’re using GitHub’s Hub application, you can run git browse to open your browser to your current branch.

Patching the release

Now you want to check out the release branch you’re targeting (or create it if this is the first patch), and branch off it for your change. You do this by running the following:

git checkout release/<release version>
git pull # This is to ensure you have the latest version of the release branch
git checkout -b patch/<TICKET NUMBER>/release/<release version>

Next we want to use the cherry-pick command to add the commit from the development branch to this branch.

git cherry-pick <<Commit ID>>.

Note: If you’ve cut your branch without pulling in changes, or other changes have gone in since you cut, you should rebase to ensure a smooth pull request experience later. Follow this guide for further information: Rebasing your development branches in Git

Conflicts

In the example above, you can see that in my case, there was a conflict. If this happens, don’t panic, this happens often when patching into older branches. Git will tell you which file(s) have conflicts. Simply open the affected files and fix the conflicts.

Once you’ve resolved the conflict(s), save the file(s) and from the prompt run:

git add -A
git commit

After running the commit command, you’ll be taken to your text editor where you’ll see the commit message of the original commit you cherry-picked. In most cases, just save and quit.

Pushing

Now you can push to your branch using the usual git push origin HEAD command.

Wrapping up

After this has been completed, you can open a pull request from your working branch back to the release branch.


DISCLAIMER: The information provided on this website is generated from my own notes and is provided "as is" and without warranties. Robert Ian Hawdon can not be held responsible for damages caused by following a guide published on this site. This website contains links to other third-party websites. Such links are provided as convienice of the reader. I do not endorce the contents of these third party sites.