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