Search code examples
gitgithooks

Git pre-commit hook. Empty index behavior


I'm writing a pre-commit script to find binary files added to the index.

While working on it I've realized that if I add one single binary file, then do a commit, the script would unstage it(leaving the index empty) but the commit would proceed(unless I do something to prevent it).

Is this the expected behavior?

What I want to know is why do "git commit" forbid by default proceeding if index is empty, but when in a hook script the commit would be done.

For the record, I have a workaround to avoid commit to be done in cases where index is empty.

I hope someone can explain why the commit is done.


Solution

  • Git does allow empty commits, if you use the --allow-empty flag.

    So, what's happening here is that git starts the commit and checks for "is empty" (which would require adding --allow-empty) and it's not empty. So git runs your hook, which empties out the commit, but you've already passed the "not empty" test, which is not repeated—it's up to the hook to exit nonzero in this case.