Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JShint git pre-commit hook
{
"devel": false,
"undef": true
}
#!/usr/bin/env python
import os, sys
"""
Checks your git commit with JSHint. Only checks staged files
"""
def jshint():
errors = []
# get all staged files
f = os.popen('git diff-index --name-only --cached HEAD')
for file in f.readlines():
# you may have to change path to jshint!
# global options stored in ~/.jshintrc
g = os.popen('/usr/local/bin/jshint ' + file)
# add all errors from all files together
for error in g.readlines():
errors.append(error)
# got errors?
if errors:
for i, error in enumerate(errors):
print error,
# Abort the commit
sys.exit(1)
# All good
sys.exit(0)
if __name__ == '__main__':
jshint()
@matthewlein

This comment has been minimized.

Copy link
Owner Author

@matthewlein matthewlein commented Apr 30, 2012

@sam3k

This comment has been minimized.

Copy link

@sam3k sam3k commented Jul 3, 2012

Hey Matt, is the argument of os.popen() the path to the file staged to commit or the path to jshint?

It seems to be like it is for the staged commit js files, but when I try to run it it gives me an error:

my/path/myModifiedJS.js: Permission denied

I did chmod +x .git/hooks/pre-commit as mentioned in the article above but still gives me this error.

Any ideas?

@matthewlein

This comment has been minimized.

Copy link
Owner Author

@matthewlein matthewlein commented Jul 3, 2012

no...afraid not. I only get 1% of that code :)

@sam3k

This comment has been minimized.

Copy link

@sam3k sam3k commented Jul 4, 2012

and this hook works for you? git-rev-parse gives me a syntax error but this passes that specific line:

if git rev-parse --verify HEAD >/dev/null 2>&1

but now i get:

fatal: --name-only, --name-status, --check and -s are mutually exclusive

@matthewlein

This comment has been minimized.

Copy link
Owner Author

@matthewlein matthewlein commented Jul 9, 2012

(I'm on a Mac and know nothing about PC setup for this—and so far my use has been pretty limited, haven't done very complicated git stuff with it)

Yea, it works for me. If its silently failing your path to jshint is maybe off

this one uses:
/usr/local/bin/jshint

but npm installs in /usr/bin/jshint I think. If you do which jshint in terminal you should get the correct path to paste in there. and the
.jshintrc file goes in your user folder (to make it global) or it can be put in many other places detailed here: https://github.com/jshint/node-jshint/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment