summaryrefslogtreecommitdiff
path: root/lib/python/qmk/cli
diff options
context:
space:
mode:
Diffstat (limited to 'lib/python/qmk/cli')
-rw-r--r--lib/python/qmk/cli/__init__.py1
-rw-r--r--lib/python/qmk/cli/cformat.py10
-rwxr-xr-xlib/python/qmk/cli/compile.py4
-rwxr-xr-xlib/python/qmk/cli/doctor.py62
-rwxr-xr-xlib/python/qmk/cli/info.py158
-rwxr-xr-xlib/python/qmk/cli/json2c.py12
-rw-r--r--lib/python/qmk/cli/list/keymaps.py18
7 files changed, 223 insertions, 42 deletions
diff --git a/lib/python/qmk/cli/__init__.py b/lib/python/qmk/cli/__init__.py
index 394a1353bc..47f60c601b 100644
--- a/lib/python/qmk/cli/__init__.py
+++ b/lib/python/qmk/cli/__init__.py
@@ -13,6 +13,7 @@ from . import docs
from . import doctor
from . import flash
from . import hello
+from . import info
from . import json
from . import json2c
from . import list
diff --git a/lib/python/qmk/cli/cformat.py b/lib/python/qmk/cli/cformat.py
index 0cd8b6192a..600161c5c5 100644
--- a/lib/python/qmk/cli/cformat.py
+++ b/lib/python/qmk/cli/cformat.py
@@ -4,7 +4,9 @@ import subprocess
from shutil import which
from milc import cli
-import qmk.path
+
+from qmk.path import normpath
+from qmk.c_parse import c_source_files
def cformat_run(files, all_files):
@@ -45,10 +47,10 @@ def cformat(cli):
ignores = ['tmk_core/protocol/usb_hid', 'quantum/template']
# Find the list of files to format
if cli.args.files:
- files.extend(qmk.path.normpath(file) for file in cli.args.files)
+ files.extend(normpath(file) for file in cli.args.files)
# If -a is specified
elif cli.args.all_files:
- all_files = qmk.path.c_source_files(core_dirs)
+ all_files = c_source_files(core_dirs)
# The following statement checks each file to see if the file path is in the ignored directories.
files.extend(file for file in all_files if not any(i in str(file) for i in ignores))
# No files specified & no -a flag
@@ -56,7 +58,7 @@ def cformat(cli):
base_args = ['git', 'diff', '--name-only', cli.args.base_branch]
out = subprocess.run(base_args + core_dirs, check=True, stdout=subprocess.PIPE)
changed_files = filter(None, out.stdout.decode('UTF-8').split('\n'))
- filtered_files = [qmk.path.normpath(file) for file in changed_files if not any(i in file for i in ignores)]
+ filtered_files = [normpath(file) for file in changed_files if not any(i in file for i in ignores)]
files.extend(file for file in filtered_files if file.exists() and file.suffix in ['.c', '.h', '.cpp'])
# Run clang-format on the files we've found
diff --git a/lib/python/qmk/cli/compile.py b/lib/python/qmk/cli/compile.py
index 6480d624b0..341f365f8c 100755
--- a/lib/python/qmk/cli/compile.py
+++ b/lib/python/qmk/cli/compile.py
@@ -7,7 +7,6 @@ from argparse import FileType
from milc import cli
-import qmk.path
from qmk.decorators import automagic_keyboard, automagic_keymap
from qmk.commands import compile_configurator_json, create_make_command, parse_configurator_json
@@ -32,11 +31,8 @@ def compile(cli):
# If a configurator JSON was provided generate a keymap and compile it
# FIXME(skullydazed): add code to check and warn if the keymap already exists when compiling a json keymap.
user_keymap = parse_configurator_json(cli.args.filename)
- keymap_path = qmk.path.keymap(user_keymap['keyboard'])
command = compile_configurator_json(user_keymap)
- cli.log.info('Wrote keymap to {fg_cyan}%s/%s/keymap.c', keymap_path, user_keymap['keymap'])
-
else:
if cli.config.compile.keyboard and cli.config.compile.keymap:
# Generate the make command for a specific keyboard/keymap.
diff --git a/lib/python/qmk/cli/doctor.py b/lib/python/qmk/cli/doctor.py
index 3c46248372..011c3dd3c2 100755
--- a/lib/python/qmk/cli/doctor.py
+++ b/lib/python/qmk/cli/doctor.py
@@ -24,12 +24,26 @@ ESSENTIAL_BINARIES = {
},
'bin/qmk': {},
}
-ESSENTIAL_SUBMODULES = ['lib/chibios', 'lib/lufa']
-def _udev_rule(vid, pid=None):
+def _udev_rule(vid, pid=None, *args):
""" Helper function that return udev rules
"""
+ rule = ""
+ if pid:
+ rule = 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", ATTRS{idProduct}=="%s", TAG+="uaccess", RUN{builtin}+="uaccess"' % (vid, pid)
+ else:
+ rule = 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", TAG+="uaccess", RUN{builtin}+="uaccess"' % vid
+ if args:
+ rule = ', '.join([rule, *args])
+ return rule
+
+
+def _deprecated_udev_rule(vid, pid=None):
+ """ Helper function that return udev rules
+
+ Note: these are no longer the recommended rules, this is just used to check for them
+ """
if pid:
return 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", ATTRS{idProduct}=="%s", MODE:="0666"' % (vid, pid)
else:
@@ -109,14 +123,11 @@ def check_submodules():
for submodule in submodules.status().values():
if submodule['status'] is None:
- if submodule['name'] in ESSENTIAL_SUBMODULES:
- cli.log.error('Submodule %s has not yet been cloned!', submodule['name'])
- ok = False
- else:
- cli.log.warn('Submodule %s is not available.', submodule['name'])
+ cli.log.error('Submodule %s has not yet been cloned!', submodule['name'])
+ ok = False
elif not submodule['status']:
- if submodule['name'] in ESSENTIAL_SUBMODULES:
- cli.log.warn('Submodule %s is not up to date!')
+ cli.log.error('Submodule %s is not up to date!', submodule['name'])
+ ok = False
return ok
@@ -128,10 +139,24 @@ def check_udev_rules():
udev_dir = Path("/etc/udev/rules.d/")
desired_rules = {
'dfu': {_udev_rule("03eb", "2ff4"), _udev_rule("03eb", "2ffb"), _udev_rule("03eb", "2ff0")},
- 'tmk': {_udev_rule("feed")},
- 'input_club': {_udev_rule("1c11")},
+ 'input_club': {_udev_rule("1c11", "b007")},
'stm32': {_udev_rule("1eaf", "0003"), _udev_rule("0483", "df11")},
- 'caterina': {'ATTRS{idVendor}=="2a03", ENV{ID_MM_DEVICE_IGNORE}="1"', 'ATTRS{idVendor}=="2341", ENV{ID_MM_DEVICE_IGNORE}="1"'},
+ 'bootloadhid': {_udev_rule("16c0", "05df")},
+ 'caterina': {
+ _udev_rule("2341", "0036", 'ENV{ID_MM_DEVICE_IGNORE}="1"'),
+ _udev_rule("1b4f", "9205", 'ENV{ID_MM_DEVICE_IGNORE}="1"'),
+ _udev_rule("1b4f", "9203", 'ENV{ID_MM_DEVICE_IGNORE}="1"'),
+ _udev_rule("2a03", "0036", 'ENV{ID_MM_DEVICE_IGNORE}="1"')
+ }
+ }
+
+ # These rules are no longer recommended, only use them to check for their presence.
+ deprecated_rules = {
+ 'dfu': {_deprecated_udev_rule("03eb", "2ff4"), _deprecated_udev_rule("03eb", "2ffb"), _deprecated_udev_rule("03eb", "2ff0")},
+ 'input_club': {_deprecated_udev_rule("1c11")},
+ 'stm32': {_deprecated_udev_rule("1eaf", "0003"), _deprecated_udev_rule("0483", "df11")},
+ 'bootloadhid': {_deprecated_udev_rule("16c0", "05df")},
+ 'caterina': {'ATTRS{idVendor}=="2a03", ENV{ID_MM_DEVICE_IGNORE}="1"', 'ATTRS{idVendor}=="2341", ENV{ID_MM_DEVICE_IGNORE}="1"'}
}
if udev_dir.exists():
@@ -147,12 +172,15 @@ def check_udev_rules():
# Check if the desired rules are among the currently present rules
for bootloader, rules in desired_rules.items():
+ # For caterina, check if ModemManager is running
+ if bootloader == "caterina":
+ if check_modem_manager():
+ ok = False
+ cli.log.warn("{bg_yellow}Detected ModemManager without the necessary udev rules. Please either disable it or set the appropriate udev rules if you are using a Pro Micro.")
if not rules.issubset(current_rules):
- # If the rules for catalina are not present, check if ModemManager is running
- if bootloader == "caterina":
- if check_modem_manager():
- ok = False
- cli.log.warn("{bg_yellow}Detected ModemManager without udev rules. Please either disable it or set the appropriate udev rules if you are using a Pro Micro.")
+ deprecated_rule = deprecated_rules.get(bootloader)
+ if deprecated_rule and deprecated_rule.issubset(current_rules):
+ cli.log.warn("{bg_yellow}Found old, deprecated udev rules for '%s' boards. The new rules on https://docs.qmk.fm/#/faq_build?id=linux-udev-rules offer better security with the same functionality.", bootloader)
else:
cli.log.warn("{bg_yellow}Missing udev rules for '%s' boards. You'll need to use `sudo` in order to flash them.", bootloader)
diff --git a/lib/python/qmk/cli/info.py b/lib/python/qmk/cli/info.py
new file mode 100755
index 0000000000..5e4b391411
--- /dev/null
+++ b/lib/python/qmk/cli/info.py
@@ -0,0 +1,158 @@
+"""Keyboard information script.
+
+Compile an info.json for a particular keyboard and pretty-print it.
+"""
+import json
+
+from milc import cli
+
+from qmk.decorators import automagic_keyboard, automagic_keymap
+from qmk.keyboard import render_layouts, render_layout
+from qmk.keymap import locate_keymap
+from qmk.info import info_json
+from qmk.path import is_keyboard
+
+ROW_LETTERS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop'
+COL_LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijilmnopqrstuvwxyz'
+
+
+def show_keymap(info_json, title_caps=True):
+ """Render the keymap in ascii art.
+ """
+ keymap_path = locate_keymap(cli.config.info.keyboard, cli.config.info.keymap)
+
+ if keymap_path and keymap_path.suffix == '.json':
+ if title_caps:
+ cli.echo('{fg_blue}Keymap "%s"{fg_reset}:', cli.config.info.keymap)
+ else:
+ cli.echo('{fg_blue}keymap_%s{fg_reset}:', cli.config.info.keymap)
+
+ keymap_data = json.load(keymap_path.open())
+ layout_name = keymap_data['layout']
+
+ for layer_num, layer in enumerate(keymap_data['layers']):
+ if title_caps:
+ cli.echo('{fg_cyan}Layer %s{fg_reset}:', layer_num)
+ else:
+ cli.echo('{fg_cyan}layer_%s{fg_reset}:', layer_num)
+
+ print(render_layout(info_json['layouts'][layout_name]['layout'], layer))
+
+
+def show_layouts(kb_info_json, title_caps=True):
+ """Render the layouts with info.json labels.
+ """
+ for layout_name, layout_art in render_layouts(kb_info_json).items():
+ title = layout_name.title() if title_caps else layout_name
+ cli.echo('{fg_cyan}%s{fg_reset}:', title)
+ print(layout_art) # Avoid passing dirty data to cli.echo()
+
+
+def show_matrix(info_json, title_caps=True):
+ """Render the layout with matrix labels in ascii art.
+ """
+ for layout_name, layout in info_json['layouts'].items():
+ # Build our label list
+ labels = []
+ for key in layout['layout']:
+ if key['matrix']:
+ row = ROW_LETTERS[key['matrix'][0]]
+ col = COL_LETTERS[key['matrix'][1]]
+
+ labels.append(row + col)
+ else:
+ labels.append('')
+
+ # Print the header
+ if title_caps:
+ cli.echo('{fg_blue}Matrix for "%s"{fg_reset}:', layout_name)
+ else:
+ cli.echo('{fg_blue}matrix_%s{fg_reset}:', layout_name)
+
+ print(render_layout(info_json['layouts'][layout_name]['layout'], labels))
+
+
+def print_friendly_output(info_json):
+ """Print the info.json in a friendly text format.
+ """
+ cli.echo('{fg_blue}Keyboard Name{fg_reset}: %s', info_json.get('keyboard_name', 'Unknown'))
+ cli.echo('{fg_blue}Manufacturer{fg_reset}: %s', info_json.get('manufacturer', 'Unknown'))
+ if 'url' in info_json:
+ cli.echo('{fg_blue}Website{fg_reset}: %s', info_json.get('url', ''))
+ if info_json.get('maintainer', 'qmk') == 'qmk':
+ cli.echo('{fg_blue}Maintainer{fg_reset}: QMK Community')
+ else:
+ cli.echo('{fg_blue}Maintainer{fg_reset}: %s', info_json['maintainer'])
+ cli.echo('{fg_blue}Keyboard Folder{fg_reset}: %s', info_json.get('keyboard_folder', 'Unknown'))
+ cli.echo('{fg_blue}Layouts{fg_reset}: %s', ', '.join(sorted(info_json['layouts'].keys())))
+ if 'width' in info_json and 'height' in info_json:
+ cli.echo('{fg_blue}Size{fg_reset}: %s x %s' % (info_json['width'], info_json['height']))
+ cli.echo('{fg_blue}Processor{fg_reset}: %s', info_json.get('processor', 'Unknown'))
+ cli.echo('{fg_blue}Bootloader{fg_reset}: %s', info_json.get('bootloader', 'Unknown'))
+
+ if cli.config.info.layouts:
+ show_layouts(info_json, True)
+
+ if cli.config.info.matrix:
+ show_matrix(info_json, True)
+
+ if cli.config_source.info.keymap and cli.config_source.info.keymap != 'config_file':
+ show_keymap(info_json, True)
+
+
+def print_text_output(info_json):
+ """Print the info.json in a plain text format.
+ """
+ for key in sorted(info_json):
+ if key == 'layouts':
+ cli.echo('{fg_blue}layouts{fg_reset}: %s', ', '.join(sorted(info_json['layouts'].keys())))
+ else:
+ cli.echo('{fg_blue}%s{fg_reset}: %s', key, info_json[key])
+
+ if cli.config.info.layouts:
+ show_layouts(info_json, False)
+
+ if cli.config.info.matrix:
+ show_matrix(info_json, False)
+
+ if cli.config_source.info.keymap and cli.config_source.info.keymap != 'config_file':
+ show_keymap(info_json, False)
+
+
+@cli.argument('-kb', '--keyboard', help='Keyboard to show info for.')
+@cli.argument('-km', '--keymap', help='Show the layers for a JSON keymap too.')
+@cli.argument('-l', '--layouts', action='store_true', help='Render the layouts.')
+@cli.argument('-m', '--matrix', action='store_true', help='Render the layouts with matrix information.')
+@cli.argument('-f', '--format', default='friendly', arg_only=True, help='Format to display the data in (friendly, text, json) (Default: friendly).')
+@cli.subcommand('Keyboard information.')
+@automagic_keyboard
+@automagic_keymap
+def info(cli):
+ """Compile an info.json for a particular keyboard and pretty-print it.
+ """
+ # Determine our keyboard(s)
+ if not cli.config.info.keyboard:
+ cli.log.error('Missing paramater: --keyboard')
+ cli.subcommands['info'].print_help()
+ exit(1)
+
+ if not is_keyboard(cli.config.info.keyboard):
+ cli.log.error('Invalid keyboard: "%s"', cli.config.info.keyboard)
+ exit(1)
+
+ # Build the info.json file
+ kb_info_json = info_json(cli.config.info.keyboard)
+
+ # Output in the requested format
+ if cli.args.format == 'json':
+ print(json.dumps(kb_info_json))
+ exit()
+
+ if cli.args.format == 'text':
+ print_text_output(kb_info_json)
+
+ elif cli.args.format == 'friendly':
+ print_friendly_output(kb_info_json)
+
+ else:
+ cli.log.error('Unknown format: %s', cli.args.format)
diff --git a/lib/python/qmk/cli/json2c.py b/lib/python/qmk/cli/json2c.py
index 5218405070..af0d80a9ac 100755
--- a/lib/python/qmk/cli/json2c.py
+++ b/lib/python/qmk/cli/json2c.py
@@ -18,19 +18,19 @@ def json2c(cli):
This command uses the `qmk.keymap` module to generate a keymap.c from a configurator export. The generated keymap is written to stdout, or to a file if -o is provided.
"""
# Error checking
- if not cli.args.filename.exists():
- cli.log.error('JSON file does not exist!')
+ if cli.args.filename and cli.args.filename.name == '-':
+ # TODO(skullydazed/anyone): Read file contents from STDIN
+ cli.log.error('Reading from STDIN is not (yet) supported.')
cli.print_usage()
exit(1)
- if cli.args.filename.name == '-':
- # TODO(skullydazed/anyone): Read file contents from STDIN
- cli.log.error('Reading from STDIN is not (yet) supported.')
+ if not cli.args.filename.exists():
+ cli.log.error('JSON file does not exist!')
cli.print_usage()
exit(1)
# Environment processing
- if cli.args.output.name == ('-'):
+ if cli.args.output and cli.args.output.name == '-':
cli.args.output = None
# Parse the configurator json
diff --git a/lib/python/qmk/cli/list/keymaps.py b/lib/python/qmk/cli/list/keymaps.py
index cec9ca0224..b18289eb35 100644
--- a/lib/python/qmk/cli/list/keymaps.py
+++ b/lib/python/qmk/cli/list/keymaps.py
@@ -4,7 +4,7 @@ from milc import cli
import qmk.keymap
from qmk.decorators import automagic_keyboard
-from qmk.errors import NoSuchKeyboardError
+from qmk.path import is_keyboard
@cli.argument("-kb", "--keyboard", help="Specify keyboard name. Example: 1upkeyboards/1up60hse")
@@ -13,13 +13,9 @@ from qmk.errors import NoSuchKeyboardError
def list_keymaps(cli):
"""List the keymaps for a specific keyboard
"""
- try:
- for name in qmk.keymap.list_keymaps(cli.config.list_keymaps.keyboard):
- # We echo instead of cli.log.info to allow easier piping of this output
- cli.echo('%s', name)
- except NoSuchKeyboardError as e:
- cli.echo("{fg_red}%s: %s", cli.config.list_keymaps.keyboard, e.message)
- except (FileNotFoundError, PermissionError) as e:
- cli.echo("{fg_red}%s: %s", cli.config.list_keymaps.keyboard, e)
- except TypeError:
- cli.echo("{fg_red}Something went wrong. Did you specify a keyboard?")
+ if not is_keyboard(cli.config.list_keymaps.keyboard):
+ cli.log.error('Keyboard %s does not exist!', cli.config.list_keymaps.keyboard)
+ exit(1)
+
+ for name in qmk.keymap.list_keymaps(cli.config.list_keymaps.keyboard):
+ print(name)