gitpre-commit-hookpre-commit

How can I make a Git pre-commit code check?


Is it even possible to accomplish this with Git? :)

I want this:

Sometimes I switch one variable in my code to true (localMode = true;) for my own debugging purposes. But this should never be committed. 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?


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

Solution

  • Use How Git hooks made me a better (and more lovable) developer.

    I think you can just add some regular expression to detect localMode = true into the sample code at the page.