1
0

lint.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 _chibios_conf_includenext_check(target):
  131. """Check the ChibiOS conf.h for the correct inclusion of the next conf.h
  132. """
  133. for i, line in enumerate(target.open()):
  134. if f'#include_next "{target.name}"' in line:
  135. return f'Found `#include_next "{target.name}"` on line {i} of {target}, should be `#include_next <{target.name}>` (use angle brackets, not quotes)'
  136. return None
  137. def _rules_mk_assignment_only(rules_mk):
  138. """Check the keyboard-level rules.mk to ensure it only has assignments.
  139. """
  140. errors = []
  141. continuation = None
  142. for i, line in enumerate(rules_mk.open()):
  143. line = line.strip()
  144. if '#' in line:
  145. line = line[:line.index('#')]
  146. if continuation:
  147. line = continuation + line
  148. continuation = None
  149. if line:
  150. if line[-1] == '\\':
  151. continuation = line[:-1]
  152. continue
  153. if line and '=' not in line:
  154. errors.append(f'Non-assignment code on line +{i} {rules_mk}: {line}')
  155. return errors
  156. def _handle_duplicating_code_defaults(kb, info):
  157. def _collect_dotted_output(kb_info_json, prefix=''):
  158. """Print the info.json in a plain text format with dot-joined keys.
  159. """
  160. for key in sorted(kb_info_json):
  161. new_prefix = f'{prefix}.{key}' if prefix else key
  162. if isinstance(kb_info_json[key], dict):
  163. yield from _collect_dotted_output(kb_info_json[key], new_prefix)
  164. elif isinstance(kb_info_json[key], list):
  165. # TODO: handle non primitives?
  166. yield (new_prefix, kb_info_json[key])
  167. else:
  168. yield (new_prefix, kb_info_json[key])
  169. defaults_map = json_load(Path('data/mappings/info_defaults.hjson'))
  170. dotty_info = dotty(info)
  171. ok = True
  172. for key, v_default in _collect_dotted_output(defaults_map):
  173. v_info = dotty_info.get(key)
  174. if v_default == v_info:
  175. cli.log.error(f'{kb}: Option "{key}" duplicates default value of "{v_default}"')
  176. ok = False
  177. return ok
  178. def keymap_check(kb, km):
  179. """Perform the keymap level checks.
  180. """
  181. keymap_path = locate_keymap(kb, km)
  182. if not keymap_path:
  183. cli.log.error("%s: Can't find %s keymap.", kb, km)
  184. return False
  185. if km in INVALID_KM_NAMES:
  186. cli.log.error("%s: The keymap %s should not exist!", kb, km)
  187. return False
  188. ok = True
  189. if not is_valid_keymap_name(km):
  190. cli.log.error(f'{kb}/{km}: Keymap name must contain only a-z, 0-9 and _!')
  191. ok = False
  192. # Additional checks
  193. invalid_files = git_get_ignored_files(keymap_path.parent.as_posix())
  194. for file in invalid_files:
  195. cli.log.error(f'{kb}/{km}: The file "{file}" should not exist!')
  196. ok = False
  197. for file in _get_code_files(kb, km):
  198. if not _has_license(file):
  199. cli.log.error(f'{kb}/{km}: The file "{file}" does not have a license header!')
  200. ok = False
  201. if file.name in CHIBIOS_CONF_CHECKS:
  202. check_error = _chibios_conf_includenext_check(file)
  203. if check_error is not None:
  204. cli.log.error(f'{kb}/{km}: {check_error}')
  205. ok = False
  206. return ok
  207. def keyboard_check(kb): # noqa C901
  208. """Perform the keyboard level checks.
  209. """
  210. ok = True
  211. kb_info = info_json(kb)
  212. if not _handle_json_errors(kb, kb_info):
  213. ok = False
  214. # Additional checks
  215. if not _handle_invalid_features(kb, kb_info):
  216. ok = False
  217. if not _handle_duplicating_code_defaults(kb, kb_info):
  218. ok = False
  219. invalid_files = git_get_ignored_files(f'keyboards/{kb}/')
  220. for file in invalid_files:
  221. if 'keymap' in file:
  222. continue
  223. cli.log.error(f'{kb}: The file "{file}" should not exist!')
  224. ok = False
  225. if not _get_readme_files(kb):
  226. cli.log.error(f'{kb}: Is missing a readme.md file!')
  227. ok = False
  228. for file in _get_readme_files(kb):
  229. if _is_invalid_readme(file):
  230. cli.log.error(f'{kb}: The file "{file}" still contains template tokens!')
  231. ok = False
  232. for file in _get_build_files(kb):
  233. if _is_empty_rules(file):
  234. cli.log.error(f'{kb}: The file "{file}" is effectively empty and should be removed!')
  235. ok = False
  236. if file.suffix in ['rules.mk']:
  237. rules_mk_assignment_errors = _rules_mk_assignment_only(file)
  238. if rules_mk_assignment_errors:
  239. ok = False
  240. cli.log.error('%s: Non-assignment code found in rules.mk. Move it to post_rules.mk instead.', kb)
  241. for assignment_error in rules_mk_assignment_errors:
  242. cli.log.error(assignment_error)
  243. for file in _get_code_files(kb):
  244. if not _has_license(file):
  245. cli.log.error(f'{kb}: The file "{file}" does not have a license header!')
  246. ok = False
  247. if file.name in ['config.h']:
  248. if _is_empty_include(file):
  249. cli.log.error(f'{kb}: The file "{file}" is effectively empty and should be removed!')
  250. ok = False
  251. if file.name in CHIBIOS_CONF_CHECKS:
  252. check_error = _chibios_conf_includenext_check(file)
  253. if check_error is not None:
  254. cli.log.error(f'{kb}: {check_error}')
  255. ok = False
  256. return ok
  257. @cli.argument('--strict', action='store_true', help='Treat warnings as errors')
  258. @cli.argument('-kb', '--keyboard', action='append', type=keyboard_folder_or_all, completer=keyboard_completer, help='Keyboard to check. May be passed multiple times.')
  259. @cli.argument('-km', '--keymap', help='The keymap to check')
  260. @cli.subcommand('Check keyboard and keymap for common mistakes.')
  261. @automagic_keyboard
  262. @automagic_keymap
  263. def lint(cli):
  264. """Check keyboard and keymap for common mistakes.
  265. """
  266. # Determine our keyboard list
  267. if not cli.config.lint.keyboard:
  268. cli.log.error('Missing required arguments: --keyboard')
  269. cli.print_help()
  270. return False
  271. # milc config handling of user.keymap breaks running lint without keymap argument
  272. # so we have to disable that while still allowing a default to be set with lint.keymap
  273. if 'keymap' not in cli.config_source.lint.keys() and cli.config.lint.keymap:
  274. cli.config.lint.keymap = None
  275. if isinstance(cli.config.lint.keyboard, str):
  276. # if provided via config - string not array
  277. keyboard_list = [cli.config.lint.keyboard]
  278. elif any(is_all_keyboards(kb) for kb in cli.args.keyboard):
  279. keyboard_list = list_keyboards()
  280. else:
  281. keyboard_list = list(set(cli.config.lint.keyboard))
  282. failed = []
  283. # Lint each keyboard
  284. for kb in keyboard_list:
  285. # Determine keymaps to also check
  286. if cli.args.keymap == 'all':
  287. keymaps = list_keymaps(kb)
  288. elif cli.args.keymap:
  289. keymaps = {cli.args.keymap}
  290. elif cli.config.lint.keymap:
  291. keymaps = {cli.config.lint.keymap}
  292. else:
  293. keymaps = _list_defaultish_keymaps(kb)
  294. ok = True
  295. # keyboard level checks
  296. if not keyboard_check(kb):
  297. ok = False
  298. # Keymap specific checks
  299. for keymap in keymaps:
  300. if not keymap_check(kb, keymap):
  301. ok = False
  302. # Report status
  303. if not ok:
  304. failed.append(kb)
  305. # Check and report the overall status
  306. if failed:
  307. cli.log.error('Lint check failed for: %s', ', '.join(failed))
  308. return False
  309. cli.log.info('Lint check passed!')
  310. return True