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.
I would just cherry-pick everything, then do this:
Then I would revert the changes I don't want, then make a new commit.
Use
git merge --squash branch_name
this will get all changes from the other branch and will prepare a commit for you. Now remove all unneeded changes and leave the one you want. And git will not know that there was a merge.I usually use the
-p
flag with a git checkout from the other branch which I find easier and more granular than most other methods I have come across.In principle:
example:
You then get a dialog asking you which changes you want in "blobs" this pretty much works out to every chunk of continuous code change which you can then signal
y
(Yes)n
(No) etc for each chunk of code.The
-p
orpatch
option works for a variety of commands in git includinggit stash save -p
which allows you to choose what you want to stash from your current workI sometimes use this technique when I have done a lot of work and would like to separate it out and commit in more topic based commits using
git add -p
and choosing what I want for each commit :)Merge a branch into new one (squash) and remove the files not needed: