gitgithooks

`git diff` does not work when run from a git pre-commit hook


I have a git pre-commit hook that does some style checking on any modified files before committing.

The implementation is irrelevant, but it starts by calling git diff. Here's what i have in (repo)/.git/hooks/pre-commit.

#!/bin/sh


echo "=== Running script..."
git diff
echo "=== Done running script..."

# Other stuf
# ....

# Always exit with 1 so pre-commit hook always fails.
# Useful for testing
exit 1

When I actually try committing something, the pre-commit hook correctly fires, but the git diff command doesn't output anything (there are definitely modified files)

> git commit --all -m "foo"
=== Running script...
=== Done running script...

However if I run the pre-commit hook script directly/manually, it does work

> ./.git/hooks/pre-commit
=== Running script...
(... outputs git diff ...)
=== Done running script...

What's different about git calling the hook versus me manually calling it? It runs as the same user either way (my username)

I've also tried suggestions from this thread, but unset GIT_DIR, --git-dir=, and work-tree= didn't fix anything.

Thanks!


Solution

  • You need to use git diff --cached because the changes are already staged.