logo

qmk_firmware

custom branch of QMK firmware git clone https://anongit.hacktivis.me/git/qmk_firmware.git

python.py (2536B)


  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', 'util/ci']
  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. files = list(map(normpath, filter(None, files)))
  21. for file in files:
  22. if file.suffix[1:] in py_file_suffixes:
  23. yield file
  24. else:
  25. cli.log.debug('Skipping file %s', file)
  26. @cli.argument('-n', '--dry-run', arg_only=True, action='store_true', help="Don't actually format.")
  27. @cli.argument('-b', '--base-branch', default='origin/master', help='Branch to compare to diffs to.')
  28. @cli.argument('-a', '--all-files', arg_only=True, action='store_true', help='Format all files.')
  29. @cli.argument('files', nargs='*', arg_only=True, type=normpath, help='Filename(s) to format.')
  30. @cli.subcommand("Format python code according to QMK's style.", hidden=False if cli.config.user.developer else True)
  31. def format_python(cli):
  32. """Format python code according to QMK's style.
  33. """
  34. # Find the list of files to format
  35. if cli.args.files:
  36. files = list(filter_files(cli.args.files))
  37. if not files:
  38. cli.log.error('No Python files in filelist: %s', ', '.join(map(str, cli.args.files)))
  39. exit(0)
  40. if cli.args.all_files:
  41. cli.log.warning('Filenames passed with -a, only formatting: %s', ','.join(map(str, files)))
  42. elif cli.args.all_files:
  43. git_ls_cmd = ['git', 'ls-files', *py_dirs]
  44. git_ls = cli.run(git_ls_cmd, stdin=DEVNULL)
  45. files = list(filter_files(git_ls.stdout.split('\n')))
  46. else:
  47. git_diff_cmd = ['git', 'diff', '--name-only', cli.args.base_branch, *py_dirs]
  48. git_diff = cli.run(git_diff_cmd, stdin=DEVNULL)
  49. files = list(filter_files(git_diff.stdout.split('\n')))
  50. # Sanity check
  51. if not files:
  52. cli.log.error('No changed files detected. Use "qmk format-python -a" to format all files')
  53. return False
  54. return yapf_run(files)