lint.py 11 KB

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