aboutsummaryrefslogtreecommitdiff
path: root/lib/python/qmk
diff options
context:
space:
mode:
authorZach White <skullydazed@gmail.com>2021-05-10 11:18:44 -0700
committerGitHub <noreply@github.com>2021-05-10 11:18:44 -0700
commita3e7f3e7c58ee98596ead5c213f3a9ed8340cd80 (patch)
treeef0cb85205fad7562045f23caa8a16384e43bbb5 /lib/python/qmk
parent66ed80ad3a0edecd9d7abbef71fc2a6e3e59b541 (diff)
downloadqmk_firmware-a3e7f3e7c58ee98596ead5c213f3a9ed8340cd80.tar.gz
qmk_firmware-a3e7f3e7c58ee98596ead5c213f3a9ed8340cd80.zip
Improve our CI tests (#11476)
* add a test and dry-run to qmk generate-api * add a dry-run to qmk pyformat * Add a --dry-run to qmk cformat * reverse the order of nose2 and flake8 tests * run CI test against cformat and pyformat * fix programming errors * tweak job name * fix argument * refine the files we select * fix stack trace in --ci * make cformat exit clean * fix c file extensions * decouple CI from pyformat * remove --ci arg * make ci happy * use the environment var instead * change output to text * fix log message * replace tabs
Diffstat (limited to 'lib/python/qmk')
-rw-r--r--lib/python/qmk/cli/cformat.py119
-rwxr-xr-xlib/python/qmk/cli/generate/api.py35
-rwxr-xr-xlib/python/qmk/cli/pyformat.py15
-rw-r--r--lib/python/qmk/cli/pytest.py3
-rw-r--r--lib/python/qmk/tests/test_cli_commands.py16
5 files changed, 140 insertions, 48 deletions
diff --git a/lib/python/qmk/cli/cformat.py b/lib/python/qmk/cli/cformat.py
index d0d3b3b0a..9333aaec4 100644
--- a/lib/python/qmk/cli/cformat.py
+++ b/lib/python/qmk/cli/cformat.py
@@ -1,6 +1,7 @@
1"""Format C code according to QMK's style. 1"""Format C code according to QMK's style.
2""" 2"""
3import subprocess 3import subprocess
4from os import path
4from shutil import which 5from shutil import which
5 6
6from argcomplete.completers import FilesCompleter 7from argcomplete.completers import FilesCompleter
@@ -9,58 +10,118 @@ from milc import cli
9from qmk.path import normpath 10from qmk.path import normpath
10from qmk.c_parse import c_source_files 11from qmk.c_parse import c_source_files
11 12
13c_file_suffixes = ('c', 'h', 'cpp')
14core_dirs = ('drivers', 'quantum', 'tests', 'tmk_core', 'platforms')
15ignored = ('tmk_core/protocol/usb_hid', 'quantum/template', 'platforms/chibios')
12 16
13def cformat_run(files, all_files): 17
14 """Spawn clang-format subprocess with proper arguments 18def find_clang_format():
19 """Returns the path to clang-format.
15 """ 20 """
16 # Determine which version of clang-format to use
17 clang_format = ['clang-format', '-i']
18 for clang_version in range(20, 6, -1): 21 for clang_version in range(20, 6, -1):
19 binary = 'clang-format-%d' % clang_version 22 binary = f'clang-format-{clang_version}'
23
20 if which(binary): 24 if which(binary):
21 clang_format[0] = binary 25 return binary
22 break 26
27 return 'clang-format'
28
29
30def find_diffs(files):
31 """Run clang-format and diff it against a file.
32 """
33 found_diffs = False
34
35 for file in files:
36 cli.log.debug('Checking for changes in %s', file)
37 clang_format = subprocess.Popen([find_clang_format(), file], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
38 diff = cli.run(['diff', '-u', f'--label=a/{file}', f'--label=b/{file}', str(file), '-'], stdin=clang_format.stdout, capture_output=True)
39
40 if diff.returncode != 0:
41 print(diff.stdout)
42 found_diffs = True
43
44 return found_diffs
45
46
47def cformat_run(files):
48 """Spawn clang-format subprocess with proper arguments
49 """
50 # Determine which version of clang-format to use
51 clang_format = [find_clang_format(), '-i']
52
23 try: 53 try:
24 if not files: 54 cli.run(clang_format + list(map(str, files)), check=True, capture_output=False)
25 cli.log.warn('No changes detected. Use "qmk cformat -a" to format all files')
26 return False
27 subprocess.run(clang_format + [file for file in files], check=True)
28 cli.log.info('Successfully formatted the C code.') 55 cli.log.info('Successfully formatted the C code.')
56 return True
29 57
30 except subprocess.CalledProcessError: 58 except subprocess.CalledProcessError as e:
31 cli.log.error('Error formatting C code!') 59 cli.log.error('Error formatting C code!')
60 cli.log.debug('%s exited with returncode %s', e.cmd, e.returncode)
61 cli.log.debug('STDOUT:')
62 cli.log.debug(e.stdout)
63 cli.log.debug('STDERR:')
64 cli.log.debug(e.stderr)
32 return False 65 return False
33 66
34 67
35@cli.argument('-a', '--all-files', arg_only=True, action='store_true', help='Format all core files.') 68def filter_files(files):
69 """Yield only files to be formatted and skip the rest
70 """
71 for file in files:
72 if file.name.split('.')[-1] in c_file_suffixes:
73 yield file
74 else:
75 cli.log.debug('Skipping file %s', file)
76
77
78@cli.argument('-n', '--dry-run', arg_only=True, action='store_true', help="Flag only, don't automatically format.")
36@cli.argument('-b', '--base-branch', default='origin/master', help='Branch to compare to diffs to.') 79@cli.argument('-b', '--base-branch', default='origin/master', help='Branch to compare to diffs to.')
37@cli.argument('files', nargs='*', arg_only=True, completer=FilesCompleter('.c'), help='Filename(s) to format.') 80@cli.argument('-a', '--all-files', arg_only=True, action='store_true', help='Format all core files.')
81@cli.argument('files', nargs='*', arg_only=True, type=normpath, completer=FilesCompleter('.c'), help='Filename(s) to format.')
38@cli.subcommand("Format C code according to QMK's style.", hidden=False if cli.config.user.developer else True) 82@cli.subcommand("Format C code according to QMK's style.", hidden=False if cli.config.user.developer else True)
39def cformat(cli): 83def cformat(cli):
40 """Format C code according to QMK's style. 84 """Format C code according to QMK's style.
41 """ 85 """
42 # Empty array for files
43 files = []
44 # Core directories for formatting
45 core_dirs = ['drivers', 'quantum', 'tests', 'tmk_core', 'platforms']
46 ignores = ['tmk_core/protocol/usb_hid', 'quantum/template', 'platforms/chibios']
47 # Find the list of files to format 86 # Find the list of files to format
48 if cli.args.files: 87 if cli.args.files:
49 files.extend(normpath(file) for file in cli.args.files) 88 files = list(filter_files(cli.args.files))
89
90 if not files:
91 cli.log.error('No C files in filelist: %s', ', '.join(map(str, cli.args.files)))
92 exit(0)
93
50 if cli.args.all_files: 94 if cli.args.all_files:
51 cli.log.warning('Filenames passed with -a, only formatting: %s', ','.join(map(str, files))) 95 cli.log.warning('Filenames passed with -a, only formatting: %s', ','.join(map(str, files)))
52 # If -a is specified 96
53 elif cli.args.all_files: 97 elif cli.args.all_files:
54 all_files = c_source_files(core_dirs) 98 all_files = c_source_files(core_dirs)
55 # The following statement checks each file to see if the file path is in the ignored directories. 99 # The following statement checks each file to see if the file path is in the ignored directories.
56 files.extend(file for file in all_files if not any(i in str(file) for i in ignores)) 100 files = [file for file in all_files if not any(i in str(file) for i in ignored)]
57 # No files specified & no -a flag 101
58 else: 102 else:
59 base_args = ['git', 'diff', '--name-only', cli.args.base_branch] 103 git_diff_cmd = ['git', 'diff', '--name-only', cli.args.base_branch, *core_dirs]
60 out = subprocess.run(base_args + core_dirs, check=True, stdout=subprocess.PIPE) 104 git_diff = cli.run(git_diff_cmd)
61 changed_files = filter(None, out.stdout.decode('UTF-8').split('\n')) 105
62 filtered_files = [normpath(file) for file in changed_files if not any(i in file for i in ignores)] 106 if git_diff.returncode != 0:
63 files.extend(file for file in filtered_files if file.exists() and file.suffix in ['.c', '.h', '.cpp']) 107 cli.log.error("Error running %s", git_diff_cmd)
108 print(git_diff.stderr)
109 return git_diff.returncode
110
111 files = []
112
113 for file in git_diff.stdout.strip().split('\n'):
114 if not any([file.startswith(ignore) for ignore in ignored]):
115 if path.exists(file) and file.split('.')[-1] in c_file_suffixes:
116 files.append(file)
117
118 # Sanity check
119 if not files:
120 cli.log.error('No changed files detected. Use "qmk cformat -a" to format all files')
121 return False
64 122
65 # Run clang-format on the files we've found 123 # Run clang-format on the files we've found
66 cformat_run(files, cli.args.all_files) 124 if cli.args.dry_run:
125 return not find_diffs(files)
126 else:
127 return cformat_run(files)
diff --git a/lib/python/qmk/cli/generate/api.py b/lib/python/qmk/cli/generate/api.py
index 70019428f..8ab7522a7 100755
--- a/lib/python/qmk/cli/generate/api.py
+++ b/lib/python/qmk/cli/generate/api.py
@@ -13,6 +13,7 @@ from qmk.json_schema import json_load
13from qmk.keyboard import list_keyboards 13from qmk.keyboard import list_keyboards
14 14
15 15
16@cli.argument('-n', '--dry-run', arg_only=True, action='store_true', help="Don't write the data to disk.")
16@cli.subcommand('Creates a new keymap for the keyboard of your choosing', hidden=False if cli.config.user.developer else True) 17@cli.subcommand('Creates a new keymap for the keyboard of your choosing', hidden=False if cli.config.user.developer else True)
17def generate_api(cli): 18def generate_api(cli):
18 """Generates the QMK API data. 19 """Generates the QMK API data.
@@ -40,10 +41,14 @@ def generate_api(cli):
40 keyboard_readme_src = Path('keyboards') / keyboard_name / 'readme.md' 41 keyboard_readme_src = Path('keyboards') / keyboard_name / 'readme.md'
41 42
42 keyboard_dir.mkdir(parents=True, exist_ok=True) 43 keyboard_dir.mkdir(parents=True, exist_ok=True)
43 keyboard_info.write_text(json.dumps({'last_updated': current_datetime(), 'keyboards': {keyboard_name: kb_all[keyboard_name]}})) 44 keyboard_json = json.dumps({'last_updated': current_datetime(), 'keyboards': {keyboard_name: kb_all[keyboard_name]}})
45 if not cli.args.dry_run:
46 keyboard_info.write_text(keyboard_json)
47 cli.log.debug('Wrote file %s', keyboard_info)
44 48
45 if keyboard_readme_src.exists(): 49 if keyboard_readme_src.exists():
46 copyfile(keyboard_readme_src, keyboard_readme) 50 copyfile(keyboard_readme_src, keyboard_readme)
51 cli.log.debug('Copied %s -> %s', keyboard_readme_src, keyboard_readme)
47 52
48 if 'usb' in kb_all[keyboard_name]: 53 if 'usb' in kb_all[keyboard_name]:
49 usb = kb_all[keyboard_name]['usb'] 54 usb = kb_all[keyboard_name]['usb']
@@ -57,20 +62,26 @@ def generate_api(cli):
57 if 'vid' in usb and 'pid' in usb: 62 if 'vid' in usb and 'pid' in usb:
58 usb_list[usb['vid']][usb['pid']][keyboard_name] = usb 63 usb_list[usb['vid']][usb['pid']][keyboard_name] = usb
59 64
60 # Write the global JSON files 65 # Generate data for the global files
61 keyboard_all_file.write_text(json.dumps({'last_updated': current_datetime(), 'keyboards': kb_all}, cls=InfoJSONEncoder))
62 usb_file.write_text(json.dumps({'last_updated': current_datetime(), 'usb': usb_list}, cls=InfoJSONEncoder))
63
64 keyboard_list = sorted(kb_all) 66 keyboard_list = sorted(kb_all)
65 keyboard_list_file.write_text(json.dumps({'last_updated': current_datetime(), 'keyboards': keyboard_list}, cls=InfoJSONEncoder))
66
67 keyboard_aliases = json_load(Path('data/mappings/keyboard_aliases.json')) 67 keyboard_aliases = json_load(Path('data/mappings/keyboard_aliases.json'))
68 keyboard_aliases_file.write_text(json.dumps({'last_updated': current_datetime(), 'keyboard_aliases': keyboard_aliases}, cls=InfoJSONEncoder))
69
70 keyboard_metadata = { 68 keyboard_metadata = {
71 'last_updated': current_datetime(), 69 'last_updated': current_datetime(),
72 'keyboards': keyboard_list, 70 'keyboards': keyboard_list,
73 'keyboard_aliases': keyboard_aliases, 71 'keyboard_aliases': keyboard_aliases,
74 'usb': usb_list, 72 'usb': usb_list,
75 } 73 }
76 keyboard_metadata_file.write_text(json.dumps(keyboard_metadata, cls=InfoJSONEncoder)) 74
75 # Write the global JSON files
76 keyboard_all_json = json.dumps({'last_updated': current_datetime(), 'keyboards': kb_all}, cls=InfoJSONEncoder)
77 usb_json = json.dumps({'last_updated': current_datetime(), 'usb': usb_list}, cls=InfoJSONEncoder)
78 keyboard_list_json = json.dumps({'last_updated': current_datetime(), 'keyboards': keyboard_list}, cls=InfoJSONEncoder)
79 keyboard_aliases_json = json.dumps({'last_updated': current_datetime(), 'keyboard_aliases': keyboard_aliases}, cls=InfoJSONEncoder)
80 keyboard_metadata_json = json.dumps(keyboard_metadata, cls=InfoJSONEncoder)
81
82 if not cli.args.dry_run:
83 keyboard_all_file.write_text(keyboard_all_json)
84 usb_file.write_text(usb_json)
85 keyboard_list_file.write_text(keyboard_list_json)
86 keyboard_aliases_file.write_text(keyboard_aliases_json)
87 keyboard_metadata_file.write_text(keyboard_metadata_json)
diff --git a/lib/python/qmk/cli/pyformat.py b/lib/python/qmk/cli/pyformat.py
index 146444380..02581f0d8 100755
--- a/lib/python/qmk/cli/pyformat.py
+++ b/lib/python/qmk/cli/pyformat.py
@@ -5,13 +5,22 @@ from milc import cli
5import subprocess 5import subprocess
6 6
7 7
8@cli.argument('-n', '--dry-run', arg_only=True, action='store_true', help="Flag only, don't automatically format.")
8@cli.subcommand("Format python code according to QMK's style.", hidden=False if cli.config.user.developer else True) 9@cli.subcommand("Format python code according to QMK's style.", hidden=False if cli.config.user.developer else True)
9def pyformat(cli): 10def pyformat(cli):
10 """Format python code according to QMK's style. 11 """Format python code according to QMK's style.
11 """ 12 """
13 edit = '--diff' if cli.args.dry_run else '--in-place'
14 yapf_cmd = ['yapf', '-vv', '--recursive', edit, 'bin/qmk', 'lib/python']
12 try: 15 try:
13 subprocess.run(['yapf', '-vv', '-ri', 'bin/qmk', 'lib/python'], check=True) 16 cli.run(yapf_cmd, check=True, capture_output=False)
14 cli.log.info('Successfully formatted the python code in `bin/qmk` and `lib/python`.') 17 cli.log.info('Python code in `bin/qmk` and `lib/python` is correctly formatted.')
18 return True
15 19
16 except subprocess.CalledProcessError: 20 except subprocess.CalledProcessError:
17 cli.log.error('Error formatting python code!') 21 if cli.args.dry_run:
22 cli.log.error('Python code in `bin/qmk` and `lib/python` incorrectly formatted!')
23 else:
24 cli.log.error('Error formatting python code!')
25
26 return False
diff --git a/lib/python/qmk/cli/pytest.py b/lib/python/qmk/cli/pytest.py
index 5417a9cb3..50a1d70a4 100644
--- a/lib/python/qmk/cli/pytest.py
+++ b/lib/python/qmk/cli/pytest.py
@@ -11,6 +11,7 @@ from milc import cli
11def pytest(cli): 11def pytest(cli):
12 """Run several linting/testing commands. 12 """Run several linting/testing commands.
13 """ 13 """
14 flake8 = subprocess.run(['flake8', 'lib/python', 'bin/qmk'])
15 nose2 = subprocess.run(['nose2', '-v']) 14 nose2 = subprocess.run(['nose2', '-v'])
15 flake8 = subprocess.run(['flake8', 'lib/python', 'bin/qmk'])
16
16 return flake8.returncode | nose2.returncode 17 return flake8.returncode | nose2.returncode
diff --git a/lib/python/qmk/tests/test_cli_commands.py b/lib/python/qmk/tests/test_cli_commands.py
index c57d2b7fc..741551e5e 100644
--- a/lib/python/qmk/tests/test_cli_commands.py
+++ b/lib/python/qmk/tests/test_cli_commands.py
@@ -33,10 +33,15 @@ def check_returncode(result, expected=[0]):
33 33
34 34
35def test_cformat(): 35def test_cformat():
36 result = check_subcommand('cformat', 'quantum/matrix.c') 36 result = check_subcommand('cformat', '-n', 'quantum/matrix.c')
37 check_returncode(result) 37 check_returncode(result)
38 38
39 39
40def test_cformat_all():
41 result = check_subcommand('cformat', '-n', '-a')
42 check_returncode(result, [0, 1])
43
44
40def test_compile(): 45def test_compile():
41 result = check_subcommand('compile', '-kb', 'handwired/pytest/basic', '-km', 'default', '-n') 46 result = check_subcommand('compile', '-kb', 'handwired/pytest/basic', '-km', 'default', '-n')
42 check_returncode(result) 47 check_returncode(result)
@@ -83,9 +88,9 @@ def test_hello():
83 88
84 89
85def test_pyformat(): 90def test_pyformat():
86 result = check_subcommand('pyformat') 91 result = check_subcommand('pyformat', '--dry-run')
87 check_returncode(result) 92 check_returncode(result)
88 assert 'Successfully formatted the python code' in result.stdout 93 assert 'Python code in `bin/qmk` and `lib/python` is correctly formatted.' in result.stdout
89 94
90 95
91def test_list_keyboards(): 96def test_list_keyboards():
@@ -225,6 +230,11 @@ def test_clean():
225 assert result.stdout.count('done') == 2 230 assert result.stdout.count('done') == 2
226 231
227 232
233def test_generate_api():
234 result = check_subcommand('generate-api', '--dry-run')
235 check_returncode(result)
236
237
228def test_generate_rgb_breathe_table(): 238def test_generate_rgb_breathe_table():
229 result = check_subcommand("generate-rgb-breathe-table", "-c", "1.2", "-m", "127") 239 result = check_subcommand("generate-rgb-breathe-table", "-c", "1.2", "-m", "127")
230 check_returncode(result) 240 check_returncode(result)