Skip to content

Instantly share code, notes, and snippets.

@scottrabin
Forked from kenkouot/pre-commit
Last active December 9, 2015 15:30
Show Gist options
  • Save scottrabin/607c4d61449766cfbced to your computer and use it in GitHub Desktop.
Save scottrabin/607c4d61449766cfbced to your computer and use it in GitHub Desktop.
#!/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)
@biswarupdasgupta
Copy link

Hi Scott,

We are trying to integrate this in our repo and are facing some problems. When we run the js-beautify tool, we want to pass some more arguments (e.g. -w150 -m2) apart from "-r". However if add additional arguments it does not work. Can you please give some pointers on how to achieve this? Changing

command.insert(1, '-r')

to

command.insert(1, '-w 10')  

didnt work

Thanks in advance !

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