pre-commit 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env python
  2. from __future__ import absolute_import
  3. import os
  4. import sys
  5. import subprocess
  6. import json
  7. from glob import glob
  8. from click import echo
  9. from sentry.lint.engine import check_files, get_js_files
  10. text_type = type(u'')
  11. # git usurbs your bin path for hooks and will always run system python
  12. if 'VIRTUAL_ENV' in os.environ:
  13. site_packages = glob(
  14. '%s/lib/*/site-packages' % os.environ['VIRTUAL_ENV'])[0]
  15. sys.path.insert(0, site_packages)
  16. PRETTIER_VERSION = "1.2.2"
  17. def js_format(file_list=None):
  18. """
  19. We only format JavaScript code as part of this pre-commit hook. It is not part
  20. of the lint engine.
  21. """
  22. project_root = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
  23. prettier_path = os.path.join(project_root, 'node_modules', '.bin', 'prettier')
  24. if not os.path.exists(prettier_path):
  25. echo('!! Skipping JavaScript formatting because prettier is not installed.', err=True)
  26. return False
  27. # Get Prettier version from package.json
  28. package_version = None
  29. package_json_path = os.path.join(project_root, 'package.json')
  30. with open(package_json_path) as package_json:
  31. try:
  32. package_version = json.load(package_json)['devDependencies']['prettier']
  33. except KeyError:
  34. echo('!! Prettier missing from package.json', err=True)
  35. return False
  36. prettier_version = subprocess.check_output([prettier_path, '--version']).rstrip()
  37. if prettier_version != package_version:
  38. echo('!! Prettier is out of date: %s (expected %s). Please run `yarn install`.' \
  39. % (prettier_version, package_version), err=True)
  40. return False
  41. js_file_list = get_js_files(file_list)
  42. has_errors = False
  43. if js_file_list:
  44. status = subprocess.Popen([prettier_path, '--write', '--single-quote',
  45. '--bracket-spacing=false', '--print-width=90', '--jsx-bracket-same-line=true'] +
  46. js_file_list
  47. ).wait()
  48. has_errors = status != 0
  49. if not has_errors:
  50. # Stage modifications by Prettier
  51. status = subprocess.Popen(['git', 'update-index', '--add'] + file_list).wait()
  52. has_errors = status != 0
  53. return has_errors
  54. def main():
  55. from flake8.hooks import run
  56. gitcmd = "git diff-index --cached --name-only HEAD"
  57. _, files_modified, _ = run(gitcmd)
  58. files_modified = [
  59. text_type(f)
  60. for f in files_modified
  61. if os.path.exists(f)
  62. ]
  63. # Prettier formatting must take place before linting
  64. js_format(files_modified)
  65. return check_files(files_modified)
  66. if __name__ == '__main__':
  67. sys.exit(main())