简体   繁体   中英

How can I merge a specific file from one branch into another branch in Git

I have 2 branches in a git repo, lets call them, dev and test. I have changes in a single file, somecode.js. Both branches have changes to somecode.js. The 2 branches have diverged significantly (but manageably) so a straight "merge" is insufficient.

I have tried http://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/ but it doesn't merge the contents of both files. You basically just write over the file instead of actually merging the contents of the file.

I have also tried:

git checkout -b newbranch
git checkout test somecode.js
git commit -m "somecode changes from newbranch"
git checkout dev
git merge newbranch

And

git checkout -m test somecode.js

(I was really hopeful with the -m for merge, but it didn't appear to work for me...)

I thought I was close to what I needed, but then I realized that it just fast-forwarded the commit meaning it didn't merge, it wrote over the original file in test.

So, to reiterate, how can I merge a specific file from one branch into another branch without just writing over the file in the branch I am merging into using git.

I think you like to use

git checkout -p

In your case

git checkout dev
git checkout -p test somecode.js

And you can interactively apply the diffs.

git checkout dev
git show test:somecode.js > somecode.js.theirs
git show $(git merge-base dev test):somecode.js > somecode.js.base
git merge-file somecode.js somecode.js.base somecode.js.theirs 

This way you'll manually make a three-way merge from somecode.js on test branch into somecode.js on dev branch.

Or.. You can create a temporary branch with the changes you want and make a squash merge from it. Is it 'git way' enough? :)

git checkout -b test/filtered $(git merge-base dev test)
git diff ..test -- somecode.js | git apply
git add -- somecode.js
git commit -m "Updated somecode.js"
git checkout dev
git merge --squash test/filtered
git branch -D test/filtered

I think git merge-file is what you're looking for. From the man page:

git merge-file incorporates all changes that lead from the <base-file> to
<other-file> into <current-file>. The result ordinarily goes into <current-file>.
git merge-file is useful for combining separate changes to an original. Suppose
<base-file> is the original, and both <current-file> and <other-file> are
modifications of <base-file>, then git merge-file combines both changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM