Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
690 views
in Technique[技术] by (71.8m points)

git - How to cherry pick only changes for only one file, not the whole commit

I need to apply changes introduced in one branch to another branch. I can use cherry pick to do that. However, in my case I want to apply changes which are relevant only for one file, I don't need to cherry pick whole commit. How to do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have different options based on what you want to achieve:

If you want the contents of the file to be the same as on the target branch, you can use git checkout <branch> -- <filename>. This will however not “cherry-pick” the changes that happened in a single commit, but just take the resulting state of said file. So if you added a line in a commit, but previous commits changed more, and you only want to add that line without those other changes, then a checkout is not what you want.

Otherwise if you want to apply the patch introduced in a commit to only a single file, you have multiple options. You could run git cherry-pick -n, i.e. without committing it, edit the commit (for example reset all files using git reset -- . and only add the file you actually want to change using git add <filename>). Or you could create the diff for the file and apply the diff then:

git diff <branch>^..<branch> -- <filename> | git apply

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...