0

What is the git diff command needed to show the changes a merge would make without performing the merge?

I've done searches and not found what I'm looking for. For example, I'm on branch feature/cool, and I run git diff main. It shows me all of the new files I have created on feature/cool that's not what would be merged. It is, however, a valid difference between the two branches.

I've seen how to do this with git merge see this:

I would accept that git doesn't have a way to do that with the git diff command but I thought I found the command to do this a few days ago.

PatS
  • 8,833
  • 12
  • 57
  • 100
  • There might be a `git log` command that does this. – PatS Apr 13 '23 at 12:29
  • 1
    Well.... `git diff main` will show you what would be merged _if `main`_ has not moved since you started working on your branch (or you last merged it). If the branch moved, you need to use `...`: `git diff main...` (3 dots) or `git diff main...@` (or something like that). – eftshift0 Apr 13 '23 at 13:12
  • It’s unclear to me what this means. A merge is visualized as a three-way, diff, while `git diff` as used here is two-way. – Guildenstern Apr 16 '23 at 09:58
  • (note: still not a single command, but a possible alternative of `git merge -n`) If your intention is to be able to preview the diff without modifying your index or your files on disk, there is `git merge-tree` ([doc here](https://git-scm.com/docs/git-merge-tree)). After calling it you may compare the content of the tree that was generated to either side of the merge: `git diff main ` or `git diff branch ` – LeGEC Apr 16 '23 at 18:15

1 Answers1

2

It's not possible to know before the merge, exactly what will change after the merge, in all scenarios. That being said, most of the time the 3 dot diff syntax will be close:

git diff <target-branch>...<source-branch>

The 3 dot diff will be exactly correct in either of the following scenarios:

  1. The source branch is fully up to date with the target branch.
  2. The source branch doesn't touch any of the same files as the target branch, since the merge-base of the two branches.

When those 2 rules aren't true, it's possible that the same lines have been modified on both sides (oftentimes due to a cherry-pick) and then some of the changes that show up in the diff won't actually be included in the merge.

Side Note: The 3 dot diff, being useful most of the time, is oftentimes used as the default view for Pull Requests in some tools (e.g. GitHub and Azure DevOps).

Suggestion: If you really want to know what will change, just do it and look:

git switch --detach <target-branch> # detach to avoid touching existing branches
git merge <source-branch> --no-ff # force a merge commit to prevent fast-forward
git diff @~1 @ # look at the difference between before and after the merge commit
TTT
  • 22,611
  • 8
  • 63
  • 69