How to make a git pre-commit code check?

timetowonder picture timetowonder · Nov 18, 2014 · Viewed 9.2k times · Source

First question... is it even possible to accomplish this with git? :)

What I want is this:

Sometimes I switch one variable in my code to true (localMode = true;) for my own debugging purposes. But this should never be commited. I should only commit code with the variable set to false. And of course sometimes I forget to make this change. Is it possible for git to somehow stop or warn me if I am about to commit the 'wrong' code?

UPD:
Thanks for the help! I ended up with the following shell script:

#!/bin/bash
git diff --cached --name-only | while read FILE; do
if [[ $(echo "$FILE" | grep -E "^.+main\-controller\.js$") ]]; then
    content=$(<"$FILE")
    if [[ $(echo "$content" | grep -E "rootScope\.localMode = true") ]]; then   
        echo -e "\e[1;31m\tCommit contains localMode set to true.\e[0m" >&2
        exit 1
    fi
fi
done

Answer

dcastro picture dcastro · Nov 18, 2014

Yes, you can use a pre-commit hook.

Just drop a shell script named pre-commit (with no extension) inside your ".git/hooks" folder with the logic to check your variable and either:

  • change it to false and continue with the commit or
  • print a message telling the user to correct the value manually, and exit with a non-zero code to abort the commit

The hooks folder should contain a few samples, such as "pre-commit.sample", which you might find helpful.

From the docs:

The pre-commit hook is run first, before you even type in a commit message. It’s used to inspect the snapshot that’s about to be committed, to see if you’ve forgotten something, to make sure tests run, or to examine whatever you need to inspect in the code. Exiting non-zero from this hook aborts the commit, although you can bypass it with git commit --no-verify. You can do things like check for code style (run lint or something equivalent), check for trailing whitespace (the default hook does exactly this), or check for appropriate documentation on new methods.