123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- #!/usr/bin/env python
- from __future__ import absolute_import
- import os
- import sys
- import subprocess
- import json
- from glob import glob
- from click import echo
- from sentry.lint.engine import check_files, get_js_files
- text_type = type(u'')
- # git usurbs your bin path for hooks and will always run system python
- if 'VIRTUAL_ENV' in os.environ:
- site_packages = glob(
- '%s/lib/*/site-packages' % os.environ['VIRTUAL_ENV'])[0]
- sys.path.insert(0, site_packages)
- PRETTIER_VERSION = "1.2.2"
- def js_format(file_list=None):
- """
- We only format JavaScript code as part of this pre-commit hook. It is not part
- of the lint engine.
- """
- project_root = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
- prettier_path = os.path.join(project_root, 'node_modules', '.bin', 'prettier')
- if not os.path.exists(prettier_path):
- echo('!! Skipping JavaScript formatting because prettier is not installed.', err=True)
- return False
- # Get Prettier version from package.json
- package_version = None
- package_json_path = os.path.join(project_root, 'package.json')
- with open(package_json_path) as package_json:
- try:
- package_version = json.load(package_json)['devDependencies']['prettier']
- except KeyError:
- echo('!! Prettier missing from package.json', err=True)
- return False
- prettier_version = subprocess.check_output([prettier_path, '--version']).rstrip()
- if prettier_version != package_version:
- echo('!! Prettier is out of date: %s (expected %s). Please run `yarn install`.' \
- % (prettier_version, package_version), err=True)
- return False
- js_file_list = get_js_files(file_list)
- has_errors = False
- if js_file_list:
- status = subprocess.Popen([prettier_path, '--write', '--single-quote',
- '--bracket-spacing=false', '--print-width=90', '--jsx-bracket-same-line=true'] +
- js_file_list
- ).wait()
- has_errors = status != 0
- if not has_errors:
- # Stage modifications by Prettier
- status = subprocess.Popen(['git', 'update-index', '--add'] + file_list).wait()
- has_errors = status != 0
- return has_errors
- def main():
- from flake8.hooks import run
- gitcmd = "git diff-index --cached --name-only HEAD"
- _, files_modified, _ = run(gitcmd)
- files_modified = [
- text_type(f)
- for f in files_modified
- if os.path.exists(f)
- ]
- # Prettier formatting must take place before linting
- js_format(files_modified)
- return check_files(files_modified)
- if __name__ == '__main__':
- sys.exit(main())
|