diff options
| author | Erovia <Erovia@users.noreply.github.com> | 2020-10-07 01:10:19 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-10-06 17:10:19 -0700 |
| commit | 058737f116b53116726f32175205b46e22396f86 (patch) | |
| tree | d84cecc2d1716d93b56b078a3f86eff14db13415 /lib | |
| parent | c9a06965c991a84ac76014d9791e439f88dfb957 (diff) | |
| download | qmk_firmware-058737f116b53116726f32175205b46e22396f86.tar.gz qmk_firmware-058737f116b53116726f32175205b46e22396f86.zip | |
[CLI] Add c2json (#8817)
* Basic keymap parsing finally works
* Add 'keymap.json' creation to the qmk.keymap module
* Add tests and fix formatting
* Fix/exclude flake8 errors
* Convert keymap.c to valid keymap.json
* Fix some errors
* Add tests
* Finalize keymap.json creation, add json template
* Add docs
* Move pygments to the standard requirements
* Add support for nameless layers, fix tests
* Fix things after rebase
* Add missing 'keymap' value.
* Fix missing layer numbers from advanced keycodes
Buckwich noticed that if the advanced keycode / layer toggling key
contains a number, it goes missing.
Now we properly handle them.
Thx for noticing!
* Apply suggestions from code review
* fixup tests
Co-authored-by: Zach White <skullydazed@drpepper.org>
Co-authored-by: skullY <skullydazed@gmail.com>
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/python/qmk/cli/__init__.py | 1 | ||||
| -rw-r--r-- | lib/python/qmk/cli/c2json.py | 62 | ||||
| -rwxr-xr-x | lib/python/qmk/cli/doctor.py | 2 | ||||
| -rw-r--r-- | lib/python/qmk/commands.py | 3 | ||||
| -rw-r--r-- | lib/python/qmk/keymap.py | 280 | ||||
| -rw-r--r-- | lib/python/qmk/tests/test_cli_commands.py | 22 | ||||
| -rw-r--r-- | lib/python/qmk/tests/test_qmk_keymap.py | 20 |
7 files changed, 355 insertions, 35 deletions
diff --git a/lib/python/qmk/cli/__init__.py b/lib/python/qmk/cli/__init__.py index 47f60c601..ba964ebbb 100644 --- a/lib/python/qmk/cli/__init__.py +++ b/lib/python/qmk/cli/__init__.py | |||
| @@ -6,6 +6,7 @@ import sys | |||
| 6 | 6 | ||
| 7 | from milc import cli | 7 | from milc import cli |
| 8 | 8 | ||
| 9 | from . import c2json | ||
| 9 | from . import cformat | 10 | from . import cformat |
| 10 | from . import compile | 11 | from . import compile |
| 11 | from . import config | 12 | from . import config |
diff --git a/lib/python/qmk/cli/c2json.py b/lib/python/qmk/cli/c2json.py new file mode 100644 index 000000000..0267303fd --- /dev/null +++ b/lib/python/qmk/cli/c2json.py | |||
| @@ -0,0 +1,62 @@ | |||
| 1 | """Generate a keymap.json from a keymap.c file. | ||
| 2 | """ | ||
| 3 | import json | ||
| 4 | import sys | ||
| 5 | |||
| 6 | from milc import cli | ||
| 7 | |||
| 8 | import qmk.keymap | ||
| 9 | import qmk.path | ||
| 10 | |||
| 11 | |||
| 12 | @cli.argument('--no-cpp', arg_only=True, action='store_false', help='Do not use \'cpp\' on keymap.c') | ||
| 13 | @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to') | ||
| 14 | @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages") | ||
| 15 | @cli.argument('-kb', '--keyboard', arg_only=True, required=True, help='The keyboard\'s name') | ||
| 16 | @cli.argument('-km', '--keymap', arg_only=True, required=True, help='The keymap\'s name') | ||
| 17 | @cli.argument('filename', arg_only=True, help='keymap.c file') | ||
| 18 | @cli.subcommand('Creates a keymap.json from a keymap.c file.') | ||
| 19 | def c2json(cli): | ||
| 20 | """Generate a keymap.json from a keymap.c file. | ||
| 21 | |||
| 22 | This command uses the `qmk.keymap` module to generate a keymap.json from a keymap.c file. The generated keymap is written to stdout, or to a file if -o is provided. | ||
| 23 | """ | ||
| 24 | cli.args.filename = qmk.path.normpath(cli.args.filename) | ||
| 25 | |||
| 26 | # Error checking | ||
| 27 | if not cli.args.filename.exists(): | ||
| 28 | cli.log.error('C file does not exist!') | ||
| 29 | cli.print_usage() | ||
| 30 | exit(1) | ||
| 31 | |||
| 32 | if str(cli.args.filename) == '-': | ||
| 33 | # TODO(skullydazed/anyone): Read file contents from STDIN | ||
| 34 | cli.log.error('Reading from STDIN is not (yet) supported.') | ||
| 35 | cli.print_usage() | ||
| 36 | exit(1) | ||
| 37 | |||
| 38 | # Environment processing | ||
| 39 | if cli.args.output == ('-'): | ||
| 40 | cli.args.output = None | ||
| 41 | |||
| 42 | # Parse the keymap.c | ||
| 43 | keymap_json = qmk.keymap.c2json(cli.args.keyboard, cli.args.keymap, cli.args.filename, use_cpp=cli.args.no_cpp) | ||
| 44 | |||
| 45 | # Generate the keymap.json | ||
| 46 | try: | ||
| 47 | keymap_json = qmk.keymap.generate(keymap_json['keyboard'], keymap_json['layout'], keymap_json['layers'], type='json', keymap=keymap_json['keymap']) | ||
| 48 | except KeyError: | ||
| 49 | cli.log.error('Something went wrong. Try to use --no-cpp.') | ||
| 50 | sys.exit(1) | ||
| 51 | |||
| 52 | if cli.args.output: | ||
| 53 | cli.args.output.parent.mkdir(parents=True, exist_ok=True) | ||
| 54 | if cli.args.output.exists(): | ||
| 55 | cli.args.output.replace(cli.args.output.name + '.bak') | ||
| 56 | cli.args.output.write_text(json.dumps(keymap_json)) | ||
| 57 | |||
| 58 | if not cli.args.quiet: | ||
| 59 | cli.log.info('Wrote keymap to %s.', cli.args.output) | ||
| 60 | |||
| 61 | else: | ||
| 62 | print(json.dumps(keymap_json)) | ||
diff --git a/lib/python/qmk/cli/doctor.py b/lib/python/qmk/cli/doctor.py index 984c308d1..7fafd5757 100755 --- a/lib/python/qmk/cli/doctor.py +++ b/lib/python/qmk/cli/doctor.py | |||
| @@ -58,7 +58,7 @@ def parse_gcc_version(version): | |||
| 58 | return { | 58 | return { |
| 59 | 'major': int(m.group(1)), | 59 | 'major': int(m.group(1)), |
| 60 | 'minor': int(m.group(2)) if m.group(2) else 0, | 60 | 'minor': int(m.group(2)) if m.group(2) else 0, |
| 61 | 'patch': int(m.group(3)) if m.group(3) else 0 | 61 | 'patch': int(m.group(3)) if m.group(3) else 0, |
| 62 | } | 62 | } |
| 63 | 63 | ||
| 64 | 64 | ||
diff --git a/lib/python/qmk/commands.py b/lib/python/qmk/commands.py index 4db4667a8..5a6e60988 100644 --- a/lib/python/qmk/commands.py +++ b/lib/python/qmk/commands.py | |||
| @@ -7,7 +7,6 @@ import subprocess | |||
| 7 | import shlex | 7 | import shlex |
| 8 | import shutil | 8 | import shutil |
| 9 | 9 | ||
| 10 | from milc import cli | ||
| 11 | import qmk.keymap | 10 | import qmk.keymap |
| 12 | 11 | ||
| 13 | 12 | ||
| @@ -84,6 +83,4 @@ def run(command, *args, **kwargs): | |||
| 84 | safecmd = ' '.join(safecmd) | 83 | safecmd = ' '.join(safecmd) |
| 85 | command = [os.environ['SHELL'], '-c', safecmd] | 84 | command = [os.environ['SHELL'], '-c', safecmd] |
| 86 | 85 | ||
| 87 | cli.log.debug('Running command: %s', command) | ||
| 88 | |||
| 89 | return subprocess.run(command, *args, **kwargs) | 86 | return subprocess.run(command, *args, **kwargs) |
diff --git a/lib/python/qmk/keymap.py b/lib/python/qmk/keymap.py index 78510a8a7..2b271fe80 100644 --- a/lib/python/qmk/keymap.py +++ b/lib/python/qmk/keymap.py | |||
| @@ -1,11 +1,18 @@ | |||
| 1 | """Functions that help you work with QMK keymaps. | 1 | """Functions that help you work with QMK keymaps. |
| 2 | """ | 2 | """ |
| 3 | from pathlib import Path | 3 | from pathlib import Path |
| 4 | import json | ||
| 5 | import subprocess | ||
| 6 | |||
| 7 | from pygments.lexers.c_cpp import CLexer | ||
| 8 | from pygments.token import Token | ||
| 9 | from pygments import lex | ||
| 4 | 10 | ||
| 5 | from milc import cli | 11 | from milc import cli |
| 6 | 12 | ||
| 7 | from qmk.keyboard import rules_mk | 13 | from qmk.keyboard import rules_mk |
| 8 | import qmk.path | 14 | import qmk.path |
| 15 | import qmk.commands | ||
| 9 | 16 | ||
| 10 | # The `keymap.c` template to use when a keyboard doesn't have its own | 17 | # The `keymap.c` template to use when a keyboard doesn't have its own |
| 11 | DEFAULT_KEYMAP_C = """#include QMK_KEYBOARD_H | 18 | DEFAULT_KEYMAP_C = """#include QMK_KEYBOARD_H |
| @@ -22,22 +29,35 @@ __KEYMAP_GOES_HERE__ | |||
| 22 | """ | 29 | """ |
| 23 | 30 | ||
| 24 | 31 | ||
| 25 | def template(keyboard): | 32 | def template(keyboard, type='c'): |
| 26 | """Returns the `keymap.c` template for a keyboard. | 33 | """Returns the `keymap.c` or `keymap.json` template for a keyboard. |
| 27 | 34 | ||
| 28 | If a template exists in `keyboards/<keyboard>/templates/keymap.c` that | 35 | If a template exists in `keyboards/<keyboard>/templates/keymap.c` that |
| 29 | text will be used instead of `DEFAULT_KEYMAP_C`. | 36 | text will be used instead of `DEFAULT_KEYMAP_C`. |
| 30 | 37 | ||
| 38 | If a template exists in `keyboards/<keyboard>/templates/keymap.json` that | ||
| 39 | text will be used instead of an empty dictionary. | ||
| 40 | |||
| 31 | Args: | 41 | Args: |
| 32 | keyboard | 42 | keyboard |
| 33 | The keyboard to return a template for. | 43 | The keyboard to return a template for. |
| 34 | """ | ||
| 35 | template_file = Path('keyboards/%s/templates/keymap.c' % keyboard) | ||
| 36 | 44 | ||
| 37 | if template_file.exists(): | 45 | type |
| 38 | return template_file.read_text() | 46 | 'json' for `keymap.json` and 'c' (or anything else) for `keymap.c` |
| 47 | """ | ||
| 48 | if type == 'json': | ||
| 49 | template_file = Path('keyboards/%s/templates/keymap.json' % keyboard) | ||
| 50 | template = {'keyboard': keyboard} | ||
| 51 | if template_file.exists(): | ||
| 52 | template.update(json.loads(template_file.read_text())) | ||
| 53 | else: | ||
| 54 | template_file = Path('keyboards/%s/templates/keymap.c' % keyboard) | ||
| 55 | if template_file.exists(): | ||
| 56 | template = template_file.read_text() | ||
| 57 | else: | ||
| 58 | template = DEFAULT_KEYMAP_C | ||
| 39 | 59 | ||
| 40 | return DEFAULT_KEYMAP_C | 60 | return template |
| 41 | 61 | ||
| 42 | 62 | ||
| 43 | def _strip_any(keycode): | 63 | def _strip_any(keycode): |
| @@ -57,8 +77,8 @@ def is_keymap_dir(keymap): | |||
| 57 | return True | 77 | return True |
| 58 | 78 | ||
| 59 | 79 | ||
| 60 | def generate(keyboard, layout, layers): | 80 | def generate(keyboard, layout, layers, type='c', keymap=None): |
| 61 | """Returns a keymap.c for the specified keyboard, layout, and layers. | 81 | """Returns a `keymap.c` or `keymap.json` for the specified keyboard, layout, and layers. |
| 62 | 82 | ||
| 63 | Args: | 83 | Args: |
| 64 | keyboard | 84 | keyboard |
| @@ -69,24 +89,30 @@ def generate(keyboard, layout, layers): | |||
| 69 | 89 | ||
| 70 | layers | 90 | layers |
| 71 | An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode. | 91 | An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode. |
| 72 | """ | ||
| 73 | layer_txt = [] | ||
| 74 | |||
| 75 | for layer_num, layer in enumerate(layers): | ||
| 76 | if layer_num != 0: | ||
| 77 | layer_txt[-1] = layer_txt[-1] + ',' | ||
| 78 | 92 | ||
| 79 | layer = map(_strip_any, layer) | 93 | type |
| 80 | layer_keys = ', '.join(layer) | 94 | 'json' for `keymap.json` and 'c' (or anything else) for `keymap.c` |
| 81 | layer_txt.append('\t[%s] = %s(%s)' % (layer_num, layout, layer_keys)) | 95 | """ |
| 82 | 96 | new_keymap = template(keyboard, type) | |
| 83 | keymap = '\n'.join(layer_txt) | 97 | if type == 'json': |
| 84 | keymap_c = template(keyboard) | 98 | new_keymap['keymap'] = keymap |
| 85 | 99 | new_keymap['layout'] = layout | |
| 86 | return keymap_c.replace('__KEYMAP_GOES_HERE__', keymap) | 100 | new_keymap['layers'] = layers |
| 87 | 101 | else: | |
| 88 | 102 | layer_txt = [] | |
| 89 | def write(keyboard, keymap, layout, layers): | 103 | for layer_num, layer in enumerate(layers): |
| 104 | if layer_num != 0: | ||
| 105 | layer_txt[-1] = layer_txt[-1] + ',' | ||
| 106 | layer_keys = ', '.join(layer) | ||
| 107 | layer_txt.append('\t[%s] = %s(%s)' % (layer_num, layout, layer_keys)) | ||
| 108 | |||
| 109 | keymap = '\n'.join(layer_txt) | ||
| 110 | new_keymap = new_keymap.replace('__KEYMAP_GOES_HERE__', keymap) | ||
| 111 | |||
| 112 | return new_keymap | ||
| 113 | |||
| 114 | |||
| 115 | def write(keyboard, keymap, layout, layers, type='c'): | ||
| 90 | """Generate the `keymap.c` and write it to disk. | 116 | """Generate the `keymap.c` and write it to disk. |
| 91 | 117 | ||
| 92 | Returns the filename written to. | 118 | Returns the filename written to. |
| @@ -103,12 +129,19 @@ def write(keyboard, keymap, layout, layers): | |||
| 103 | 129 | ||
| 104 | layers | 130 | layers |
| 105 | An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode. | 131 | An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode. |
| 132 | |||
| 133 | type | ||
| 134 | 'json' for `keymap.json` and 'c' (or anything else) for `keymap.c` | ||
| 106 | """ | 135 | """ |
| 107 | keymap_c = generate(keyboard, layout, layers) | 136 | keymap_content = generate(keyboard, layout, layers, type) |
| 108 | keymap_file = qmk.path.keymap(keyboard) / keymap / 'keymap.c' | 137 | if type == 'json': |
| 138 | keymap_file = qmk.path.keymap(keyboard) / keymap / 'keymap.json' | ||
| 139 | keymap_content = json.dumps(keymap_content) | ||
| 140 | else: | ||
| 141 | keymap_file = qmk.path.keymap(keyboard) / keymap / 'keymap.c' | ||
| 109 | 142 | ||
| 110 | keymap_file.parent.mkdir(parents=True, exist_ok=True) | 143 | keymap_file.parent.mkdir(parents=True, exist_ok=True) |
| 111 | keymap_file.write_text(keymap_c) | 144 | keymap_file.write_text(keymap_content) |
| 112 | 145 | ||
| 113 | cli.log.info('Wrote keymap to {fg_cyan}%s', keymap_file) | 146 | cli.log.info('Wrote keymap to {fg_cyan}%s', keymap_file) |
| 114 | 147 | ||
| @@ -188,3 +221,192 @@ def list_keymaps(keyboard): | |||
| 188 | names = names.union([keymap.name for keymap in cl_path.iterdir() if is_keymap_dir(keymap)]) | 221 | names = names.union([keymap.name for keymap in cl_path.iterdir() if is_keymap_dir(keymap)]) |
| 189 | 222 | ||
| 190 | return sorted(names) | 223 | return sorted(names) |
| 224 | |||
| 225 | |||
| 226 | def _c_preprocess(path): | ||
| 227 | """ Run a file through the C pre-processor | ||
| 228 | |||
| 229 | Args: | ||
| 230 | path: path of the keymap.c file | ||
| 231 | |||
| 232 | Returns: | ||
| 233 | the stdout of the pre-processor | ||
| 234 | """ | ||
| 235 | pre_processed_keymap = qmk.commands.run(['cpp', path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) | ||
| 236 | return pre_processed_keymap.stdout | ||
| 237 | |||
| 238 | |||
| 239 | def _get_layers(keymap): # noqa C901 : until someone has a good idea how to simplify/split up this code | ||
| 240 | """ Find the layers in a keymap.c file. | ||
| 241 | |||
| 242 | Args: | ||
| 243 | keymap: the content of the keymap.c file | ||
| 244 | |||
| 245 | Returns: | ||
| 246 | a dictionary containing the parsed keymap | ||
| 247 | """ | ||
| 248 | layers = list() | ||
| 249 | opening_braces = '({[' | ||
| 250 | closing_braces = ')}]' | ||
| 251 | keymap_certainty = brace_depth = 0 | ||
| 252 | is_keymap = is_layer = is_adv_kc = False | ||
| 253 | layer = dict(name=False, layout=False, keycodes=list()) | ||
| 254 | for line in lex(keymap, CLexer()): | ||
| 255 | if line[0] is Token.Name: | ||
| 256 | if is_keymap: | ||
| 257 | # If we are inside the keymap array | ||
| 258 | # we know the keymap's name and the layout macro will come, | ||
| 259 | # followed by the keycodes | ||
| 260 | if not layer['name']: | ||
| 261 | if line[1].startswith('LAYOUT') or line[1].startswith('KEYMAP'): | ||
| 262 | # This can happen if the keymap array only has one layer, | ||
| 263 | # for macropads and such | ||
| 264 | layer['name'] = '0' | ||
| 265 | layer['layout'] = line[1] | ||
| 266 | else: | ||
| 267 | layer['name'] = line[1] | ||
| 268 | elif not layer['layout']: | ||
| 269 | layer['layout'] = line[1] | ||
| 270 | elif is_layer: | ||
| 271 | # If we are inside a layout macro, | ||
| 272 | # collect all keycodes | ||
| 273 | if line[1] == '_______': | ||
| 274 | kc = 'KC_TRNS' | ||
| 275 | elif line[1] == 'XXXXXXX': | ||
| 276 | kc = 'KC_NO' | ||
| 277 | else: | ||
| 278 | kc = line[1] | ||
| 279 | if is_adv_kc: | ||
| 280 | # If we are inside an advanced keycode | ||
| 281 | # collect everything and hope the user | ||
| 282 | # knew what he/she was doing | ||
| 283 | layer['keycodes'][-1] += kc | ||
| 284 | else: | ||
| 285 | layer['keycodes'].append(kc) | ||
| 286 | |||
| 287 | # The keymaps array's signature: | ||
| 288 | # const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] | ||
| 289 | # | ||
| 290 | # Only if we've found all 6 keywords in this specific order | ||
| 291 | # can we know for sure that we are inside the keymaps array | ||
| 292 | elif line[1] == 'PROGMEM' and keymap_certainty == 2: | ||
| 293 | keymap_certainty = 3 | ||
| 294 | elif line[1] == 'keymaps' and keymap_certainty == 3: | ||
| 295 | keymap_certainty = 4 | ||
| 296 | elif line[1] == 'MATRIX_ROWS' and keymap_certainty == 4: | ||
| 297 | keymap_certainty = 5 | ||
| 298 | elif line[1] == 'MATRIX_COLS' and keymap_certainty == 5: | ||
| 299 | keymap_certainty = 6 | ||
| 300 | elif line[0] is Token.Keyword: | ||
| 301 | if line[1] == 'const' and keymap_certainty == 0: | ||
| 302 | keymap_certainty = 1 | ||
| 303 | elif line[0] is Token.Keyword.Type: | ||
| 304 | if line[1] == 'uint16_t' and keymap_certainty == 1: | ||
| 305 | keymap_certainty = 2 | ||
| 306 | elif line[0] is Token.Punctuation: | ||
| 307 | if line[1] in opening_braces: | ||
| 308 | brace_depth += 1 | ||
| 309 | if is_keymap: | ||
| 310 | if is_layer: | ||
| 311 | # We found the beginning of a non-basic keycode | ||
| 312 | is_adv_kc = True | ||
| 313 | layer['keycodes'][-1] += line[1] | ||
| 314 | elif line[1] == '(' and brace_depth == 2: | ||
| 315 | # We found the beginning of a layer | ||
| 316 | is_layer = True | ||
| 317 | elif line[1] == '{' and keymap_certainty == 6: | ||
| 318 | # We found the beginning of the keymaps array | ||
| 319 | is_keymap = True | ||
| 320 | elif line[1] in closing_braces: | ||
| 321 | brace_depth -= 1 | ||
| 322 | if is_keymap: | ||
| 323 | if is_adv_kc: | ||
| 324 | layer['keycodes'][-1] += line[1] | ||
| 325 | if brace_depth == 2: | ||
| 326 | # We found the end of a non-basic keycode | ||
| 327 | is_adv_kc = False | ||
| 328 | elif line[1] == ')' and brace_depth == 1: | ||
| 329 | # We found the end of a layer | ||
| 330 | is_layer = False | ||
| 331 | layers.append(layer) | ||
| 332 | layer = dict(name=False, layout=False, keycodes=list()) | ||
| 333 | elif line[1] == '}' and brace_depth == 0: | ||
| 334 | # We found the end of the keymaps array | ||
| 335 | is_keymap = False | ||
| 336 | keymap_certainty = 0 | ||
| 337 | elif is_adv_kc: | ||
| 338 | # Advanced keycodes can contain other punctuation | ||
| 339 | # e.g.: MT(MOD_LCTL | MOD_LSFT, KC_ESC) | ||
| 340 | layer['keycodes'][-1] += line[1] | ||
| 341 | |||
| 342 | elif line[0] is Token.Literal.Number.Integer and is_keymap and not is_adv_kc: | ||
| 343 | # If the pre-processor finds the 'meaning' of the layer names, | ||
| 344 | # they will be numbers | ||
| 345 | if not layer['name']: | ||
| 346 | layer['name'] = line[1] | ||
| 347 | |||
| 348 | else: | ||
| 349 | # We only care about | ||
| 350 | # operators and such if we | ||
| 351 | # are inside an advanced keycode | ||
| 352 | # e.g.: MT(MOD_LCTL | MOD_LSFT, KC_ESC) | ||
| 353 | if is_adv_kc: | ||
| 354 | layer['keycodes'][-1] += line[1] | ||
| 355 | |||
| 356 | return layers | ||
| 357 | |||
| 358 | |||
| 359 | def parse_keymap_c(keymap_file, use_cpp=True): | ||
| 360 | """ Parse a keymap.c file. | ||
| 361 | |||
| 362 | Currently only cares about the keymaps array. | ||
| 363 | |||
| 364 | Args: | ||
| 365 | keymap_file: path of the keymap.c file | ||
| 366 | |||
| 367 | use_cpp: if True, pre-process the file with the C pre-processor | ||
| 368 | |||
| 369 | Returns: | ||
| 370 | a dictionary containing the parsed keymap | ||
| 371 | """ | ||
| 372 | if use_cpp: | ||
| 373 | keymap_file = _c_preprocess(keymap_file) | ||
| 374 | else: | ||
| 375 | keymap_file = keymap_file.read_text() | ||
| 376 | |||
| 377 | keymap = dict() | ||
| 378 | keymap['layers'] = _get_layers(keymap_file) | ||
| 379 | return keymap | ||
| 380 | |||
| 381 | |||
| 382 | def c2json(keyboard, keymap, keymap_file, use_cpp=True): | ||
| 383 | """ Convert keymap.c to keymap.json | ||
| 384 | |||
| 385 | Args: | ||
| 386 | keyboard: The name of the keyboard | ||
| 387 | |||
| 388 | keymap: The name of the keymap | ||
| 389 | |||
| 390 | layout: The LAYOUT macro this keymap uses. | ||
| 391 | |||
| 392 | keymap_file: path of the keymap.c file | ||
| 393 | |||
| 394 | use_cpp: if True, pre-process the file with the C pre-processor | ||
| 395 | |||
| 396 | Returns: | ||
| 397 | a dictionary in keymap.json format | ||
| 398 | """ | ||
| 399 | keymap_json = parse_keymap_c(keymap_file, use_cpp) | ||
| 400 | |||
| 401 | dirty_layers = keymap_json.pop('layers', None) | ||
| 402 | keymap_json['layers'] = list() | ||
| 403 | for layer in dirty_layers: | ||
| 404 | layer.pop('name') | ||
| 405 | layout = layer.pop('layout') | ||
| 406 | if not keymap_json.get('layout', False): | ||
| 407 | keymap_json['layout'] = layout | ||
| 408 | keymap_json['layers'].append(layer.pop('keycodes')) | ||
| 409 | |||
| 410 | keymap_json['keyboard'] = keyboard | ||
| 411 | keymap_json['keymap'] = keymap | ||
| 412 | return keymap_json | ||
diff --git a/lib/python/qmk/tests/test_cli_commands.py b/lib/python/qmk/tests/test_cli_commands.py index 0b840b466..7ac0bcbde 100644 --- a/lib/python/qmk/tests/test_cli_commands.py +++ b/lib/python/qmk/tests/test_cli_commands.py | |||
| @@ -1,10 +1,11 @@ | |||
| 1 | import subprocess | 1 | from subprocess import STDOUT, PIPE |
| 2 | |||
| 2 | from qmk.commands import run | 3 | from qmk.commands import run |
| 3 | 4 | ||
| 4 | 5 | ||
| 5 | def check_subcommand(command, *args): | 6 | def check_subcommand(command, *args): |
| 6 | cmd = ['bin/qmk', command] + list(args) | 7 | cmd = ['bin/qmk', command] + list(args) |
| 7 | result = run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) | 8 | result = run(cmd, stdout=PIPE, stderr=STDOUT, universal_newlines=True) |
| 8 | return result | 9 | return result |
| 9 | 10 | ||
| 10 | 11 | ||
| @@ -28,6 +29,11 @@ def test_compile(): | |||
| 28 | check_returncode(result) | 29 | check_returncode(result) |
| 29 | 30 | ||
| 30 | 31 | ||
| 32 | def test_compile_json(): | ||
| 33 | result = check_subcommand('compile', '-kb', 'handwired/onekey/pytest', '-km', 'default_json') | ||
| 34 | check_returncode(result) | ||
| 35 | |||
| 36 | |||
| 31 | def test_flash(): | 37 | def test_flash(): |
| 32 | result = check_subcommand('flash', '-kb', 'handwired/onekey/pytest', '-km', 'default', '-n') | 38 | result = check_subcommand('flash', '-kb', 'handwired/onekey/pytest', '-km', 'default', '-n') |
| 33 | check_returncode(result) | 39 | check_returncode(result) |
| @@ -153,3 +159,15 @@ def test_info_matrix_render(): | |||
| 153 | assert 'LAYOUT_ortho_1x1' in result.stdout | 159 | assert 'LAYOUT_ortho_1x1' in result.stdout |
| 154 | assert '│0A│' in result.stdout | 160 | assert '│0A│' in result.stdout |
| 155 | assert 'Matrix for "LAYOUT_ortho_1x1"' in result.stdout | 161 | assert 'Matrix for "LAYOUT_ortho_1x1"' in result.stdout |
| 162 | |||
| 163 | |||
| 164 | def test_c2json(): | ||
| 165 | result = check_subcommand("c2json", "-kb", "handwired/onekey/pytest", "-km", "default", "keyboards/handwired/onekey/keymaps/default/keymap.c") | ||
| 166 | check_returncode(result) | ||
| 167 | assert result.stdout.strip() == '{"keyboard": "handwired/onekey/pytest", "documentation": "This file is a keymap.json file for handwired/onekey/pytest", "keymap": "default", "layout": "LAYOUT_ortho_1x1", "layers": [["KC_A"]]}' | ||
| 168 | |||
| 169 | |||
| 170 | def test_c2json_nocpp(): | ||
| 171 | result = check_subcommand("c2json", "--no-cpp", "-kb", "handwired/onekey/pytest", "-km", "default", "keyboards/handwired/onekey/keymaps/pytest_nocpp/keymap.c") | ||
| 172 | check_returncode(result) | ||
| 173 | assert result.stdout.strip() == '{"keyboard": "handwired/onekey/pytest", "documentation": "This file is a keymap.json file for handwired/onekey/pytest", "keymap": "default", "layout": "LAYOUT", "layers": [["KC_ENTER"]]}' | ||
diff --git a/lib/python/qmk/tests/test_qmk_keymap.py b/lib/python/qmk/tests/test_qmk_keymap.py index d8669e549..7ef708e0d 100644 --- a/lib/python/qmk/tests/test_qmk_keymap.py +++ b/lib/python/qmk/tests/test_qmk_keymap.py | |||
| @@ -6,14 +6,34 @@ def test_template_onekey_proton_c(): | |||
| 6 | assert templ == qmk.keymap.DEFAULT_KEYMAP_C | 6 | assert templ == qmk.keymap.DEFAULT_KEYMAP_C |
| 7 | 7 | ||
| 8 | 8 | ||
| 9 | def test_template_onekey_proton_c_json(): | ||
| 10 | templ = qmk.keymap.template('handwired/onekey/proton_c', type='json') | ||
| 11 | assert templ == {'keyboard': 'handwired/onekey/proton_c'} | ||
| 12 | |||
| 13 | |||
| 9 | def test_template_onekey_pytest(): | 14 | def test_template_onekey_pytest(): |
| 10 | templ = qmk.keymap.template('handwired/onekey/pytest') | 15 | templ = qmk.keymap.template('handwired/onekey/pytest') |
| 11 | assert templ == '#include QMK_KEYBOARD_H\nconst uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {__KEYMAP_GOES_HERE__};\n' | 16 | assert templ == '#include QMK_KEYBOARD_H\nconst uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {__KEYMAP_GOES_HERE__};\n' |
| 12 | 17 | ||
| 13 | 18 | ||
| 19 | def test_template_onekey_pytest_json(): | ||
| 20 | templ = qmk.keymap.template('handwired/onekey/pytest', type='json') | ||
| 21 | assert templ == {'keyboard': 'handwired/onekey/pytest', "documentation": "This file is a keymap.json file for handwired/onekey/pytest"} | ||
| 22 | |||
| 23 | |||
| 14 | def test_generate_onekey_pytest(): | 24 | def test_generate_onekey_pytest(): |
| 15 | templ = qmk.keymap.generate('handwired/onekey/pytest', 'LAYOUT', [['KC_A']]) | 25 | templ = qmk.keymap.generate('handwired/onekey/pytest', 'LAYOUT', [['KC_A']]) |
| 16 | assert templ == '#include QMK_KEYBOARD_H\nconst uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {\t[0] = LAYOUT(KC_A)};\n' | 26 | assert templ == '#include QMK_KEYBOARD_H\nconst uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {\t[0] = LAYOUT(KC_A)};\n' |
| 17 | 27 | ||
| 18 | 28 | ||
| 29 | def test_generate_onekey_pytest_json(): | ||
| 30 | templ = qmk.keymap.generate('handwired/onekey/pytest', 'LAYOUT', [['KC_A']], type='json', keymap='default') | ||
| 31 | assert templ == {"keyboard": "handwired/onekey/pytest", "documentation": "This file is a keymap.json file for handwired/onekey/pytest", "keymap": "default", "layout": "LAYOUT", "layers": [["KC_A"]]} | ||
| 32 | |||
| 33 | |||
| 34 | def test_parse_keymap_c(): | ||
| 35 | parsed_keymap_c = qmk.keymap.parse_keymap_c('keyboards/handwired/onekey/keymaps/default/keymap.c') | ||
| 36 | assert parsed_keymap_c == {'layers': [{'name': '0', 'layout': 'LAYOUT_ortho_1x1', 'keycodes': ['KC_A']}]} | ||
| 37 | |||
| 38 | |||
| 19 | # FIXME(skullydazed): Add a test for qmk.keymap.write that mocks up an FD. | 39 | # FIXME(skullydazed): Add a test for qmk.keymap.write that mocks up an FD. |
