Search code examples
gitversion-controldiffgit-diff

Can git do a diff between a repo file and an external (non-repo) file?


I need to do a diff between the version of myfile that was in master~2, and a copy of myfile that exists outside the repository itself (say D:\folder\myfile).

The wording in git-diff under --no-index says:

git diff --no-index [--options] [--] […]

This form is to compare the given two paths on the filesystem. You can omit the --no-index option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree

The wording "at least one" seems to imply that comparison can be done between one repo file and one non-repo file, but in practice:

$ git diff master~2:myfile D:/folder/myfile  
error: Could not access: 'master~2:myfile'

$ git diff master~2:myfile -- D:/folder/myfile  
fatal: D:/folder/myfile: 'D:/folder/myfile' is outside repository  

$ git diff --no-index master~2:myfile -- D:/folder/myfile  
usage: git diff --no-index <path> <path>

What is the easiest way to achieve this comparison?


Solution

  • Without using git-diff, I found an indirect way of achieving this - the method given in this blog post, just using the external file as the original "current file", and making sure to have the repo directory as current-directory before doing the git show.

    The steps involved are:

    1. Open the external non-repo file in vim the usual way
    2. Do a :vsp new to vertically split a new (blank) window
    3. :cd to the working directory of the git repository
    4. :read !git show master~2:myfile to read the contents of myfile as it was 2 commits ago
    5. setf yourfiletypehere for syntax highlighting (optional)
    6. :diffthis in one window, then switch to the other window and run :diffthis again, and you have your diff