If I want to merge into a Git branch the changes made only to some of the files changed in a particular commit which includes changes to multiple files, how can this be achieved?
Suppose the Git commit called stuff
has changes to files A
, B
, C
, and D
but I want to merge only stuff
's changes to files A
and B
. It sounds like a job for git cherry-pick
but cherry-pick
only knows how to merge entire commits, not a subset of the files.
Cherry pick is to pick changes from a specific "commit". The simplest solution is to pick all changes of certain files is to use
In example:
Sources and full explanation http://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/
UPDATE:
With this method, git will not MERGE the file, it will just override any other change done on the destination branch. You will need to merge the changes manually:
I found another way which prevents any conflicting merge on cherry-picking which IMO is kind of easy to remember and understand. Since you are actually not cherry-picking a commit, but part of it, you need to split it first and then create a commit which will suit your needs and cherry-pick it.
First create a branch from the commit you want to split and checkout it:
Then revert previous commit:
Then add the files/changes you want to cherry-pick:
and commit it:
note the commit hash, let's call it PICK-SHA and go back to your main branch, master for example forcing the checkout:
and cherry-pick the commit:
now you can delete the temp branch:
I'd do it with
cherry-pick -n
(--no-commit
) which lets you inspect (and modify) the result before committing:If the vast majority of modifications are things you don't want, instead of checking out individual paths (the middle step), you could reset everything back, then add in what you want:
The other methods didn't work for me since the commit had a lot of changes and conflicts to a lot of other files. What I came up with was simply
It doesn't actually
add
the files or do a commit for you so you may need to follow it up withOr if you want to skip the add you can use the
--cached
argument togit apply
The situation:
You are on your branch, let's say
master
and you have your commit on any other branch. You have to pick only one file from that particular commit.The approach:
Step 1: Checkout on the required branch.
Step 2: Make sure you have copied the required commit hash.
Step 3: You now have the changes of the required file on your desired branch. You just need to add and commit them.
Perhaps the advantage of this method over Jefromi's answer is that you don't have to remember which behaviour of git reset is the right one :)