How do I merge changes to a single file, rather than merging commits?

我有两个分支(A和B),我想将分支A中的单个文件与分支B中相应的单个文件合并。


I came across the same problem. To be precise, I have two branches A and B with the same files but a different programming interface in some files. Now the methods of file f , which is independent of the interface differences in the two branches, were changed in branch B , but the change is important for both branches. Thus, I need to merge just file f of branch B into file f of branch A .

A simple command already solved the problem for me if I assume that all changes are committed in both branches A and B :

git checkout A

git checkout --patch B f

The first command switches into branch A , into where I want to merge B 's version of the file f . The second command patches the file f with f of HEAD of B . You may even accept/discard single parts of the patch. Instead of B you can specify any commit here, it does not have to be HEAD .

Community edit: If the file f on B does not exist on A yet, then omit the --patch option. Otherwise, you'll get a "No Change." message.


Here's what I do in these situations. It's a kludge but it works just fine for me.

  • Create another branch based off of your working branch.
  • git pull/git merge the revision (SHA1) which contains the file you want to copy. So this will merge all of your changes, but we are only using this branch to grab the one file.
  • Fix up any Conflicts etc. investigate your file.
  • checkout your working branch
  • Checkout the file commited from your merge.
  • Commit it.
  • I tried patching and my situation was too ugly for it. So in short it would look like this:

    Working Branch: A Experimental Branch: B (contains file.txt which has changes I want to fold in.)

    git checkout A
    

    Create new branch based on A:

    git checkout -b tempAB
    

    Merge B into tempAB

    git merge B
    

    Copy the sha1 hash of the merge:

    git log
    
    commit 8dad944210dfb901695975886737dc35614fa94e
    Merge: ea3aec1 0f76e61
    Author: matthewe <matthewe@matthewe.com>
    Date:   Wed Oct 3 15:13:24 2012 -0700
    
    Merge branch 'B' into tempAB
    

    Checkout your working branch:

    git checkout A
    

    Checkout your fixed-up file:

    git checkout 7e65b5a52e5f8b1979d75dffbbe4f7ee7dad5017 file.txt
    

    And there you should have it. Commit your result.


    You could use:

        git merge-file
    

    Tip: https://www.kernel.org/pub/software/scm/git/docs/git-merge-file.html

    链接地址: http://www.djcxy.com/p/45040.html

    上一篇: 你如何维护开发代码和生产代码?

    下一篇: 如何将更改合并到单个文件中,而不是合并提交?