lint.py 7.9 KB

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