Git: Apply part of a commit to another branch

Git

Git Problem Overview


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?

Git Solutions


Solution 1 - Git

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.

Solution 2 - Git

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbhiView Question on Stackoverflow
Solution 1 - GitdahlbykView Answer on Stackoverflow
Solution 2 - GitAlexView Answer on Stackoverflow