Unknown Pirate
Unknown Pirate

Reputation: 21

pre-commit hook not working

I'm trying to add a pre-commit hook to my project, When I run ./.git/hook/pre-commit it gives proper result.
While committing variable OUTPUT is always empty.

#!/bin/bash
OUTPUT=`git diff | flake8 --diff`


if [ -z "${OUTPUT}" ]
then
      echo "================== You are awesome ===================="
      echo "${OUTPUT}"
      exit 1
else
      echo ""
      echo "================== Your code stinks, Fix them ===================="
      echo ""
      echo "${OUTPUT}"
      exit 1
fi
exit 1

Upvotes: 2

Views: 3150

Answers (2)

Matthieu Moy
Matthieu Moy

Reputation: 16547

git diff shows you unstaged changes, i.e. changes that will not go in the commit. Within the pre-commit hook, the output will be empty unless you are doing a partial commit.

What you want is git diff --staged instead: it shows you the changes you are about to commit, and this is the part you want to check using flake8.

You can try running git status within the hook and look at "Changes to be committed:" and "Changes not staged for commit:" sections to understand what I mean.

Also, one of your exit 1 should be an exit 0 ;-).

Upvotes: 0

Vampire
Vampire

Reputation: 38724

The hooks are run in a different environment. Especially the PATH might not be set like you have it for your user. Try using the whole path to the executables you call like git and flake8 and see if it works then.

Upvotes: 1

Related Questions