Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to git-diff a file against standard input?

Tags:

git

Let's say I'm editing a file. If I save the file, git-diff will give me its changes relative to the index. I'd like to get the changes relative to the index without saving the file first – for a "realtime" diff.

One solution is to write the unsaved changes to a temporary file (i.e. save the file elsewhere), write the staged file to another temporary file (git show :file > tempfile2) then git-diff tempfile tempfile2. However that seems inelegant.

Is there a better way?

like image 320
Andy Stewart Avatar asked Mar 07 '13 12:03

Andy Stewart


2 Answers

Since git 1.5.1 there's been an option to diff against stdin - it's just not been documented

$ echo foo | git diff --no-index -- my_file -

On playing with this a bit more I realized this might not be what the OP (or I) wanted - it diffs the current state of the file to stdin, not the last committed state of the file to stdin. Something like this will do that

$ echo foo | diff -u <(git show :my_file) -

Note this does mean invoking diff directly which might not pick up some settings in your git config. Basically as ams says in his answer.

like image 82
Ash Berlin-Taylor Avatar answered Oct 22 '22 08:10

Ash Berlin-Taylor


Improving upon Ash Berlin's answer.

This allows you to use the nice features of git-diff.

git show :file | git diff --no-index -- - temp_saved_path

Note that this still might not be as convenient as you'd like, because you still have to write to a temp file. Until you save the file, the changes are either not on disk at all (in-memory only), or in some kind of temporary file that is editor-dependent. It's possible that Vim could do this seamlessly in one step, but I'm not familiar enough to say.

like image 38
Kelvin Avatar answered Oct 22 '22 09:10

Kelvin