lint.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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, include_userspace=False):
  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 _handle_invalid_config(kb, info):
  133. """Check for invalid keyboard level config
  134. """
  135. if info.get('url') == "":
  136. cli.log.warning(f'{kb}: Invalid keyboard level config detected - Optional field "url" should not be empty.')
  137. return True
  138. def _chibios_conf_includenext_check(target):
  139. """Check the ChibiOS conf.h for the correct inclusion of the next conf.h
  140. """
  141. for i, line in enumerate(target.open()):
  142. if f'#include_next "{target.name}"' in line:
  143. return f'Found `#include_next "{target.name}"` on line {i} of {target}, should be `#include_next <{target.name}>` (use angle brackets, not quotes)'
  144. return None
  145. def _rules_mk_assignment_only(rules_mk):
  146. """Check the keyboard-level rules.mk to ensure it only has assignments.
  147. """
  148. errors = []
  149. continuation = None
  150. for i, line in enumerate(rules_mk.open()):
  151. line = line.strip()
  152. if '#' in line:
  153. line = line[:line.index('#')]
  154. if continuation:
  155. line = continuation + line
  156. continuation = None
  157. if line:
  158. if line[-1] == '\\':
  159. continuation = line[:-1]
  160. continue
  161. if line and '=' not in line:
  162. errors.append(f'Non-assignment code on line +{i} {rules_mk}: {line}')
  163. return errors
  164. def keymap_check(kb, km):
  165. """Perform the keymap level checks.
  166. """
  167. ok = True
  168. keymap_path = locate_keymap(kb, km)
  169. if not keymap_path:
  170. ok = False
  171. cli.log.error("%s: Can't find %s keymap.", kb, km)
  172. return ok
  173. if km in INVALID_KM_NAMES:
  174. ok = False
  175. cli.log.error("%s: The keymap %s should not exist!", kb, km)
  176. return ok
  177. # Additional checks
  178. invalid_files = git_get_ignored_files(keymap_path.parent.as_posix())
  179. for file in invalid_files:
  180. cli.log.error(f'{kb}/{km}: The file "{file}" should not exist!')
  181. ok = False
  182. for file in _get_code_files(kb, km):
  183. if not _has_license(file):
  184. cli.log.error(f'{kb}/{km}: The file "{file}" does not have a license header!')
  185. ok = False
  186. if file.name in CHIBIOS_CONF_CHECKS:
  187. check_error = _chibios_conf_includenext_check(file)
  188. if check_error is not None:
  189. cli.log.error(f'{kb}/{km}: {check_error}')
  190. ok = False
  191. return ok
  192. def keyboard_check(kb): # noqa C901
  193. """Perform the keyboard level checks.
  194. """
  195. ok = True
  196. kb_info = info_json(kb)
  197. if not _handle_json_errors(kb, kb_info):
  198. ok = False
  199. # Additional checks
  200. if not _handle_invalid_features(kb, kb_info):
  201. ok = False
  202. if not _handle_invalid_config(kb, kb_info):
  203. ok = False
  204. invalid_files = git_get_ignored_files(f'keyboards/{kb}/')
  205. for file in invalid_files:
  206. if 'keymap' in file:
  207. continue
  208. cli.log.error(f'{kb}: The file "{file}" should not exist!')
  209. ok = False
  210. for file in _get_readme_files(kb):
  211. if _is_invalid_readme(file):
  212. cli.log.error(f'{kb}: The file "{file}" still contains template tokens!')
  213. ok = False
  214. for file in _get_build_files(kb):
  215. if _is_empty_rules(file):
  216. cli.log.error(f'{kb}: The file "{file}" is effectively empty and should be removed!')
  217. ok = False
  218. if file.suffix in ['rules.mk']:
  219. rules_mk_assignment_errors = _rules_mk_assignment_only(file)
  220. if rules_mk_assignment_errors:
  221. ok = False
  222. cli.log.error('%s: Non-assignment code found in rules.mk. Move it to post_rules.mk instead.', kb)
  223. for assignment_error in rules_mk_assignment_errors:
  224. cli.log.error(assignment_error)
  225. for file in _get_code_files(kb):
  226. if not _has_license(file):
  227. cli.log.error(f'{kb}: The file "{file}" does not have a license header!')
  228. ok = False
  229. if file.name in ['config.h']:
  230. if _is_empty_include(file):
  231. cli.log.error(f'{kb}: The file "{file}" is effectively empty and should be removed!')
  232. ok = False
  233. if file.name in CHIBIOS_CONF_CHECKS:
  234. check_error = _chibios_conf_includenext_check(file)
  235. if check_error is not None:
  236. cli.log.error(f'{kb}: {check_error}')
  237. ok = False
  238. return ok
  239. @cli.argument('--strict', action='store_true', help='Treat warnings as errors')
  240. @cli.argument('-kb', '--keyboard', action='append', type=keyboard_folder_or_all, completer=keyboard_completer, help='Keyboard to check. May be passed multiple times.')
  241. @cli.argument('-km', '--keymap', help='The keymap to check')
  242. @cli.subcommand('Check keyboard and keymap for common mistakes.')
  243. @automagic_keyboard
  244. @automagic_keymap
  245. def lint(cli):
  246. """Check keyboard and keymap for common mistakes.
  247. """
  248. # Determine our keyboard list
  249. if not cli.config.lint.keyboard:
  250. cli.log.error('Missing required arguments: --keyboard')
  251. cli.print_help()
  252. return False
  253. if isinstance(cli.config.lint.keyboard, str):
  254. # if provided via config - string not array
  255. keyboard_list = [cli.config.lint.keyboard]
  256. elif any(is_all_keyboards(kb) for kb in cli.args.keyboard):
  257. keyboard_list = list_keyboards()
  258. else:
  259. keyboard_list = list(set(cli.config.lint.keyboard))
  260. failed = []
  261. # Lint each keyboard
  262. for kb in keyboard_list:
  263. # Determine keymaps to also check
  264. if cli.args.keymap == 'all':
  265. keymaps = list_keymaps(kb)
  266. elif cli.config.lint.keymap:
  267. keymaps = {cli.config.lint.keymap}
  268. else:
  269. keymaps = _list_defaultish_keymaps(kb)
  270. # Ensure that at least a 'default' keymap always exists
  271. keymaps.add('default')
  272. ok = True
  273. # keyboard level checks
  274. if not keyboard_check(kb):
  275. ok = False
  276. # Keymap specific checks
  277. for keymap in keymaps:
  278. if not keymap_check(kb, keymap):
  279. ok = False
  280. # Report status
  281. if not ok:
  282. failed.append(kb)
  283. # Check and report the overall status
  284. if failed:
  285. cli.log.error('Lint check failed for: %s', ', '.join(failed))
  286. return False
  287. cli.log.info('Lint check passed!')
  288. return True