Skip to content

Commit

Permalink
Further simplification.
Browse files Browse the repository at this point in the history
  • Loading branch information
tzarc committed Sep 29, 2023
1 parent c5aaa25 commit 74d37f8
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 25 deletions.
3 changes: 1 addition & 2 deletions lib/python/qmk/cli/find.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
)
@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('-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.')
def find(cli):
"""Search through all keyboards and keymaps for a given search criteria.
Expand All @@ -24,7 +23,7 @@ def find(cli):
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.')

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:
print(f'{keyboard}:{keymap}')

Expand Down
5 changes: 2 additions & 3 deletions lib/python/qmk/cli/mass_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ def mass_compile_targets(targets, clean, dry_run, no_temp, parallel, env):
@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('-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(
'-f',
'--filter',
Expand All @@ -96,8 +95,8 @@ def mass_compile(cli):
"""Compile QMK Firmware against all keyboards.
"""
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:
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)
33 changes: 15 additions & 18 deletions lib/python/qmk/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from dotty_dict import dotty
from milc import cli

from qmk.util import parallelize
from qmk.util import parallel_map
from qmk.info import keymap_json
import qmk.keyboard
import qmk.keymap
Expand Down Expand Up @@ -58,7 +58,7 @@ def _load_keymap_info(arg0, arg1=None):
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.
Caters for 'all' in either keyboard or keymap, or both.
Expand All @@ -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}")
return []
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.
Caters for 'all' in either keyboard or keymap, or both.
Expand All @@ -85,15 +85,13 @@ def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] =
if keymap == 'all':
cli.log.info('Retrieving list of all keyboards and keymaps...')
targets = []
with parallelize(parallel) as map_func:
for kb in map_func(_all_keymaps, all_keyboards):
targets.extend(kb)
for kb in parallel_map(_all_keymaps, all_keyboards):
targets.extend(kb)
return targets
else:
cli.log.info(f'Retrieving list of keyboards with 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, map_func(keyboard_filter, all_keyboards))]
return [(kb, keymap) for kb in filter(lambda e: e is not None, parallel_map(keyboard_filter, all_keyboards))]
else:
if keymap == 'all':
keyboard = qmk.keyboard.resolve_keyboard(keyboard)
Expand All @@ -103,17 +101,17 @@ def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] =
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.
"""
overall_targets = []
all_keyboards = qmk.keyboard.list_keyboards()
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)))


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.
Optionally includes the values of the queried info.json keys.
Expand All @@ -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]
else:
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 map_func(_load_keymap_info, target_list)]
valid_keymaps = [(e[0], e[1], dotty(e[2])) for e in parallel_map(_load_keymap_info, target_list)]

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>[^#]+)$')
Expand Down Expand Up @@ -184,13 +181,13 @@ def f(e):
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.
"""
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.
"""
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])))
31 changes: 29 additions & 2 deletions lib/python/qmk/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,51 @@
import functools
import multiprocessing

from milc import cli
from milc.subcommand import config


@contextlib.contextmanager
def parallelize(do_parallel):
def parallelize():
"""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
available. If parallelization is not requested, returns the original map()
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
return

# Prefer mpire's `WorkerPool` if it's available
with contextlib.suppress(ImportError):
from mpire import WorkerPool
with WorkerPool() as pool:
yield functools.partial(pool.imap_unordered, progress_bar=True)
return

# Otherwise fall back to multiprocessing's `Pool`
with multiprocessing.Pool() as pool:
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)

0 comments on commit 74d37f8

Please sign in to comment.