Further simplification.

This commit is contained in:
Nick Brassel 2023-09-29 16:06:38 +10:00
parent c5aaa25b6c
commit 74d37f8e4e
No known key found for this signature in database
4 changed files with 47 additions and 25 deletions

View File

@ -15,7 +15,6 @@ from qmk.search import search_keymap_targets
) )
@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('-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.argument('-km', '--keymap', type=str, default='default', help="The keymap name to build. Default is 'default'.")
@cli.argument('-x', '--disable-parallel-parsing', arg_only=True, action='store_true', help="Disables parallel parsing of files, useful for debugging stalls.")
@cli.subcommand('Find builds which match supplied search criteria.') @cli.subcommand('Find builds which match supplied search criteria.')
def find(cli): 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.
@ -24,7 +23,7 @@ def find(cli):
if len(cli.args.filter) == 0 and len(cli.args.print) > 0: if len(cli.args.filter) == 0 and len(cli.args.print) > 0:
cli.log.warning('No filters supplied -- keymaps not parsed, unable to print requested values.') cli.log.warning('No filters supplied -- keymaps not parsed, unable to print requested values.')
targets = search_keymap_targets([('all', cli.config.find.keymap)], cli.args.filter, cli.args.print, parallel=not cli.config.find.disable_parallel_parsing) targets = search_keymap_targets([('all', cli.config.find.keymap)], cli.args.filter, cli.args.print)
for keyboard, keymap, print_vals in targets: for keyboard, keymap, print_vals in targets:
print(f'{keyboard}:{keymap}') print(f'{keyboard}:{keymap}')

View File

@ -79,7 +79,6 @@ all: {keyboard_safe}_{keymap_name}_binary
@cli.argument('-j', '--parallel', type=int, default=1, help="Set the number of parallel make jobs; 0 means unlimited.") @cli.argument('-j', '--parallel', type=int, default=1, help="Set the number of parallel make jobs; 0 means unlimited.")
@cli.argument('-c', '--clean', arg_only=True, action='store_true', help="Remove object files before compiling.") @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('-n', '--dry-run', arg_only=True, action='store_true', help="Don't actually build, just show the commands to be run.")
@cli.argument('-x', '--disable-parallel-parsing', arg_only=True, action='store_true', help="Disables parallel parsing of files, useful for debugging stalls.")
@cli.argument( @cli.argument(
'-f', '-f',
'--filter', '--filter',
@ -96,8 +95,8 @@ def mass_compile(cli):
"""Compile QMK Firmware against all keyboards. """Compile QMK Firmware against all keyboards.
""" """
if len(cli.args.builds) > 0: if len(cli.args.builds) > 0:
targets = search_make_targets(cli.args.builds, cli.args.filter, parallel=not cli.config.mass_compile.disable_parallel_parsing) targets = search_make_targets(cli.args.builds, cli.args.filter)
else: else:
targets = search_keymap_targets([('all', cli.config.mass_compile.keymap)], cli.args.filter, parallel=not cli.config.mass_compile.disable_parallel_parsing) targets = search_keymap_targets([('all', cli.config.mass_compile.keymap)], cli.args.filter)
return mass_compile_targets(targets, cli.args.clean, cli.args.dry_run, cli.config.mass_compile.no_temp, cli.config.mass_compile.parallel, cli.args.env) return mass_compile_targets(targets, cli.args.clean, cli.args.dry_run, cli.config.mass_compile.no_temp, cli.config.mass_compile.parallel, cli.args.env)

View File

@ -9,7 +9,7 @@ from typing import List, Tuple
from dotty_dict import dotty from dotty_dict import dotty
from milc import cli from milc import cli
from qmk.util import parallelize from qmk.util import parallel_map
from qmk.info import keymap_json from qmk.info import keymap_json
import qmk.keyboard import qmk.keyboard
import qmk.keymap import qmk.keymap
@ -58,7 +58,7 @@ def _load_keymap_info(arg0, arg1=None):
return (arg0, arg1, keymap_json(arg0, arg1)) return (arg0, arg1, keymap_json(arg0, arg1))
def expand_make_targets(targets: List[str], parallel=True) -> List[Tuple[str, str]]: def expand_make_targets(targets: List[str]) -> List[Tuple[str, str]]:
"""Expand a list of make targets into a list of (keyboard, keymap) tuples. """Expand a list of make targets into a list of (keyboard, keymap) tuples.
Caters for 'all' in either keyboard or keymap, or both. Caters for 'all' in either keyboard or keymap, or both.
@ -70,10 +70,10 @@ def expand_make_targets(targets: List[str], parallel=True) -> List[Tuple[str, st
cli.log.error(f"Invalid build target: {target}") cli.log.error(f"Invalid build target: {target}")
return [] return []
split_targets.append((split_target[0], split_target[1])) split_targets.append((split_target[0], split_target[1]))
return expand_keymap_targets(split_targets, parallel) return expand_keymap_targets(split_targets)
def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] = None, parallel=True) -> List[Tuple[str, str]]: def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] = None) -> List[Tuple[str, str]]:
"""Expand a keyboard input and keymap input into a list of (keyboard, keymap) tuples. """Expand a keyboard input and keymap input into a list of (keyboard, keymap) tuples.
Caters for 'all' in either keyboard or keymap, or both. Caters for 'all' in either keyboard or keymap, or both.
@ -85,15 +85,13 @@ def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] =
if keymap == 'all': if keymap == 'all':
cli.log.info('Retrieving list of all keyboards and keymaps...') cli.log.info('Retrieving list of all keyboards and keymaps...')
targets = [] targets = []
with parallelize(parallel) as map_func: for kb in parallel_map(_all_keymaps, all_keyboards):
for kb in map_func(_all_keymaps, all_keyboards):
targets.extend(kb) targets.extend(kb)
return targets return targets
else: else:
cli.log.info(f'Retrieving list of keyboards with keymap "{keymap}"...') cli.log.info(f'Retrieving list of keyboards with keymap "{keymap}"...')
keyboard_filter = functools.partial(_keymap_exists, keymap=keymap) keyboard_filter = functools.partial(_keymap_exists, keymap=keymap)
with parallelize(parallel) as map_func: return [(kb, keymap) for kb in filter(lambda e: e is not None, parallel_map(keyboard_filter, all_keyboards))]
return [(kb, keymap) for kb in filter(lambda e: e is not None, map_func(keyboard_filter, all_keyboards))]
else: else:
if keymap == 'all': if keymap == 'all':
keyboard = qmk.keyboard.resolve_keyboard(keyboard) keyboard = qmk.keyboard.resolve_keyboard(keyboard)
@ -103,17 +101,17 @@ def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] =
return [(qmk.keyboard.resolve_keyboard(keyboard), keymap)] return [(qmk.keyboard.resolve_keyboard(keyboard), keymap)]
def expand_keymap_targets(targets: List[Tuple[str, str]], parallel=True) -> List[Tuple[str, str]]: def expand_keymap_targets(targets: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
"""Expand a list of (keyboard, keymap) tuples inclusive of 'all', into a list of explicit (keyboard, keymap) tuples. """Expand a list of (keyboard, keymap) tuples inclusive of 'all', into a list of explicit (keyboard, keymap) tuples.
""" """
overall_targets = [] overall_targets = []
all_keyboards = qmk.keyboard.list_keyboards() all_keyboards = qmk.keyboard.list_keyboards()
for target in targets: for target in targets:
overall_targets.extend(_expand_keymap_target(target[0], target[1], all_keyboards, parallel)) overall_targets.extend(_expand_keymap_target(target[0], target[1], all_keyboards))
return list(sorted(set(overall_targets))) return list(sorted(set(overall_targets)))
def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str] = [], print_vals: List[str] = [], parallel=True) -> List[Tuple[str, str, List[Tuple[str, str]]]]: def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str] = [], print_vals: List[str] = []) -> List[Tuple[str, str, List[Tuple[str, str]]]]:
"""Filter a list of (keyboard, keymap) tuples based on the supplied filters. """Filter a list of (keyboard, keymap) tuples based on the supplied filters.
Optionally includes the values of the queried info.json keys. Optionally includes the values of the queried info.json keys.
@ -122,8 +120,7 @@ def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str
targets = [(kb, km, {}) for kb, km in target_list] targets = [(kb, km, {}) for kb, km in target_list]
else: else:
cli.log.info('Parsing data for all matching keyboard/keymap combinations...') cli.log.info('Parsing data for all matching keyboard/keymap combinations...')
with parallelize(parallel) as map_func: valid_keymaps = [(e[0], e[1], dotty(e[2])) for e in parallel_map(_load_keymap_info, target_list)]
valid_keymaps = [(e[0], e[1], dotty(e[2])) for e in map_func(_load_keymap_info, target_list)]
function_re = re.compile(r'^(?P<function>[a-zA-Z]+)\((?P<key>[a-zA-Z0-9_\.]+)(,\s*(?P<value>[^#]+))?\)$') function_re = re.compile(r'^(?P<function>[a-zA-Z]+)\((?P<key>[a-zA-Z0-9_\.]+)(,\s*(?P<value>[^#]+))?\)$')
equals_re = re.compile(r'^(?P<key>[a-zA-Z0-9_\.]+)\s*=\s*(?P<value>[^#]+)$') equals_re = re.compile(r'^(?P<key>[a-zA-Z0-9_\.]+)\s*=\s*(?P<value>[^#]+)$')
@ -184,13 +181,13 @@ def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str
return targets return targets
def search_keymap_targets(targets: List[Tuple[str, str]] = [('all', 'default')], filters: List[str] = [], print_vals: List[str] = [], parallel=True) -> List[Tuple[str, str, List[Tuple[str, str]]]]: def search_keymap_targets(targets: List[Tuple[str, str]] = [('all', 'default')], filters: List[str] = [], print_vals: List[str] = []) -> List[Tuple[str, str, List[Tuple[str, str]]]]:
"""Search for build targets matching the supplied criteria. """Search for build targets matching the supplied criteria.
""" """
return list(sorted(_filter_keymap_targets(expand_keymap_targets(targets, parallel), filters, print_vals, parallel), key=lambda e: (e[0], e[1]))) return list(sorted(_filter_keymap_targets(expand_keymap_targets(targets), filters, print_vals), key=lambda e: (e[0], e[1])))
def search_make_targets(targets: List[str], filters: List[str] = [], print_vals: List[str] = [], parallel=True) -> List[Tuple[str, str, List[Tuple[str, str]]]]: def search_make_targets(targets: List[str], filters: List[str] = [], print_vals: List[str] = []) -> List[Tuple[str, str, List[Tuple[str, str]]]]:
"""Search for build targets matching the supplied criteria. """Search for build targets matching the supplied criteria.
""" """
return list(sorted(_filter_keymap_targets(expand_make_targets(targets, parallel), filters, print_vals, parallel), key=lambda e: (e[0], e[1]))) return list(sorted(_filter_keymap_targets(expand_make_targets(targets), filters, print_vals), key=lambda e: (e[0], e[1])))

