python.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 normpath(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. git_ls_cmd = ['git', 'ls-files', *py_dirs]
  43. git_ls = cli.run(git_ls_cmd, stdin=DEVNULL)
  44. files = list(filter_files(git_ls.stdout.split('\n')))
  45. else:
  46. git_diff_cmd = ['git', 'diff', '--name-only', cli.args.base_branch, *py_dirs]
  47. git_diff = cli.run(git_diff_cmd, stdin=DEVNULL)
  48. files = list(filter_files(git_diff.stdout.split('\n')))
  49. # Sanity check
  50. if not files:
  51. cli.log.error('No changed files detected. Use "qmk format-python -a" to format all files')
  52. return False
  53. return yapf_run(files)