lint.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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, preprocess_c_file
  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_build_files(kb, km=None):
  27. """Return potential keyboard/keymap build files
  28. """
  29. search_path = locate_keymap(kb, km).parent if km else keyboard(kb)
  30. build_files = []
  31. if not km:
  32. current_path = Path()
  33. for path_part in search_path.parts:
  34. current_path = current_path / path_part
  35. build_files.extend(current_path.glob('*rules.mk'))
  36. for file in search_path.glob("**/*rules.mk"):
  37. # Ignore keymaps when only globing keyboard files
  38. if not km and 'keymaps' in file.parts:
  39. continue
  40. build_files.append(file)
  41. return set(build_files)
  42. def _get_code_files(kb, km=None):
  43. """Return potential keyboard/keymap code files
  44. """
  45. search_path = locate_keymap(kb, km).parent if km else keyboard(kb)
  46. code_files = []
  47. if not km:
  48. current_path = Path()
  49. for path_part in search_path.parts:
  50. current_path = current_path / path_part
  51. code_files.extend(current_path.glob('*.h'))
  52. code_files.extend(current_path.glob('*.c'))
  53. for file in c_source_files([search_path]):
  54. # Ignore keymaps when only globing keyboard files
  55. if not km and 'keymaps' in file.parts:
  56. continue
  57. code_files.append(file)
  58. return code_files
  59. def _is_empty_rules(file):
  60. """Check if file contains any useful content
  61. """
  62. for line in file.read_text(encoding='utf-8').split("\n"):
  63. if len(line) > 0 and not line.isspace() and not line.startswith('#'):
  64. return False
  65. return True
  66. def _is_empty_include(file):
  67. """Check if file contains any useful content
  68. """
  69. for line in preprocess_c_file(file).split("\n"):
  70. if len(line) > 0 and not line.isspace() and not line.startswith('#pragma once'):
  71. return False
  72. return True
  73. def _has_license(file):
  74. """Check file has a license header
  75. """
  76. # Crude assumption that first line of license header is a comment
  77. fline = open(file).readline().rstrip()
  78. return fline.startswith(("/*", "//"))
  79. def _handle_json_errors(kb, info):
  80. """Convert any json errors into lint errors
  81. """
  82. ok = True
  83. # Check for errors in the json
  84. if info['parse_errors']:
  85. ok = False
  86. cli.log.error(f'{kb}: Errors found when generating info.json.')
  87. if cli.config.lint.strict and info['parse_warnings']:
  88. ok = False
  89. cli.log.error(f'{kb}: Warnings found when generating info.json (Strict mode enabled.)')
  90. return ok
  91. def _handle_invalid_features(kb, info):
  92. """Check for features that should never be enabled at the keyboard level
  93. """
  94. ok = True
  95. features = set(info.get('features', []))
  96. for found in features & INVALID_KB_FEATURES:
  97. ok = False
  98. cli.log.error(f'{kb}: Invalid keyboard level feature detected - {found}')
  99. return ok
  100. def _chibios_conf_includenext_check(target):
  101. """Check the ChibiOS conf.h for the correct inclusion of the next conf.h
  102. """
  103. for i, line in enumerate(target.open()):
  104. if f'#include_next "{target.name}"' in line:
  105. return f'Found `#include_next "{target.name}"` on line {i} of {target}, should be `#include_next <{target.name}>` (use angle brackets, not quotes)'
  106. return None
  107. def _rules_mk_assignment_only(rules_mk):
  108. """Check the keyboard-level rules.mk to ensure it only has assignments.
  109. """
  110. errors = []
  111. continuation = None
  112. for i, line in enumerate(rules_mk.open()):
  113. line = line.strip()
  114. if '#' in line:
  115. line = line[:line.index('#')]
  116. if continuation:
  117. line = continuation + line
  118. continuation = None
  119. if line:
  120. if line[-1] == '\\':
  121. continuation = line[:-1]
  122. continue
  123. if line and '=' not in line:
  124. errors.append(f'Non-assignment code on line +{i} {rules_mk}: {line}')
  125. return errors
  126. def keymap_check(kb, km):
  127. """Perform the keymap level checks.
  128. """
  129. ok = True
  130. keymap_path = locate_keymap(kb, km)
  131. if not keymap_path:
  132. ok = False
  133. cli.log.error("%s: Can't find %s keymap.", kb, km)
  134. return ok
  135. if km in INVALID_KM_NAMES:
  136. ok = False
  137. cli.log.error("%s: The keymap %s should not exist!", kb, km)
  138. return ok
  139. # Additional checks
  140. invalid_files = git_get_ignored_files(keymap_path.parent.as_posix())
  141. for file in invalid_files:
  142. cli.log.error(f'{kb}/{km}: The file "{file}" should not exist!')
  143. ok = False
  144. for file in _get_code_files(kb, km):
  145. if not _has_license(file):
  146. cli.log.error(f'{kb}/{km}: The file "{file}" does not have a license header!')
  147. ok = False
  148. if file.name in CHIBIOS_CONF_CHECKS:
  149. check_error = _chibios_conf_includenext_check(file)
  150. if check_error is not None:
  151. cli.log.error(f'{kb}/{km}: {check_error}')
  152. ok = False
  153. return ok
  154. def keyboard_check(kb):
  155. """Perform the keyboard level checks.
  156. """
  157. ok = True
  158. kb_info = info_json(kb)
  159. if not _handle_json_errors(kb, kb_info):
  160. ok = False
  161. # Additional checks
  162. if not _handle_invalid_features(kb, kb_info):
  163. ok = False
  164. invalid_files = git_get_ignored_files(f'keyboards/{kb}/')
  165. for file in invalid_files:
  166. if 'keymap' in file:
  167. continue
  168. cli.log.error(f'{kb}: The file "{file}" should not exist!')
  169. ok = False
  170. for file in _get_build_files(kb):
  171. if _is_empty_rules(file):
  172. cli.log.error(f'{kb}: The file "{file}" is effectively empty and should be removed!')
  173. ok = False
  174. if file.suffix in ['rules.mk']:
  175. rules_mk_assignment_errors = _rules_mk_assignment_only(file)
  176. if rules_mk_assignment_errors:
  177. ok = False
  178. cli.log.error('%s: Non-assignment code found in rules.mk. Move it to post_rules.mk instead.', kb)
  179. for assignment_error in rules_mk_assignment_errors:
  180. cli.log.error(assignment_error)
  181. for file in _get_code_files(kb):
  182. if not _has_license(file):
  183. cli.log.error(f'{kb}: The file "{file}" does not have a license header!')
  184. ok = False
  185. if file.name in ['config.h']:
  186. if _is_empty_include(file):
  187. cli.log.error(f'{kb}: The file "{file}" is effectively empty and should be removed!')
  188. ok = False
  189. if file.name in CHIBIOS_CONF_CHECKS:
  190. check_error = _chibios_conf_includenext_check(file)
  191. if check_error is not None:
  192. cli.log.error(f'{kb}: {check_error}')
  193. ok = False
  194. return ok
  195. @cli.argument('--strict', action='store_true', help='Treat warnings as errors')
  196. @cli.argument('-kb', '--keyboard', action='append', type=keyboard_folder_or_all, completer=keyboard_completer, help='Keyboard to check. May be passed multiple times.')
  197. @cli.argument('-km', '--keymap', help='The keymap to check')
  198. @cli.subcommand('Check keyboard and keymap for common mistakes.')
  199. @automagic_keyboard
  200. @automagic_keymap
  201. def lint(cli):
  202. """Check keyboard and keymap for common mistakes.
  203. """
  204. # Determine our keyboard list
  205. if not cli.config.lint.keyboard:
  206. cli.log.error('Missing required arguments: --keyboard')
  207. cli.print_help()
  208. return False
  209. if isinstance(cli.config.lint.keyboard, str):
  210. # if provided via config - string not array
  211. keyboard_list = [cli.config.lint.keyboard]
  212. elif is_all_keyboards(cli.args.keyboard[0]):
  213. keyboard_list = list_keyboards()
  214. else:
  215. keyboard_list = cli.config.lint.keyboard
  216. failed = []
  217. # Lint each keyboard
  218. for kb in keyboard_list:
  219. # Determine keymaps to also check
  220. if cli.args.keymap == 'all':
  221. keymaps = list_keymaps(kb)
  222. elif cli.config.lint.keymap:
  223. keymaps = {cli.config.lint.keymap}
  224. else:
  225. keymaps = _list_defaultish_keymaps(kb)
  226. # Ensure that at least a 'default' keymap always exists
  227. keymaps.add('default')
  228. ok = True
  229. # keyboard level checks
  230. if not keyboard_check(kb):
  231. ok = False
  232. # Keymap specific checks
  233. for keymap in keymaps:
  234. if not keymap_check(kb, keymap):
  235. ok = False
  236. # Report status
  237. if not ok:
  238. failed.append(kb)
  239. # Check and report the overall status
  240. if failed:
  241. cli.log.error('Lint check failed for: %s', ', '.join(failed))
  242. return False
  243. cli.log.info('Lint check passed!')
  244. return True