lint.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. """Command to look over a keyboard/keymap and check for common mistakes.
  2. """
  3. from dotty_dict import dotty
  4. from pathlib import Path
  5. from milc import cli
  6. from qmk.decorators import automagic_keyboard, automagic_keymap
  7. from qmk.info import info_json
  8. from qmk.keyboard import keyboard_completer, keyboard_folder_or_all, is_all_keyboards, list_keyboards
  9. from qmk.keymap import locate_keymap, list_keymaps, is_valid_keymap_name
  10. from qmk.path import keyboard
  11. from qmk.git import git_get_ignored_files
  12. from qmk.c_parse import c_source_files, preprocess_c_file
  13. from qmk.json_schema import json_load
  14. CHIBIOS_CONF_CHECKS = ['chconf.h', 'halconf.h', 'mcuconf.h', 'board.h']
  15. INVALID_KB_FEATURES = set(['encoder_map', 'dip_switch_map', 'combo', 'tap_dance', 'via'])
  16. INVALID_KM_NAMES = ['via', 'vial']
  17. def _list_defaultish_keymaps(kb):
  18. """Return default like keymaps for a given keyboard
  19. """
  20. keymaps = set(list_keymaps(kb, include_userspace=False, include_community=False))
  21. # Ensure that at least a 'default' keymap always exists
  22. keymaps.add('default')
  23. return keymaps
  24. def _get_readme_files(kb, km=None):
  25. """Return potential keyboard/keymap readme files
  26. """
  27. search_path = locate_keymap(kb, km).parent if km else keyboard(kb)
  28. readme_files = []
  29. if not km:
  30. current_path = Path(search_path.parts[0])
  31. for path_part in search_path.parts[1:]:
  32. current_path = current_path / path_part
  33. readme_files.extend(current_path.glob('*readme.md'))
  34. for file in search_path.glob("**/*readme.md"):
  35. # Ignore keymaps when only globing keyboard files
  36. if not km and 'keymaps' in file.parts:
  37. continue
  38. readme_files.append(file)
  39. return set(readme_files)
  40. def _get_build_files(kb, km=None):
  41. """Return potential keyboard/keymap build files
  42. """
  43. search_path = locate_keymap(kb, km).parent if km else keyboard(kb)
  44. build_files = []
  45. if not km:
  46. current_path = Path()
  47. for path_part in search_path.parts:
  48. current_path = current_path / path_part
  49. build_files.extend(current_path.glob('*rules.mk'))
  50. for file in search_path.glob("**/*rules.mk"):
  51. # Ignore keymaps when only globing keyboard files
  52. if not km and 'keymaps' in file.parts:
  53. continue
  54. build_files.append(file)
  55. return set(build_files)
  56. def _get_code_files(kb, km=None):
  57. """Return potential keyboard/keymap code files
  58. """
  59. search_path = locate_keymap(kb, km).parent if km else keyboard(kb)
  60. code_files = []
  61. if not km:
  62. current_path = Path()
  63. for path_part in search_path.parts:
  64. current_path = current_path / path_part
  65. code_files.extend(current_path.glob('*.h'))
  66. code_files.extend(current_path.glob('*.c'))
  67. for file in c_source_files([search_path]):
  68. # Ignore keymaps when only globing keyboard files
  69. if not km and 'keymaps' in file.parts:
  70. continue
  71. code_files.append(file)
  72. return code_files
  73. def _is_invalid_readme(file):
  74. """Check if file contains any unfilled content
  75. """
  76. tokens = [
  77. '%KEYBOARD%',
  78. '%REAL_NAME%',
  79. '%USER_NAME%',
  80. 'image replace me!',
  81. 'A short description of the keyboard/project',
  82. 'The PCBs, controllers supported',
  83. 'Links to where you can find this hardware',
  84. ]
  85. for line in file.read_text(encoding='utf-8').split("\n"):
  86. if any(token in line for token in tokens):
  87. return True
  88. return False
  89. def _is_empty_rules(file):
  90. """Check if file contains any useful content
  91. """
  92. for line in file.read_text(encoding='utf-8').split("\n"):
  93. if len(line) > 0 and not line.isspace() and not line.startswith('#'):
  94. return False
  95. return True
  96. def _is_empty_include(file):
  97. """Check if file contains any useful content
  98. """
  99. for line in preprocess_c_file(file).split("\n"):
  100. if len(line) > 0 and not line.isspace() and not line.startswith('#pragma once'):
  101. return False
  102. return True
  103. def _has_license(file):
  104. """Check file has a license header
  105. """
  106. # Crude assumption that first line of license header is a comment
  107. fline = open(file).readline().rstrip()
  108. return fline.startswith(("/*", "//"))
  109. def _handle_json_errors(kb, info):
  110. """Convert any json errors into lint errors
  111. """
  112. ok = True
  113. # Check for errors in the json
  114. if info['parse_errors']:
  115. ok = False
  116. cli.log.error(f'{kb}: Errors found when generating info.json.')
  117. if cli.config.lint.strict and info['parse_warnings']:
  118. ok = False
  119. cli.log.error(f'{kb}: Warnings found when generating info.json (Strict mode enabled.)')
  120. return ok
  121. def _handle_invalid_features(kb, info):
  122. """Check for features that should never be enabled at the keyboard level
  123. """
  124. ok = True
  125. features = set(info.get('features', []))
  126. for found in features & INVALID_KB_FEATURES:
  127. ok = False
  128. cli.log.error(f'{kb}: Invalid keyboard level feature detected - {found}')
  129. return ok
  130. def _handle_invalid_config(kb, info):
  131. """Check for invalid keyboard level config
  132. """
  133. if info.get('url') == "":
  134. cli.log.warning(f'{kb}: Invalid keyboard level config detected - Optional field "url" should not be empty.')
  135. return True
  136. def _chibios_conf_includenext_check(target):
  137. """Check the ChibiOS conf.h for the correct inclusion of the next conf.h
  138. """
  139. for i, line in enumerate(target.open()):
  140. if f'#include_next "{target.name}"' in line:
  141. return f'Found `#include_next "{target.name}"` on line {i} of {target}, should be `#include_next <{target.name}>` (use angle brackets, not quotes)'
  142. return None
  143. def _rules_mk_assignment_only(rules_mk):
  144. """Check the keyboard-level rules.mk to ensure it only has assignments.
  145. """
  146. errors = []
  147. continuation = None
  148. for i, line in enumerate(rules_mk.open()):
  149. line = line.strip()
  150. if '#' in line:
  151. line = line[:line.index('#')]
  152. if continuation:
  153. line = continuation + line
  154. continuation = None
  155. if line:
  156. if line[-1] == '\\':
  157. continuation = line[:-1]
  158. continue
  159. if line and '=' not in line:
  160. errors.append(f'Non-assignment code on line +{i} {rules_mk}: {line}')
  161. return errors
  162. def _handle_duplicating_code_defaults(kb, info):
  163. def _collect_dotted_output(kb_info_json, prefix=''):
  164. """Print the info.json in a plain text format with dot-joined keys.
  165. """
  166. for key in sorted(kb_info_json):
  167. new_prefix = f'{prefix}.{key}' if prefix else key
  168. if isinstance(kb_info_json[key], dict):
  169. yield from _collect_dotted_output(kb_info_json[key], new_prefix)
  170. elif isinstance(kb_info_json[key], list):
  171. # TODO: handle non primitives?
  172. yield (new_prefix, kb_info_json[key])
  173. else:
  174. yield (new_prefix, kb_info_json[key])
  175. defaults_map = json_load(Path('data/mappings/info_defaults.hjson'))
  176. dotty_info = dotty(info)
  177. ok = True
  178. for key, v_default in _collect_dotted_output(defaults_map):
  179. v_info = dotty_info.get(key)
  180. if v_default == v_info:
  181. cli.log.error(f'{kb}: Option "{key}" duplicates default value of "{v_default}"')
  182. ok = False
  183. return ok
  184. def keymap_check(kb, km):
  185. """Perform the keymap level checks.
  186. """
  187. keymap_path = locate_keymap(kb, km)
  188. if not keymap_path:
  189. cli.log.error("%s: Can't find %s keymap.", kb, km)
  190. return False
  191. if km in INVALID_KM_NAMES:
  192. cli.log.error("%s: The keymap %s should not exist!", kb, km)
  193. return False
  194. ok = True
  195. if not is_valid_keymap_name(km):
  196. cli.log.error(f'{kb}/{km}: Keymap name must contain only a-z, 0-9 and _!')
  197. ok = False
  198. # Additional checks
  199. invalid_files = git_get_ignored_files(keymap_path.parent.as_posix())
  200. for file in invalid_files:
  201. cli.log.error(f'{kb}/{km}: The file "{file}" should not exist!')
  202. ok = False
  203. for file in _get_code_files(kb, km):
  204. if not _has_license(file):
  205. cli.log.error(f'{kb}/{km}: The file "{file}" does not have a license header!')
  206. ok = False
  207. if file.name in CHIBIOS_CONF_CHECKS:
  208. check_error = _chibios_conf_includenext_check(file)
  209. if check_error is not None:
  210. cli.log.error(f'{kb}/{km}: {check_error}')
  211. ok = False
  212. return ok
  213. def keyboard_check(kb): # noqa C901
  214. """Perform the keyboard level checks.
  215. """
  216. ok = True
  217. kb_info = info_json(kb)
  218. if not _handle_json_errors(kb, kb_info):
  219. ok = False
  220. # Additional checks
  221. if not _handle_invalid_features(kb, kb_info):
  222. ok = False
  223. if not _handle_invalid_config(kb, kb_info):
  224. ok = False
  225. if not _handle_duplicating_code_defaults(kb, kb_info):
  226. ok = False
  227. invalid_files = git_get_ignored_files(f'keyboards/{kb}/')
  228. for file in invalid_files:
  229. if 'keymap' in file:
  230. continue
  231. cli.log.error(f'{kb}: The file "{file}" should not exist!')
  232. ok = False
  233. if not _get_readme_files(kb):
  234. cli.log.error(f'{kb}: Is missing a readme.md file!')
  235. ok = False
  236. for file in _get_readme_files(kb):
  237. if _is_invalid_readme(file):
  238. cli.log.error(f'{kb}: The file "{file}" still contains template tokens!')
  239. ok = False
  240. for file in _get_build_files(kb):
  241. if _is_empty_rules(file):
  242. cli.log.error(f'{kb}: The file "{file}" is effectively empty and should be removed!')
  243. ok = False
  244. if file.suffix in ['rules.mk']:
  245. rules_mk_assignment_errors = _rules_mk_assignment_only(file)
  246. if rules_mk_assignment_errors:
  247. ok = False
  248. cli.log.error('%s: Non-assignment code found in rules.mk. Move it to post_rules.mk instead.', kb)
  249. for assignment_error in rules_mk_assignment_errors:
  250. cli.log.error(assignment_error)
  251. for file in _get_code_files(kb):
  252. if not _has_license(file):
  253. cli.log.error(f'{kb}: The file "{file}" does not have a license header!')
  254. ok = False
  255. if file.name in ['config.h']:
  256. if _is_empty_include(file):
  257. cli.log.error(f'{kb}: The file "{file}" is effectively empty and should be removed!')
  258. ok = False
  259. if file.name in CHIBIOS_CONF_CHECKS:
  260. check_error = _chibios_conf_includenext_check(file)
  261. if check_error is not None:
  262. cli.log.error(f'{kb}: {check_error}')
  263. ok = False
  264. return ok
  265. @cli.argument('--strict', action='store_true', help='Treat warnings as errors')
  266. @cli.argument('-kb', '--keyboard', action='append', type=keyboard_folder_or_all, completer=keyboard_completer, help='Keyboard to check. May be passed multiple times.')
  267. @cli.argument('-km', '--keymap', help='The keymap to check')
  268. @cli.subcommand('Check keyboard and keymap for common mistakes.')
  269. @automagic_keyboard
  270. @automagic_keymap
  271. def lint(cli):
  272. """Check keyboard and keymap for common mistakes.
  273. """
  274. # Determine our keyboard list
  275. if not cli.config.lint.keyboard:
  276. cli.log.error('Missing required arguments: --keyboard')
  277. cli.print_help()
  278. return False
  279. # milc config handling of user.keymap breaks running lint without keymap argument
  280. # so we have to disable that while still allowing a default to be set with lint.keymap
  281. if 'keymap' not in cli.config_source.lint.keys() and cli.config.lint.keymap:
  282. cli.config.lint.keymap = None
  283. if isinstance(cli.config.lint.keyboard, str):
  284. # if provided via config - string not array
  285. keyboard_list = [cli.config.lint.keyboard]
  286. elif any(is_all_keyboards(kb) for kb in cli.args.keyboard):
  287. keyboard_list = list_keyboards()
  288. else:
  289. keyboard_list = list(set(cli.config.lint.keyboard))
  290. failed = []
  291. # Lint each keyboard
  292. for kb in keyboard_list:
  293. # Determine keymaps to also check
  294. if cli.args.keymap == 'all':
  295. keymaps = list_keymaps(kb)
  296. elif cli.args.keymap:
  297. keymaps = {cli.args.keymap}
  298. elif cli.config.lint.keymap:
  299. keymaps = {cli.config.lint.keymap}
  300. else:
  301. keymaps = _list_defaultish_keymaps(kb)
  302. ok = True
  303. # keyboard level checks
  304. if not keyboard_check(kb):
  305. ok = False
  306. # Keymap specific checks
  307. for keymap in keymaps:
  308. if not keymap_check(kb, keymap):
  309. ok = False
  310. # Report status
  311. if not ok:
  312. failed.append(kb)
  313. # Check and report the overall status
  314. if failed:
  315. cli.log.error('Lint check failed for: %s', ', '.join(failed))
  316. return False
  317. cli.log.info('Lint check passed!')
  318. return True