search.py 7.9 KB

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