lint.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. """Command to look over a keyboard/keymap and check for common mistakes.
  2. """
  3. from pathlib import Path
  4. from milc import cli
  5. from qmk.decorators import automagic_keyboard, automagic_keymap
  6. from qmk.info import info_json
  7. from qmk.keyboard import keyboard_completer, keyboard_folder_or_all, is_all_keyboards, list_keyboards
  8. from qmk.keymap import locate_keymap, list_keymaps
  9. from qmk.path import keyboard
  10. from qmk.git import git_get_ignored_files
  11. from qmk.c_parse import c_source_files
  12. CHIBIOS_CONF_CHECKS = ['chconf.h', 'halconf.h', 'mcuconf.h', 'board.h']
  13. INVALID_KB_FEATURES = set(['encoder_map', 'dip_switch_map', 'combo', 'tap_dance', 'via'])
  14. INVALID_KM_NAMES = ['via', 'vial']
  15. def _list_defaultish_keymaps(kb):
  16. """Return default like keymaps for a given keyboard
  17. """
  18. defaultish = ['ansi', 'iso']
  19. # This is only here to flag it as "testable", so it doesn't fly under the radar during PR
  20. defaultish.extend(INVALID_KM_NAMES)
  21. keymaps = set()
  22. for x in list_keymaps(kb):
  23. if x in defaultish or x.startswith('default'):
  24. keymaps.add(x)
  25. return keymaps
  26. def _get_code_files(kb, km=None):
  27. """Return potential keyboard/keymap code files
  28. """
  29. search_path = locate_keymap(kb, km).parent if km else keyboard(kb)
  30. code_files = []
  31. for file in c_source_files([search_path]):
  32. # Ignore keymaps when only globing keyboard files
  33. if not km and 'keymaps' in file.parts:
  34. continue
  35. code_files.append(file)
  36. return code_files
  37. def _has_license(file):
  38. """Check file has a license header
  39. """
  40. # Crude assumption that first line of license header is a comment
  41. fline = open(file).readline().rstrip()
  42. return fline.startswith(("/*", "//"))
  43. def _handle_json_errors(kb, info):
  44. """Convert any json errors into lint errors
  45. """
  46. ok = True
  47. # Check for errors in the json
  48. if info['parse_errors']:
  49. ok = False
  50. cli.log.error(f'{kb}: Errors found when generating info.json.')
  51. if cli.config.lint.strict and info['parse_warnings']:
  52. ok = False
  53. cli.log.error(f'{kb}: Warnings found when generating info.json (Strict mode enabled.)')
  54. return ok
  55. def _handle_invalid_features(kb, info):
  56. """Check for features that should never be enabled at the keyboard level
  57. """
  58. ok = True
  59. features = set(info.get('features', []))
  60. for found in features & INVALID_KB_FEATURES:
  61. ok = False
  62. cli.log.error(f'{kb}: Invalid keyboard level feature detected - {found}')
  63. return ok
  64. def _chibios_conf_includenext_check(target):
  65. """Check the ChibiOS conf.h for the correct inclusion of the next conf.h
  66. """
  67. for i, line in enumerate(target.open()):
  68. if f'#include_next "{target.name}"' in line:
  69. return f'Found `#include_next "{target.name}"` on line {i} of {target}, should be `#include_next <{target.name}>` (use angle brackets, not quotes)'
  70. return None
  71. def _rules_mk_assignment_only(kb):
  72. """Check the keyboard-level rules.mk to ensure it only has assignments.
  73. """
  74. keyboard_path = keyboard(kb)
  75. current_path = Path()
  76. errors = []
  77. for path_part in keyboard_path.parts:
  78. current_path = current_path / path_part
  79. rules_mk = current_path / 'rules.mk'
  80. if rules_mk.exists():
  81. continuation = None
  82. for i, line in enumerate(rules_mk.open()):
  83. line = line.strip()
  84. if '#' in line:
  85. line = line[:line.index('#')]
  86. if continuation:
  87. line = continuation + line
  88. continuation = None
  89. if line:
  90. if line[-1] == '\\':
  91. continuation = line[:-1]
  92. continue
  93. if line and '=' not in line:
  94. errors.append(f'Non-assignment code on line +{i} {rules_mk}: {line}')
  95. return errors
  96. def keymap_check(kb, km):
  97. """Perform the keymap level checks.
  98. """
  99. ok = True
  100. keymap_path = locate_keymap(kb, km)
  101. if not keymap_path:
  102. ok = False
  103. cli.log.error("%s: Can't find %s keymap.", kb, km)
  104. return ok
  105. if km in INVALID_KM_NAMES:
  106. ok = False
  107. cli.log.error("%s: The keymap %s should not exist!", kb, km)
  108. return ok
  109. # Additional checks
  110. invalid_files = git_get_ignored_files(keymap_path.parent.as_posix())
  111. for file in invalid_files:
  112. cli.log.error(f'{kb}/{km}: The file "{file}" should not exist!')
  113. ok = False
  114. for file in _get_code_files(kb, km):
  115. if not _has_license(file):
  116. cli.log.error(f'{kb}/{km}: The file "{file}" does not have a license header!')
  117. ok = False
  118. if file.name in CHIBIOS_CONF_CHECKS:
  119. check_error = _chibios_conf_includenext_check(file)
  120. if check_error is not None:
  121. cli.log.error(f'{kb}/{km}: {check_error}')
  122. ok = False
  123. return ok
  124. def keyboard_check(kb):
  125. """Perform the keyboard level checks.
  126. """
  127. ok = True
  128. kb_info = info_json(kb)
  129. if not _handle_json_errors(kb, kb_info):
  130. ok = False
  131. # Additional checks
  132. if not _handle_invalid_features(kb, kb_info):
  133. ok = False
  134. rules_mk_assignment_errors = _rules_mk_assignment_only(kb)
  135. if rules_mk_assignment_errors:
  136. ok = False
  137. cli.log.error('%s: Non-assignment code found in rules.mk. Move it to post_rules.mk instead.', kb)
  138. for assignment_error in rules_mk_assignment_errors:
  139. cli.log.error(assignment_error)
  140. invalid_files = git_get_ignored_files(f'keyboards/{kb}/')
  141. for file in invalid_files:
  142. if 'keymap' in file:
  143. continue
  144. cli.log.error(f'{kb}: The file "{file}" should not exist!')
  145. ok = False
  146. for file in _get_code_files(kb):
  147. if not _has_license(file):
  148. cli.log.error(f'{kb}: The file "{file}" does not have a license header!')
  149. ok = False
  150. if file.name in CHIBIOS_CONF_CHECKS:
  151. check_error = _chibios_conf_includenext_check(file)
  152. if check_error is not None:
  153. cli.log.error(f'{kb}: {check_error}')
  154. ok = False
  155. return ok
  156. @cli.argument('--strict', action='store_true', help='Treat warnings as errors')
  157. @cli.argument('-kb', '--keyboard', action='append', type=keyboard_folder_or_all, completer=keyboard_completer, help='Keyboard to check. May be passed multiple times.')
  158. @cli.argument('-km', '--keymap', help='The keymap to check')
  159. @cli.subcommand('Check keyboard and keymap for common mistakes.')
  160. @automagic_keyboard
  161. @automagic_keymap
  162. def lint(cli):
  163. """Check keyboard and keymap for common mistakes.
  164. """
  165. # Determine our keyboard list
  166. if not cli.config.lint.keyboard:
  167. cli.log.error('Missing required arguments: --keyboard')
  168. cli.print_help()
  169. return False
  170. if isinstance(cli.config.lint.keyboard, str):
  171. # if provided via config - string not array
  172. keyboard_list = [cli.config.lint.keyboard]
  173. elif is_all_keyboards(cli.args.keyboard[0]):
  174. keyboard_list = list_keyboards()
  175. else:
  176. keyboard_list = cli.config.lint.keyboard
  177. failed = []
  178. # Lint each keyboard
  179. for kb in keyboard_list:
  180. # Determine keymaps to also check
  181. if cli.args.keymap == 'all':
  182. keymaps = list_keymaps(kb)
  183. elif cli.config.lint.keymap:
  184. keymaps = {cli.config.lint.keymap}
  185. else:
  186. keymaps = _list_defaultish_keymaps(kb)
  187. # Ensure that at least a 'default' keymap always exists
  188. keymaps.add('default')
  189. ok = True
  190. # keyboard level checks
  191. if not keyboard_check(kb):
  192. ok = False
  193. # Keymap specific checks
  194. for keymap in keymaps:
  195. if not keymap_check(kb, keymap):
  196. ok = False
  197. # Report status
  198. if not ok:
  199. failed.append(kb)
  200. # Check and report the overall status
  201. if failed:
  202. cli.log.error('Lint check failed for: %s', ', '.join(failed))
  203. return False
  204. cli.log.info('Lint check passed!')
  205. return True