Skip to content

Instantly share code, notes, and snippets.

@kenkouot
Last active August 29, 2015 13:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kenkouot/10670784 to your computer and use it in GitHub Desktop.
Save kenkouot/10670784 to your computer and use it in GitHub Desktop.
Run JS code quality tools as precommit hook. Add in your repos ".git/hooks/" directory. Make sure file is named "precommit" (with no extension). After to add this into your hooks folder, make sure that the file has executable permissions.
#!/usr/bin/env python
import subprocess
import sys
import os.path, time
def get_modified_time(file):
return time.ctime(os.path.getmtime(file))
def run_js_tools(files_str):
"""Iterate though list and run code quality tools"""
for filename in files_str:
# operate only on "Added" or "Modified" *.js files
if (filename[0] == 'A' or filename[0] == 'M') and filename.endswith('.js'):
# Get the file path
path = filename.split('\t')[1]
# Get original modified time
preprocess_mtime = get_modified_time(path)
for tool in tools:
command = [tool, path]
if 'beautify' in tool:
command.insert(1, '-r')
proc = subprocess.Popen(command, stdout=sys.stdout)
proc.communicate()
# If modified time changes, we git add
if preprocess_mtime != get_modified_time(path):
subprocess.Popen(['git', 'add', '-u'], stdout=sys.stdout)
retcode = output = proc.poll()
if retcode != 0:
sys.exit(tool + ' found errors, aborting commit')
if __name__ == '__main__':
# List of preinstalled CLI tools to check through
tools = ['js-beautify', 'jscs','jshint']
# Get the list of staged files
staged_files_str = subprocess.check_output(['git', 'diff', '--cached', '--name-status']).split('\n')
# Remove newline
staged_files_str.pop()
run_js_tools(staged_files_str)
@scottrabin
Copy link

This doesn't give much indication of why it might fail on new dev boxes; you have to npm install -g js-beautify jscs jshint before use.

Slightly better reporting of missing tools: https://gist.github.com/scottrabin/607c4d61449766cfbced

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