search.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. """Functions for searching through QMK keyboards and keymaps.
  2. """
  3. import contextlib
  4. import functools
  5. import fnmatch
  6. import logging
  7. import re
  8. from typing import List, Tuple
  9. from dotty_dict import dotty, Dotty
  10. from milc import cli
  11. from qmk.util import parallel_map
  12. from qmk.info import keymap_json
  13. from qmk.keyboard import list_keyboards, keyboard_folder
  14. from qmk.keymap import list_keymaps, locate_keymap
  15. from qmk.build_targets import KeyboardKeymapBuildTarget, BuildTarget
  16. def _set_log_level(level):
  17. cli.acquire_lock()
  18. old = cli.log_level
  19. cli.log_level = level
  20. cli.log.setLevel(level)
  21. logging.root.setLevel(level)
  22. cli.release_lock()
  23. return old
  24. @contextlib.contextmanager
  25. def ignore_logging():
  26. old = _set_log_level(logging.CRITICAL)
  27. yield
  28. _set_log_level(old)
  29. def _all_keymaps(keyboard):
  30. """Returns a list of tuples of (keyboard, keymap) for all keymaps for the given keyboard.
  31. """
  32. with ignore_logging():
  33. keyboard = keyboard_folder(keyboard)
  34. return [(keyboard, keymap) for keymap in list_keymaps(keyboard)]
  35. def _keymap_exists(keyboard, keymap):
  36. """Returns the keyboard name if the keyboard+keymap combination exists, otherwise None.
  37. """
  38. with ignore_logging():
  39. return keyboard if locate_keymap(keyboard, keymap) is not None else None
  40. def _load_keymap_info(kb_km):
  41. """Returns a tuple of (keyboard, keymap, info.json) for the given keyboard/keymap combination.
  42. """
  43. with ignore_logging():
  44. return (kb_km[0], kb_km[1], keymap_json(kb_km[0], kb_km[1]))
  45. def expand_make_targets(targets: List[str]) -> List[Tuple[str, str]]:
  46. """Expand a list of make targets into a list of (keyboard, keymap) tuples.
  47. Caters for 'all' in either keyboard or keymap, or both.
  48. """
  49. split_targets = []
  50. for target in targets:
  51. split_target = target.split(':')
  52. if len(split_target) != 2:
  53. cli.log.error(f"Invalid build target: {target}")
  54. return []
  55. split_targets.append((split_target[0], split_target[1]))
  56. return expand_keymap_targets(split_targets)
  57. def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] = None) -> List[Tuple[str, str]]:
  58. """Expand a keyboard input and keymap input into a list of (keyboard, keymap) tuples.
  59. Caters for 'all' in either keyboard or keymap, or both.
  60. """
  61. if all_keyboards is None:
  62. all_keyboards = list_keyboards()
  63. if keyboard == 'all':
  64. if keymap == 'all':
  65. cli.log.info('Retrieving list of all keyboards and keymaps...')
  66. targets = []
  67. for kb in parallel_map(_all_keymaps, all_keyboards):
  68. targets.extend(kb)
  69. return targets
  70. else:
  71. cli.log.info(f'Retrieving list of keyboards with keymap "{keymap}"...')
  72. keyboard_filter = functools.partial(_keymap_exists, keymap=keymap)
  73. return [(kb, keymap) for kb in filter(lambda e: e is not None, parallel_map(keyboard_filter, all_keyboards))]
  74. else:
  75. if keymap == 'all':
  76. cli.log.info(f'Retrieving list of keymaps for keyboard "{keyboard}"...')
  77. return _all_keymaps(keyboard)
  78. else:
  79. return [(keyboard, keymap)]
  80. def expand_keymap_targets(targets: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
  81. """Expand a list of (keyboard, keymap) tuples inclusive of 'all', into a list of explicit (keyboard, keymap) tuples.
  82. """
  83. overall_targets = []
  84. all_keyboards = list_keyboards()
  85. for target in targets:
  86. overall_targets.extend(_expand_keymap_target(target[0], target[1], all_keyboards))
  87. return list(sorted(set(overall_targets)))
  88. def _construct_build_target_kb_km(e):
  89. return KeyboardKeymapBuildTarget(keyboard=e[0], keymap=e[1])
  90. def _construct_build_target_kb_km_json(e):
  91. return KeyboardKeymapBuildTarget(keyboard=e[0], keymap=e[1], json=e[2])
  92. def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str] = []) -> List[BuildTarget]:
  93. """Filter a list of (keyboard, keymap) tuples based on the supplied filters.
  94. Optionally includes the values of the queried info.json keys.
  95. """
  96. if len(filters) == 0:
  97. cli.log.info('Preparing target list...')
  98. targets = list(set(parallel_map(_construct_build_target_kb_km, target_list)))
  99. else:
  100. cli.log.info('Parsing data for all matching keyboard/keymap combinations...')
  101. valid_keymaps = [(e[0], e[1], dotty(e[2])) for e in parallel_map(_load_keymap_info, target_list)]
  102. function_re = re.compile(r'^(?P<function>[a-zA-Z]+)\((?P<key>[a-zA-Z0-9_\.]+)(,\s*(?P<value>[^#]+))?\)$')
  103. equals_re = re.compile(r'^(?P<key>[a-zA-Z0-9_\.]+)\s*=\s*(?P<value>[^#]+)$')
  104. for filter_expr in filters:
  105. function_match = function_re.match(filter_expr)
  106. equals_match = equals_re.match(filter_expr)
  107. if function_match is not None:
  108. func_name = function_match.group('function').lower()
  109. key = function_match.group('key')
  110. value = function_match.group('value')
  111. if value is not None:
  112. if func_name == 'length':
  113. valid_keymaps = filter(lambda e, key=key, value=value: key in e[2] and len(e[2].get(key)) == int(value), valid_keymaps)
  114. elif func_name == 'contains':
  115. valid_keymaps = filter(lambda e, key=key, value=value: key in e[2] and value in e[2].get(key), valid_keymaps)
  116. else:
  117. cli.log.warning(f'Unrecognized filter expression: {function_match.group(0)}')
  118. continue
  119. cli.log.info(f'Filtering on condition: {{fg_green}}{func_name}{{fg_reset}}({{fg_cyan}}{key}{{fg_reset}}, {{fg_cyan}}{value}{{fg_reset}})...')
  120. else:
  121. if func_name == 'exists':
  122. valid_keymaps = filter(lambda e, key=key: key in e[2], valid_keymaps)
  123. elif func_name == 'absent':
  124. valid_keymaps = filter(lambda e, key=key: key not in e[2], valid_keymaps)
  125. else:
  126. cli.log.warning(f'Unrecognized filter expression: {function_match.group(0)}')
  127. continue
  128. cli.log.info(f'Filtering on condition: {{fg_green}}{func_name}{{fg_reset}}({{fg_cyan}}{key}{{fg_reset}})...')
  129. elif equals_match is not None:
  130. key = equals_match.group('key')
  131. value = equals_match.group('value')
  132. cli.log.info(f'Filtering on condition: {{fg_cyan}}{key}{{fg_reset}} == {{fg_cyan}}{value}{{fg_reset}}...')
  133. def _make_filter(k, v):
  134. expr = fnmatch.translate(v)
  135. rule = re.compile(f'^{expr}$', re.IGNORECASE)
  136. def f(e):
  137. lhs = e[2].get(k)
  138. lhs = str(False if lhs is None else lhs)
  139. return rule.search(lhs) is not None
  140. return f
  141. valid_keymaps = filter(_make_filter(key, value), valid_keymaps)
  142. else:
  143. cli.log.warning(f'Unrecognized filter expression: {filter_expr}')
  144. continue
  145. cli.log.info('Preparing target list...')
  146. valid_keymaps = [(e[0], e[1], e[2].to_dict() if isinstance(e[2], Dotty) else e[2]) for e in valid_keymaps] # need to convert dotty_dict back to dict because it doesn't survive parallelisation
  147. targets = list(set(parallel_map(_construct_build_target_kb_km_json, list(valid_keymaps))))
  148. return targets
  149. def search_keymap_targets(targets: List[Tuple[str, str]] = [('all', 'default')], filters: List[str] = []) -> List[BuildTarget]:
  150. """Search for build targets matching the supplied criteria.
  151. """
  152. return _filter_keymap_targets(expand_keymap_targets(targets), filters)
  153. def search_make_targets(targets: List[str], filters: List[str] = []) -> List[BuildTarget]:
  154. """Search for build targets matching the supplied criteria.
  155. """
  156. return _filter_keymap_targets(expand_make_targets(targets), filters)