62

How can I apply part of a commit from one branch to another? I understand that I can cherry-pick a commit, but I need to go one step further and "cherry pick" some of the changes introduced by that commit and apply them to another (target) branch.

Is there a clean way to do this, or should I just apply the entire commit, manually undo some hunks, and remember to create more atomic commits in the future?

Abhi
  • 1,117
  • 2
  • 10
  • 15
  • 3
    possible duplicate of [partly cherry-picking a commit with git](http://stackoverflow.com/questions/1526044/partly-cherry-picking-a-commit-with-git) – jweyrich Jul 08 '11 at 00:44

2 Answers2

91

git cherry-pick -n <SHA> will stage the changes but not commit them. You can then use git reset -p to unstage the bits you don't want, or git reset HEAD and git add -Ap to stage only the changes you want.

dahlbyk
  • 75,175
  • 8
  • 100
  • 122
  • 1
    applying the 'git cherry-pick -n ' and then typing git status will also offer a description on how to dismiss the files of the cherry-picked commit, that you would like to reset. – Simeon Feb 05 '21 at 10:57
16

If the parts you want to apply can be specified by path (i.e., you do not wish to specify hunks within one file) another solution is possible.

One approach is to form a patch from the commit, and apply it to your branch.

With the branch you wish to modify checked out:

git show <SHA> -- <relevant paths> | git apply

Will apply any changes in commit SHA, in paths relevant paths to your current working copy.

Alex
  • 1,306
  • 3
  • 15
  • 25