'git diff': Show only diff for files that exist in both commits

前端 未结 2 1982
悲哀的现实
悲哀的现实 2021-02-02 11:55

Is there a way to use git diff to get a diff between two commits, but only show the diff for the files that exist in both commits?

I have a branch I created

相关标签:
2条回答
  • 2021-02-02 12:14

    The existing answer, instead of showing modifications only in files that exist in both commits, it shows a diff of ALL modified files in both commits. Say, for example, one commit had 2 files modified and another has 1000, according to the question, the diff should contain <=2 files but the other solution shows 1002 files in the diff!


    Working Solution

    I couldn't find any existing git command to do this hence I had to use a combination of existing commands.

    First, let's define an alias files that gives us the names/paths of all files in a given commit like so-

    git config --global alias.files 'diff-tree --no-commit-id --name-only -r'
    

    Now git files commit_1 gives us all files present in commit_1 and doing the same on commit_2 gives us all files present in commit_2. Please see this answer of why/how this command works.

    Now, some command line acrobatics-

    sort <(git files commit_1)  <(git files commit_2) | uniq -d | xargs -d '\n' -n1 git diff commit_1 commit_2 > my_changes.diff
    

    We are passing the list of files present in both commits to sort and then picking files common to both by passing -d flag to uniq which picks only duplicates and finally invoking git diff on these common files via xargs and saving our diff into a file

    0 讨论(0)
  • 2021-02-02 12:21

    The following may do what you want:

    git diff --diff-filter=M commitA commitB
    

    The M option to --diff-filter says only to include files that appear to be modified between the two commits - ones that only exist in one branch or the other would be selected with A ("added") or D ("deleted").

    You can see which files would be selected with these letter codes by doing:

    git diff --name-status commitA commitB
    

    ... and there's more information about all of that in the git diff documentation.

    0 讨论(0)
提交回复
热议问题