Whenever there is a commit in master branch, then commit should be automatically cherry-picked to another branch

Is there any way to by which if there is a commit in master branch, then commit should automatically cherry-picked to another branch in the same project.

Hey @jainsameer04 ,

Cherry-picking is a way of moving a specific commit from one branch and applying it to another. It’s a useful tool if you have a specific issue or committed to the wrong branch or want to copy over changes for testing, but isn’t recommended to be a best practice. You might run into merge conflicts that you’ll need to review manually.

If you really need to copy over commits from one branch to another, I recommend using some kind of pre-commit logic or adding steps in your CI that clone the branch (or commits) to another branch.

I second @sugaroverflow in recommending to use some type of pre-commit or other hook for this task.

As an example, we have a latest-feature branch that attempts to mirror the latest change committed. To accomplish this task we use a post-commit git hook that runs the following script after a successful commit:

#!/usr/bin/sh 
# A simple script to checkout the latest-feature branch 
# and update it to the latest copy.
CURR=$(git branch --show-current)

git checkout latest-feature 
git pull origin latest-feature 
git merge $CURR
git push origin latest-feature
git checkout $CURR

In your project directory simply add this script to .git/hooks/post-commit, with name post-commit. Make it executable via chmod +x .git/hooks/post-commit. On your next commit you will be copying changes to latest-feature, using my example. I’m guessing you can modify this to fit what you need.

Hope this helps!

2 Likes