View File

@ -4,24 +4,51 @@ import contextlib
import functools import functools
import multiprocessing import multiprocessing
from milc import cli
from milc.subcommand import config
@contextlib.contextmanager @contextlib.contextmanager
def parallelize(do_parallel): def parallelize():
"""Returns a function that can be used in place of a map() call. """Returns a function that can be used in place of a map() call.
Attempts to use `mpire`, falling back to `multiprocessing` if it's not Attempts to use `mpire`, falling back to `multiprocessing` if it's not
available. If parallelization is not requested, returns the original map() available. If parallelization is not requested, returns the original map()
function. function.
""" """
if not do_parallel:
# Work out if we've already got a config value for parallel searching
if not cli.config.user.parallel_search:
parallel_search = True
else:
parallel_search = cli.config.user.parallel_search
# If we haven't already written a value, write it to the file
if cli.config.user.parallel_search != parallel_search:
cli.args.read_only = False
cli.config.user.parallel_search = parallel_search
config.set_config('user', 'parallel_search', parallel_search)
cli.save_config()
# Non-parallel searches use use `map()`
if not parallel_search:
yield map yield map
return return
# Prefer mpire's `WorkerPool` if it's available
with contextlib.suppress(ImportError): with contextlib.suppress(ImportError):
from mpire import WorkerPool from mpire import WorkerPool
with WorkerPool() as pool: with WorkerPool() as pool:
yield functools.partial(pool.imap_unordered, progress_bar=True) yield functools.partial(pool.imap_unordered, progress_bar=True)
return return
# Otherwise fall back to multiprocessing's `Pool`
with multiprocessing.Pool() as pool: with multiprocessing.Pool() as pool:
yield pool.imap_unordered yield pool.imap_unordered
def parallel_map(*args, **kwargs):
"""Effectively runs `map()` but executes it in parallel if necessary.
"""
with parallelize() as map_fn:
return map_fn(*args, **kwargs)