5

I'm using a git pre-commit hook to check commits. The pre-commit script basically does one thing:

exec git diff-index --check --cached HEAD --

It does some other things too, but they are irrelevant for this discussion.

The problem is, I have all sorts of files in the repository, and not all of them have to comply with the checks that enforced by "git diff-index --check".

So my question is: how can I exclude/ignore these files? That is, I do track them in git, but I want to ignore them in pre-commit check only.

For instance, a certain patch contains *.c, *.h, *ini, and *.xyz files. I want the "git diff-index --check" to apply to .c and .h files only.

kliteyn
  • 1,917
  • 11
  • 24
  • 1
    The manual page says: "When arguments are present, compares only paths matching those patterns. Otherwise all tracked files are compared." So, add `'*.c' '*.h'` when you want those checked, whenever that is. – torek Oct 08 '13 at 16:09
  • @torek Indeed, your suggestion works :) I guess the "path" argument name is misleading a bit - it made me thing that this is about path, when in fact it is all about file name patterns, including path. Please post your thing as an answer. – kliteyn Oct 08 '13 at 18:59

2 Answers2

8

The man page says:

When <path> arguments are present, compares only paths matching those patterns. Otherwise all tracked files are compared.

In other words, the "path" arguments are really glob-style patterns, not just specific paths. You can just add '*.c' '*.h' to your command.

torek
  • 448,244
  • 59
  • 642
  • 775
  • 1
    Not sure if it's an issue with my env (Windows + Git bash) or with different git version, but only the following worked for me (no quotes that is): `git diff-index --check --cached HEAD -- *.html *.js` – harriha Jul 09 '14 at 05:40
  • 1
    @Mr_and_Mrs_D: I think it should. I have not tested it. All pathspec handling *should* be done through common code in Git, so that it all behaves the same (but it's not *actually* done that way: in particular, gitignore pathspecs use separate code). – torek Oct 09 '16 at 23:40
2

The accepted answer deals correctly with the exclusion of filename extensions. To exclude files residing in a directory you can use the following command.

git diff-index --check --cached HEAD -- ':!directory'
Diomidis Spinellis
  • 18,734
  • 5
  • 61
  • 83