1

Can I use git diff to compare a file in a remote branch with a file on the local file system outside of any git repositories? I want to accomplish this without creation of any temporary files.

git diff origin/release/1.0.1:pom.xml /tmp/pom.xml
error: Could not access 'origin/release/1.0.1:pom.xml'

which isn't true as the file exists in that branch

But if run the command below:

git diff origin/release/1.0.1:pom.xml -- /tmp/pom.xml
fatal: /tmp/pom.xml '/tmp/pom.xml' is outside repository

This error is more understandable

I've read the help

git help diff

but haven't found any useful info related to this case. Is it possible?

As a workaround I use:

vimdiff <(git show origin/release/1.0.1:pom.xml) <(cat /tmp/pom.xml)

I use git version 2.17.1

ka3ak
  • 2,435
  • 2
  • 30
  • 57
  • I'd do a normal fetch (updates your tracking-branch) and then diff it: git fetch, git diff local-branch origin/origin-branch – Ramana Mar 05 '20 at 22:10
  • Git 2.42 (Q3 2023) should add support for [`git diff --no-index <(process) <(substitution)`](https://stackoverflow.com/a/76714718/6309) – VonC Jul 18 '23 at 16:10

1 Answers1

0

You could run git diff <(git show origin/release/1.0.1:pom.xml) /tmp/pom.xml, except git diff doesn't like input files that are not actual files:

error: /tmp/sh-np.eK8qhl: unsupported file type

The <(...) syntax in bash is implemented by creating named pipes (mkfifo) files in a temporary-file directory, spinning off a process to write to the named pipes, and then running the top level command. When the top level command finishes, bash removes the named pipes and kills off the process if it's still running.

Plain diff and other tools that will read from named pipes work OK. If you want to use git diff, though, your best bet is just to create a temporary file, even if you don't want to. Use a bit of shell script to automatically remove the temporary file at the end:

#! /bin/sh
rev=origin/release/1.0.1
path=pom.xml

TF=$(mktemp) || exit
trap "rm -f $TF" 0 1 2 3 15
git show $rev:$path > $TF || exit
git diff $TF /tmp/pom.xml

Except for a brief period from the point where mktemp has created the temporary file until the trap "rm -f $TF" is in effect, all ways out of this script will automatically clean it up. (Well, all ways that don't involve killing the shell irrecoverably. For instance, a kill -9 or OOM kill of the shell will cause the temporary file to be left behind. But this same flaw applies to the named-pipe <(...) syntax.)

torek
  • 448,244
  • 59
  • 642
  • 775