How to merge specific files from Git branches

后端 未结 11 1870
长发绾君心
长发绾君心 2020-11-30 16:23

I have 2 git branches branch1 and branch2 and I want to merge file.py in branch2 into file.py in branch1 and only that file.

In essence I just want to work on the fi

11条回答
  •  生来不讨喜
    2020-11-30 16:37

    None of the other current answers will actually "merge" the files, as if you were using the merge command. (At best they'll require you to manually pick diffs.) If you actually want to take advantage of merging using the information from a common ancestor, you can follow a procedure based on one found in the "Advanced Merging" section of the git Reference Manual.

    For this protocol, I'm assuming you're wanting to merge the file 'path/to/file.txt' from origin/master into HEAD - modify as appropriate. (You don't have to be in the top directory of your repository, but it helps.)

    # Find the merge base SHA1 (the common ancestor) for the two commits:
    git merge-base HEAD origin/master
    
    # Get the contents of the files at each stage
    git show :path/to/file.txt > ./file.common.txt
    git show HEAD:path/to/file.txt > ./file.ours.txt
    git show origin/master:path/to/file.txt > ./file.theirs.txt
    
    # You can pre-edit any of the files (e.g. run a formatter on it), if you want.
    
    # Merge the files
    git merge-file -p ./file.ours.txt ./file.common.txt ./file.theirs.txt > ./file.merged.txt
    
    # Resolve merge conflicts in ./file.merged.txt
    # Copy the merged version to the destination
    # Clean up the intermediate files
    

    git merge-file should use all of your default merge settings for formatting and the like.

    Also note that if your "ours" is the working copy version and you don't want to be overly cautious, you can operate directly on the file:

    git merge-base HEAD origin/master
    git show :path/to/file.txt > ./file.common.txt
    git show origin/master:path/to/file.txt > ./file.theirs.txt
    git merge-file path/to/file.txt ./file.common.txt ./file.theirs.txt
    

提交回复
热议问题