Browse Source

First pass of ruff check fixes (#26257)

Joel Challis 2 weeks ago
parent
commit
cf01e22447

+ 1 - 1
docs/cli_commands.md

@@ -214,7 +214,7 @@ options:
   -p PRINT, --print PRINT
                         For each matched target, print the value of the supplied info.json key. May be passed multiple times.
   -f FILTER, --filter FILTER
-                        Filter the list of keyboards based on their info.json data. Accepts the formats key=value, function(key), or function(key,value), eg. 'features.rgblight=true'. Valid functions are 'absent', 'contains', 'exists' and 'length'. May be passed multiple times; all filters need to match. Value may include wildcards such as '*' and '?'.
+                        Filter the list of keyboards based on their info.json data. Accepts the formats key=value, function(key), or function(key,value), eg. 'features.rgblight==true'. Valid functions are 'absent', 'contains', 'exists' and 'length'. May be passed multiple times; all filters need to match. Value may include wildcards such as '*' and '?'.
 ```
 
 ## `qmk console`

+ 2 - 2
lib/python/kle2xy.py

@@ -46,7 +46,7 @@ class KLE2xy(list):
         if 'name' in properties:
             self.name = properties['name']
 
-    def parse_layout(self, layout):  # noqa  FIXME(skullydazed): flake8 says this has a complexity of 25, it should be refactored.
+    def parse_layout(self, layout):  # noqa: C901 flake8 says this has a complexity of 25, it should be refactored.
         # Wrap this in a dictionary so hjson will parse KLE raw data
         layout = '{"layout": [' + layout + ']}'
         layout = hjson.loads(layout)['layout']
@@ -60,7 +60,7 @@ class KLE2xy(list):
             self.attrs(layout[0])
             layout = layout[1:]
 
-        for row_num, row in enumerate(layout):
+        for _row_num, row in enumerate(layout):
             self.append([])
 
             # Process the current row

+ 3 - 3
lib/python/qmk/cli/bux.py

@@ -2,14 +2,14 @@
 
 World domination secret weapon.
 """
+
 from milc import cli
 from milc.subcommand import config
 
 
 @cli.subcommand('QMK Bux miner.', hidden=True)
 def bux(cli):
-    """QMK bux
-    """
+    """QMK bux"""
     if not cli.config.user.bux:
         bux = 0
     else:
@@ -45,5 +45,5 @@ def bux(cli):
 @B   r@=               :@@-   _@@_R@fB#}@@ 2@@@#    8@@#@Q.*@B  `@@-  y@@N                    @H  B@
 @B   `.                 g@9=_~D@g R@}`&@@@ 2@&__`   8@u_Q@2!@@^-x@@` Y@QD@z                   .`  B@
 @@BBBBBBBBBBBBBBBBBBB_  `c8@@@81` S#] `N#B l####v   D###BA. vg@@#0~ i#&' 5#K   RBBBBBBBBBBBBBBBBBB@@
-""" # noqa: Do not care about the ASCII art
+"""
     print(f"{buck}\nYou've been blessed by the QMK gods!\nYou have {cli.config.user.bux} QMK bux.")

+ 4 - 13
lib/python/qmk/cli/find.py

@@ -1,26 +1,17 @@
-"""Command to search through all keyboards and keymaps for a given search criteria.
-"""
+"""Command to search through all keyboards and keymaps for a given search criteria."""
+
 import os
 from milc import cli
 from qmk.search import filter_help, search_keymap_targets
 from qmk.util import maybe_exit_config
 
 
-@cli.argument(
-    '-f',
-    '--filter',
-    arg_only=True,
-    action='append',
-    default=[],
-    help=  # noqa: `format-python` and `pytest` don't agree here.
-    f"Filter the list of keyboards based on their info.json data. Accepts the formats key=value, function(key), or function(key,value), eg. 'features.rgblight=true'. Valid functions are {filter_help()}. May be passed multiple times; all filters need to match. Value may include wildcards such as '*' and '?'."  # noqa: `format-python` and `pytest` don't agree here.
-)
+@cli.argument('-f', '--filter', arg_only=True, action='append', default=[], help=f"Filter the list of keyboards based on their info.json data. Accepts the formats key==value, function(key), or function(key,value), eg. 'features.rgblight==true'. Valid functions are {filter_help()}. May be passed multiple times; all filters need to match. Value may include wildcards such as '*' and '?'.")  # fmt: off
 @cli.argument('-p', '--print', arg_only=True, action='append', default=[], help="For each matched target, print the value of the supplied info.json key. May be passed multiple times.")
 @cli.argument('-km', '--keymap', type=str, default='default', help="The keymap name to build. Default is 'default'.")
 @cli.subcommand('Find builds which match supplied search criteria.')
 def find(cli):
-    """Search through all keyboards and keymaps for a given search criteria.
-    """
+    """Search through all keyboards and keymaps for a given search criteria."""
     os.environ.setdefault('SKIP_SCHEMA_VALIDATION', '1')
     maybe_exit_config(should_exit=False, should_reraise=True)
 

+ 6 - 3
lib/python/qmk/cli/generate/keyboard_c.py

@@ -256,10 +256,13 @@ class Layout:
 def _gen_chordal_hold_layout(info_data):
     """Convert info.json content to chordal_hold_layout
     """
+    layouts = info_data.get('layouts', {})
+    if not layouts:
+        return []
+
     # NOTE: If there are multiple layouts, only the first is read.
-    for layout_name, layout_json in info_data['layouts'].items():
-        layout = Layout(layout_json)
-        break
+    layout_name, layout_json = next(iter(layouts.items()))
+    layout = Layout(layout_json)
 
     if layout.is_symmetric():
         # If the layout is symmetric (e.g. most split keyboards), guess the

+ 2 - 2
lib/python/qmk/cli/generate/keycodes.py

@@ -58,7 +58,7 @@ def _generate_defines(lines, keycodes):
 
     lines.append('')
     lines.append('// Alias')
-    for key, value in keycodes["keycodes"].items():
+    for value in keycodes["keycodes"].values():
         temp = value.get("key")
         for alias in value.get("aliases", []):
             lines.append(f'    {alias.ljust(10)} = {temp},')
@@ -120,7 +120,7 @@ def _generate_aliases(lines, keycodes):
             lines.append(f'#define {define} {val}')
 
     lines.append('')
-    for key, value in keycodes["aliases"].items():
+    for value in keycodes["aliases"].values():
         for alias in value.get("aliases", []):
             lines.append(f'#define {alias} {value.get("key")}')
 

+ 1 - 1
lib/python/qmk/cli/lint.py

@@ -271,7 +271,7 @@ def keymap_check(kb, km):
     return ok
 
 
-def keyboard_check(kb):  # noqa C901
+def keyboard_check(kb):  # noqa: C901
     """Perform the keyboard level checks.
     """
     ok = True

+ 17 - 33
lib/python/qmk/cli/mass_compile.py

@@ -2,6 +2,7 @@
 
 This will compile everything in parallel, for testing purposes.
 """
+
 import os
 from typing import List
 from pathlib import Path
@@ -37,19 +38,16 @@ def mass_compile_targets(targets: List[BuildTarget], clean: bool, dry_run: bool,
 
         builddir.mkdir(parents=True, exist_ok=True)
         with open(makefile, "w") as f:
-            # yapf: disable
-            f.write(
-                f"""\
+            # fmt: off
+            f.write("""\
 # This file is auto-generated by qmk mass-compile
 # Do not edit this file directly.
 all: print_failures
 .PHONY: all_targets print_failures
 print_failures: all_targets
-"""# noqa
-            )
+""")
             if print_failures:
-                f.write(
-                    f"""\
+                f.write(f"""\
 	@for f in $$(ls .build/failed.log.{os.getpid()}.* 2>/dev/null | sort); do \\
 		echo; \\
 		echo "======================================================================================"; \\
@@ -58,9 +56,8 @@ print_failures: all_targets
 		cat $$f; \\
 		echo "------------------------------------------------------"; \\
 	done
-"""# noqa
-                )
-            # yapf: enable
+""")  # noqa: W191, E101
+            # fmt: on
             for target in sorted(targets, key=lambda t: (t.keyboard, t.keymap)):
                 keyboard_name = target.keyboard
                 keymap_name = target.keymap
@@ -78,9 +75,8 @@ print_failures: all_targets
                     build_log += f".{extra_args}"
                     failed_log += f".{extra_args}"
                     target_suffix = f"_{extra_args}"
-                # yapf: disable
-                f.write(
-                    f"""\
+                # fmt: off
+                f.write(f"""\
 .PHONY: {target_filename}{target_suffix}_binary
 all_targets: {target_filename}{target_suffix}_binary
 {target_filename}{target_suffix}_binary:
@@ -93,20 +89,17 @@ all_targets: {target_filename}{target_suffix}_binary
 		|| {{ grep '\\[WARNINGS\\]' "{build_log}" >/dev/null 2>&1 && printf "Build %-64s \\e[1;33m[WARNINGS]\\e[0m\\n" "{keyboard_name}:{keymap_name}" ; }} \\
 		|| printf "Build %-64s \\e[1;32m[OK]\\e[0m\\n" "{keyboard_name}:{keymap_name}"
 	@rm -f "{build_log}" || true
-"""# noqa
-                )
-                # yapf: enable
+""")  # noqa: W191, E101
+                # fmt: on
 
                 if no_temp:
-                    # yapf: disable
-                    f.write(
-                        f"""\
+                    # fmt: off
+                    f.write(f"""\
 	@rm -rf "{builddir}/{target_filename}.elf" 2>/dev/null || true
 	@rm -rf "{builddir}/{target_filename}.map" 2>/dev/null || true
 	@rm -rf "{builddir}/obj_{target_filename}" || true
-"""# noqa
-                    )
-                    # yapf: enable
+""")  # noqa: W191, E101
+                    # fmt: on
                 f.write('\n')
 
         cli.run([find_make(), *get_make_parallel_args(parallel), '-f', makefile.as_posix(), 'all'], capture_output=False, stdin=DEVNULL)
@@ -123,21 +116,12 @@ all_targets: {target_filename}{target_suffix}_binary
 @cli.argument('-c', '--clean', arg_only=True, action='store_true', help="Remove object files before compiling.")
 @cli.argument('-n', '--dry-run', arg_only=True, action='store_true', help="Don't actually build, just show the commands to be run.")
 @cli.argument('-p', '--print-failures', arg_only=True, action='store_true', help="Print failed builds.")
-@cli.argument(
-    '-f',
-    '--filter',
-    arg_only=True,
-    action='append',
-    default=[],
-    help=  # noqa: `format-python` and `pytest` don't agree here.
-    "Filter the list of keyboards based on the supplied value in rules.mk. Matches info.json structure, and accepts the formats 'features.rgblight=true' or 'exists(matrix_pins.direct)'. May be passed multiple times, all filters need to match. Value may include wildcards such as '*' and '?'."  # noqa: `format-python` and `pytest` don't agree here.
-)
+@cli.argument('-f', '--filter', arg_only=True, action='append', default=[], help="Filter the list of keyboards based on the supplied value in rules.mk. Matches info.json structure, and accepts the formats 'features.rgblight==true' or 'exists(matrix_pins.direct)'. May be passed multiple times, all filters need to match. Value may include wildcards such as '*' and '?'.")  # fmt: off
 @cli.argument('-km', '--keymap', type=str, default='default', help="The keymap name to build. Default is 'default'.")
 @cli.argument('-e', '--env', arg_only=True, action='append', default=[], help="Set a variable to be passed to make. May be passed multiple times.")
 @cli.subcommand('Compile QMK Firmware for all keyboards.', hidden=False if cli.config.user.developer else True)
 def mass_compile(cli):
-    """Compile QMK Firmware against all keyboards.
-    """
+    """Compile QMK Firmware against all keyboards."""
     maybe_exit_config(should_exit=False, should_reraise=True)
 
     if len(cli.args.builds) > 0:

+ 1 - 3
lib/python/qmk/flashers.py

@@ -9,7 +9,6 @@ import usb.core
 from qmk.constants import BOOTLOADER_VIDS_PIDS
 from milc import cli
 
-# yapf: disable
 _PID_TO_MCU = {
     '2fef': 'atmega16u2',
     '2ff0': 'atmega32u2',
@@ -17,7 +16,7 @@ _PID_TO_MCU = {
     '2ff4': 'atmega32u4',
     '2ff9': 'at90usb64',
     '2ffa': 'at90usb162',
-    '2ffb': 'at90usb128'
+    '2ffb': 'at90usb128',
 }
 
 AVRDUDE_MCU = {
@@ -25,7 +24,6 @@ AVRDUDE_MCU = {
     'atmega328p': 'm328p',
     'atmega328': 'm328',
 }
-# yapf: enable
 
 
 class DelayedKeyboardInterrupt:

+ 1 - 1
lib/python/qmk/info.py

@@ -121,7 +121,7 @@ def _validate_build_target(keyboard, info_data):
         _log_warning(info_data, 'Build marker "keyboard.json" not found.')
 
 
-def _validate_layouts(keyboard, info_data):  # noqa C901
+def _validate_layouts(keyboard, info_data):  # noqa: C901
     """Non schema checks
     """
     col_num = info_data.get('matrix_size', {}).get('cols', 0)

+ 5 - 1
lib/python/qmk/json_encoders.py

@@ -3,6 +3,7 @@
 import json
 from decimal import Decimal
 
+_sentinel = object()
 newline = '\n'
 
 
@@ -66,9 +67,12 @@ class QMKJSONEncoder(json.JSONEncoder):
 
             return "[\n" + ",\n".join(output) + "\n" + self.indent_str + "]"
 
-    def encode(self, obj, path=[]):
+    def encode(self, obj, path=_sentinel):
         """Encode JSON objects for QMK.
         """
+        if path is _sentinel:
+            path = []
+
         if isinstance(obj, Decimal):
             return self.encode_decimal(obj)
 

+ 2 - 2
lib/python/qmk/keyboard.py

@@ -224,8 +224,8 @@ def rules_mk(keyboard):
     keyboard = Path(keyboard)
     rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
 
-    for i, dir in enumerate(keyboard.parts):
-        cur_dir = cur_dir / dir
+    for folder in keyboard.parts:
+        cur_dir = cur_dir / folder
         rules = parse_rules_mk_file(cur_dir / 'rules.mk', rules)
 
     return rules

+ 1 - 1
lib/python/qmk/keymap.py

@@ -476,7 +476,7 @@ def _c_preprocess(path, stdin=DEVNULL):
     return pre_processed_keymap.stdout
 
 
-def _get_layers(keymap):  # noqa C901 : until someone has a good idea how to simplify/split up this code
+def _get_layers(keymap):  # noqa: C901 until someone has a good idea how to simplify/split up this code
     """ Find the layers in a keymap.c file.
 
     Args:

+ 2 - 2
lib/python/qmk/painter.py

@@ -123,7 +123,7 @@ def _render_image_metadata(metadata):
                 continue
 
             # Unpack rect's coords
-            l, t, r, b = v["delta_rect"]
+            l, t, r, b = v["delta_rect"]  # noqa: E741
 
             delta_px = (r - l) * (b - t)
             px = size["width"] * size["height"]
@@ -143,7 +143,7 @@ def command_args_str(cli, command_name):
 
     args = {}
     max_length = 0
-    for arg_name, was_passed in cli.args_passed[command_name].items():
+    for arg_name in cli.args_passed[command_name].keys():
         max_length = max(max_length, len(arg_name))
 
         val = getattr(cli.args, arg_name.replace("-", "_"))

+ 4 - 4
lib/python/qmk/search.py

@@ -7,7 +7,7 @@ import fnmatch
 import json
 import logging
 import re
-from typing import Callable, Dict, List, Optional, Tuple, Union
+from typing import Callable, Dict, List, Optional, Tuple, Union, Sequence
 from dotty_dict import dotty, Dotty
 from milc import cli
 
@@ -226,7 +226,7 @@ def _construct_build_target(e: KeyboardKeymapDesc):
     return e.to_build_target()
 
 
-def _filter_keymap_targets(target_list: List[KeyboardKeymapDesc], filters: List[str] = []) -> List[KeyboardKeymapDesc]:
+def _filter_keymap_targets(target_list: List[KeyboardKeymapDesc], filters: Sequence[str] = []) -> List[KeyboardKeymapDesc]:
     """Filter a list of KeyboardKeymapDesc based on the supplied filters.
 
     Optionally includes the values of the queried info.json keys.
@@ -306,7 +306,7 @@ def _filter_keymap_targets(target_list: List[KeyboardKeymapDesc], filters: List[
     return targets
 
 
-def search_keymap_targets(targets: List[Union[Tuple[str, str], Tuple[str, str, Dict[str, str]]]] = [('all', 'default')], filters: List[str] = []) -> List[BuildTarget]:
+def search_keymap_targets(targets: List[Union[Tuple[str, str], Tuple[str, str, Dict[str, str]]]], filters: Sequence[str] = []) -> List[BuildTarget]:
     """Search for build targets matching the supplied criteria.
     """
     def _make_desc(e):
@@ -321,7 +321,7 @@ def search_keymap_targets(targets: List[Union[Tuple[str, str], Tuple[str, str, D
     return sorted(targets)
 
 
-def search_make_targets(targets: List[Union[str, Tuple[str, Dict[str, str]]]], filters: List[str] = []) -> List[BuildTarget]:
+def search_make_targets(targets: List[Union[str, Tuple[str, Dict[str, str]]]], filters: Sequence[str] = []) -> List[BuildTarget]:
     """Search for build targets matching the supplied criteria.
     """
     targets = _filter_keymap_targets(expand_make_targets(targets), filters)

+ 3 - 1
lib/python/qmk/tests/test_cli_commands.py

@@ -1,3 +1,5 @@
+from typing import Sequence
+
 import platform
 from subprocess import DEVNULL
 
@@ -21,7 +23,7 @@ def check_subcommand_stdin(file_to_read, command, *args):
     return result
 
 
-def check_returncode(result, expected=[0]):
+def check_returncode(result, expected: Sequence[int] = [0]):
     """Print stdout if `result.returncode` does not match `expected`.
     """
     if result.returncode not in expected:

+ 1 - 1
lib/python/qmk/userspace.py

@@ -75,7 +75,7 @@ class UserspaceDefs:
             validate(json, 'qmk.user_repo.v0')  # `qmk.json` must have a userspace_version at minimum
         except jsonschema.ValidationError as err:
             exception.add('qmk.user_repo.v0', err)
-            raise exception
+            raise exception from None
 
         # Iterate through each version of the schema, starting with the latest and decreasing to v1
         schema_versions = [

+ 0 - 1
util/ci/discord-results.py

@@ -3,7 +3,6 @@
 import argparse
 import os
 import re
-import sys
 from pathlib import Path
 from discord_webhook import DiscordWebhook, DiscordEmbed