summaryrefslogtreecommitdiff
path: root/lib/python/qmk/cli/generate/keyboard_h.py
blob: f05178cedef76c80290ad39b0d0d089d0b77203b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""Used by the make system to generate keyboard.h from info.json.
"""
from milc import cli

from qmk.info import info_json
from qmk.keyboard import keyboard_completer, keyboard_folder
from qmk.path import normpath


def would_populate_layout_h(keyboard):
    """Detect if a given keyboard is doing data driven layouts
    """
    # Build the info.json file
    kb_info_json = info_json(keyboard)

    for layout_name in kb_info_json['layouts']:
        if kb_info_json['layouts'][layout_name]['c_macro']:
            continue

        if 'matrix' not in kb_info_json['layouts'][layout_name]['layout'][0]:
            cli.log.debug('%s/%s: No matrix data!', keyboard, layout_name)
            continue

        return True

    return False


@cli.argument('-o', '--output', arg_only=True, type=normpath, help='File to write to')
@cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
@cli.argument('-kb', '--keyboard', arg_only=True, type=keyboard_folder, completer=keyboard_completer, required=True, help='Keyboard to generate keyboard.h for.')
@cli.subcommand('Used by the make system to generate keyboard.h from info.json', hidden=True)
def generate_keyboard_h(cli):
    """Generates the keyboard.h file.
    """
    has_layout_h = would_populate_layout_h(cli.args.keyboard)

    # Build the layouts.h file.
    keyboard_h_lines = ['/* This file was generated by `qmk generate-keyboard-h`. Do not edit or copy.', ' */', '', '#pragma once', '#include "quantum.h"']

    if not has_layout_h:
        keyboard_h_lines.append('#pragma error("<keyboard>.h is only optional for data driven keyboards - kb.h == bad times")')

    # Show the results
    keyboard_h = '\n'.join(keyboard_h_lines) + '\n'

    if cli.args.output:
        cli.args.output.parent.mkdir(parents=True, exist_ok=True)
        if cli.args.output.exists():
            cli.args.output.replace(cli.args.output.parent / (cli.args.output.name + '.bak'))
        cli.args.output.write_text(keyboard_h)

        if not cli.args.quiet:
            cli.log.info('Wrote keyboard_h to %s.', cli.args.output)

    else:
        print(keyboard_h)