-
-
Save zilongshanren/cd427b695476f4c4063d to your computer and use it in GitHub Desktop.
js precommit hook for jshint, jsbeautify
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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'] | |
for tool in tools: | |
if subprocess.call(['which', tool], stdout=open(os.devnull, 'w')) > 0: | |
sys.exit("You must `npm install -g %s` to run this git pre-commit hook" % tool) | |
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment