6

I'm writing a pre-commit hook, and would like to do a check on the entire contents of each file that's about to be committed (specifically a lint check on the files). I want to lint check the file as it's going to be commited, not as it exists in my working tree (which may differ).

The pre-commit hook example that comes with git shows you how to get the diff (so you can examine for spaces and such), but I need to get the entire file as it's going to be committed.

2 Answers 2

10

Try this:

git --work-tree=/path/to/checkout-area checkout-index path/to/file-to-checkout

The --work-tree option tells git to use a different area as the work tree, so that you don't overwrite the file in your true work-tree. You might also want to add the -f option to tell it to overwrite if necessary, but if your script properly cleans up after itself it shouldn't be necessary. See the man page for checkout-index for more information.

1
  • Yep, checkout-index was just the hint I needed to find what I needed to find. Thanks! Commented Aug 27, 2009 at 19:02
5

Another solution for a single1 file is (assuming that you are not during conflicted merge or rebase):

$ git show :0:path/to/file

(where path/to/file is relative to top directory in repository).

Or "git cat-file blob :0:path/to/file", which (I think) wouldn't invoke any filters (keyword expansion, end of line conversion, etc.).

See section about extended sha-1 syntax in git-rev-parse manpage


1.) the advantage of Jefromi's answer is that using git checkout-index you can checkout more than one file; you can checkout whole directory or even whole project.

3
  • This is pretty awesome though I'm gonna find an excuse to use it.
    – Cascabel
    Commented Aug 27, 2009 at 18:26
  • The shorthand seems to be git show :path/to/file as mentioned here. I use it to check if no API key was staged in a pre-commit hook.
    – MayeulC
    Commented Jun 18, 2018 at 22:26
  • -1 unfortunately using git show in this way gives you just the staged diff of the file, not the whole staged file, which is what OP wanted.
    – C S
    Commented Apr 19, 2019 at 3:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.