Jeanluca Scaljeri Jeanluca Scaljeri - 1 year ago 117
Git Question

setup pre-commit hook jshint

I recently started a project on github.
I've managed to setup automatic testing after each commit using Travis. But now I would like to setup a pre-commit hook with jshint too. So if jshint reports errors, the commit should fail. But is this possible, and if so, how to do this ?

Answer Source

But is this possible...

Yes! This is possible. I recently wrote about it. Note that it's not specific to GitHub, just Git in general - as it's a pre-commit hook, it runs before any data is sent to GitHub.

Any appropriately-named executable files in the /.git/hooks directory of your repository will be run as hooks. There will likely be a bunch of example hooks in there already by default. Here's a simple shell script that I use as a JSLint pre-commit hook (you could modify it very easily to work with JSHint instead):


files=$(git diff --cached --name-only --diff-filter=ACM | grep "\.js$")
if [ "$files" = "" ]; then 
    exit 0 


echo "\nValidating JavaScript:\n"

for file in ${files}; do
    result=$(jslint ${file} | grep "${file} is OK")
    if [ "$result" != "" ]; then
        echo "\t\033[32mJSLint Passed: ${file}\033[0m"
        echo "\t\033[31mJSLint Failed: ${file}\033[0m"

echo "\nJavaScript validation complete\n"

if ! $pass; then
    echo "\033[41mCOMMIT FAILED:\033[0m Your commit contains files that should pass JSLint but do not. Please fix the JSLint errors and try again.\n"
    exit 1
    echo "\033[42mCOMMIT SUCCEEDED\033[0m\n"

You can simply put that in an executable file named pre-commit in your Git hooks directory, and it will run before every commit.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download