python.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """Format python code according to QMK's style.
  2. """
  3. from subprocess import CalledProcessError, DEVNULL
  4. from milc import cli
  5. from qmk.path import normpath
  6. py_file_suffixes = ('py',)
  7. py_dirs = ['lib/python']
  8. def yapf_run(files):
  9. edit = '--diff' if cli.args.dry_run else '--in-place'
  10. yapf_cmd = ['yapf', '-vv', '--recursive', edit, *files]
  11. try:
  12. cli.run(yapf_cmd, check=True, capture_output=False, stdin=DEVNULL)
  13. cli.log.info('Successfully formatted the python code.')
  14. except CalledProcessError:
  15. cli.log.error(f'Python code in {",".join(py_dirs)} incorrectly formatted!')
  16. return False
  17. def filter_files(files):
  18. """Yield only files to be formatted and skip the rest
  19. """
  20. for file in files:
  21. if file and file.name.split('.')[-1] in py_file_suffixes:
  22. yield file
  23. else:
  24. cli.log.debug('Skipping file %s', file)
  25. @cli.argument('-n', '--dry-run', arg_only=True, action='store_true', help="Don't actually format.")
  26. @cli.argument('-b', '--base-branch', default='origin/master', help='Branch to compare to diffs to.')
  27. @cli.argument('-a', '--all-files', arg_only=True, action='store_true', help='Format all files.')
  28. @cli.argument('files', nargs='*', arg_only=True, type=normpath, help='Filename(s) to format.')
  29. @cli.subcommand("Format python code according to QMK's style.", hidden=False if cli.config.user.developer else True)
  30. def format_python(cli):
  31. """Format python code according to QMK's style.
  32. """
  33. # Find the list of files to format
  34. if cli.args.files:
  35. files = list(filter_files(cli.args.files))
  36. if not files:
  37. cli.log.error('No Python files in filelist: %s', ', '.join(map(str, cli.args.files)))
  38. exit(0)
  39. if cli.args.all_files:
  40. cli.log.warning('Filenames passed with -a, only formatting: %s', ','.join(map(str, files)))
  41. elif cli.args.all_files:
  42. files = py_dirs
  43. else:
  44. git_diff_cmd = ['git', 'diff', '--name-only', cli.args.base_branch, *py_dirs]
  45. git_diff = cli.run(git_diff_cmd, stdin=DEVNULL)
  46. files = list(filter(None, git_diff.stdout.split('\n')))
  47. # Sanity check
  48. if not files:
  49. cli.log.error('No changed files detected. Use "qmk format-python -a" to format all files')
  50. return False
  51. return yapf_run(files)