lint.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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, list_keyboards
  8. from qmk.keymap import locate_keymap, list_keymaps
  9. from qmk.path import is_keyboard, keyboard
  10. from qmk.git import git_get_ignored_files
  11. from qmk.c_parse import c_source_files
  12. CHIBIOS_CONF_CHECKS = ['chconf.h', 'halconf.h', 'mcuconf.h', 'board.h']
  13. def _list_defaultish_keymaps(kb):
  14. """Return default like keymaps for a given keyboard
  15. """
  16. defaultish = ['ansi', 'iso', 'via']
  17. # This is only here to flag it as "testable", so it doesn't fly under the radar during PR
  18. defaultish.append('vial')
  19. keymaps = set()
  20. for x in list_keymaps(kb):
  21. if x in defaultish or x.startswith('default'):
  22. keymaps.add(x)
  23. return keymaps
  24. def _get_code_files(kb, km=None):
  25. """Return potential keyboard/keymap code files
  26. """
  27. search_path = locate_keymap(kb, km).parent if km else keyboard(kb)
  28. code_files = []
  29. for file in c_source_files([search_path]):
  30. # Ignore keymaps when only globing keyboard files
  31. if not km and 'keymaps' in file.parts:
  32. continue
  33. code_files.append(file)
  34. return code_files
  35. def _has_license(file):
  36. """Check file has a license header
  37. """
  38. # Crude assumption that first line of license header is a comment
  39. fline = open(file).readline().rstrip()
  40. return fline.startswith(("/*", "//"))
  41. def _handle_json_errors(kb, info):
  42. """Convert any json errors into lint errors
  43. """
  44. ok = True
  45. # Check for errors in the json
  46. if info['parse_errors']:
  47. ok = False
  48. cli.log.error(f'{kb}: Errors found when generating info.json.')
  49. if cli.config.lint.strict and info['parse_warnings']:
  50. ok = False
  51. cli.log.error(f'{kb}: Warnings found when generating info.json (Strict mode enabled.)')
  52. return ok
  53. def _chibios_conf_includenext_check(target):
  54. """Check the ChibiOS conf.h for the correct inclusion of the next conf.h
  55. """
  56. for i, line in enumerate(target.open()):
  57. if f'#include_next "{target.name}"' in line:
  58. return f'Found `#include_next "{target.name}"` on line {i} of {target}, should be `#include_next <{target.name}>` (use angle brackets, not quotes)'
  59. return None
  60. def _rules_mk_assignment_only(kb):
  61. """Check the keyboard-level rules.mk to ensure it only has assignments.
  62. """
  63. keyboard_path = keyboard(kb)
  64. current_path = Path()
  65. errors = []
  66. for path_part in keyboard_path.parts:
  67. current_path = current_path / path_part
  68. rules_mk = current_path / 'rules.mk'
  69. if rules_mk.exists():
  70. continuation = None
  71. for i, line in enumerate(rules_mk.open()):
  72. line = line.strip()
  73. if '#' in line:
  74. line = line[:line.index('#')]
  75. if continuation:
  76. line = continuation + line
  77. continuation = None
  78. if line:
  79. if line[-1] == '\\':
  80. continuation = line[:-1]
  81. continue
  82. if line and '=' not in line:
  83. errors.append(f'Non-assignment code on line +{i} {rules_mk}: {line}')
  84. return errors
  85. def keymap_check(kb, km):
  86. """Perform the keymap level checks.
  87. """
  88. ok = True
  89. keymap_path = locate_keymap(kb, km)
  90. if not keymap_path:
  91. ok = False
  92. cli.log.error("%s: Can't find %s keymap.", kb, km)
  93. return ok
  94. # Additional checks
  95. invalid_files = git_get_ignored_files(keymap_path.parent.as_posix())
  96. for file in invalid_files:
  97. cli.log.error(f'{kb}/{km}: The file "{file}" should not exist!')
  98. ok = False
  99. for file in _get_code_files(kb, km):
  100. if not _has_license(file):
  101. cli.log.error(f'{kb}/{km}: The file "{file}" does not have a license header!')
  102. ok = False
  103. if file.name in CHIBIOS_CONF_CHECKS:
  104. check_error = _chibios_conf_includenext_check(file)
  105. if check_error is not None:
  106. cli.log.error(f'{kb}/{km}: {check_error}')
  107. ok = False
  108. return ok
  109. def keyboard_check(kb):
  110. """Perform the keyboard level checks.
  111. """
  112. ok = True
  113. kb_info = info_json(kb)
  114. if not _handle_json_errors(kb, kb_info):
  115. ok = False
  116. # Additional checks
  117. rules_mk_assignment_errors = _rules_mk_assignment_only(kb)
  118. if rules_mk_assignment_errors:
  119. ok = False
  120. cli.log.error('%s: Non-assignment code found in rules.mk. Move it to post_rules.mk instead.', kb)
  121. for assignment_error in rules_mk_assignment_errors:
  122. cli.log.error(assignment_error)
  123. invalid_files = git_get_ignored_files(f'keyboards/{kb}/')
  124. for file in invalid_files:
  125. if 'keymap' in file:
  126. continue
  127. cli.log.error(f'{kb}: The file "{file}" should not exist!')
  128. ok = False
  129. for file in _get_code_files(kb):
  130. if not _has_license(file):
  131. cli.log.error(f'{kb}: The file "{file}" does not have a license header!')
  132. ok = False
  133. if file.name in CHIBIOS_CONF_CHECKS:
  134. check_error = _chibios_conf_includenext_check(file)
  135. if check_error is not None:
  136. cli.log.error(f'{kb}: {check_error}')
  137. ok = False
  138. return ok
  139. @cli.argument('--strict', action='store_true', help='Treat warnings as errors')
  140. @cli.argument('-kb', '--keyboard', completer=keyboard_completer, help='Comma separated list of keyboards to check')
  141. @cli.argument('-km', '--keymap', help='The keymap to check')
  142. @cli.argument('--all-kb', action='store_true', arg_only=True, help='Check all keyboards')
  143. @cli.argument('--all-km', action='store_true', arg_only=True, help='Check all keymaps')
  144. @cli.subcommand('Check keyboard and keymap for common mistakes.')
  145. @automagic_keyboard
  146. @automagic_keymap
  147. def lint(cli):
  148. """Check keyboard and keymap for common mistakes.
  149. """
  150. failed = []
  151. # Determine our keyboard list
  152. if cli.args.all_kb:
  153. if cli.args.keyboard:
  154. cli.log.warning('Both --all-kb and --keyboard passed, --all-kb takes precedence.')
  155. keyboard_list = list_keyboards()
  156. elif not cli.config.lint.keyboard:
  157. cli.log.error('Missing required arguments: --keyboard or --all-kb')
  158. cli.print_help()
  159. return False
  160. else:
  161. keyboard_list = cli.config.lint.keyboard.split(',')
  162. # Lint each keyboard
  163. for kb in keyboard_list:
  164. if not is_keyboard(kb):
  165. cli.log.error('No such keyboard: %s', kb)
  166. continue
  167. # Determine keymaps to also check
  168. if cli.args.all_km:
  169. keymaps = list_keymaps(kb)
  170. elif cli.config.lint.keymap:
  171. keymaps = {cli.config.lint.keymap}
  172. else:
  173. keymaps = _list_defaultish_keymaps(kb)
  174. # Ensure that at least a 'default' keymap always exists
  175. keymaps.add('default')
  176. ok = True
  177. # keyboard level checks
  178. if not keyboard_check(kb):
  179. ok = False
  180. # Keymap specific checks
  181. for keymap in keymaps:
  182. if not keymap_check(kb, keymap):
  183. ok = False
  184. # Report status
  185. if not ok:
  186. failed.append(kb)
  187. # Check and report the overall status
  188. if failed:
  189. cli.log.error('Lint check failed for: %s', ', '.join(failed))
  190. return False
  191. cli.log.info('Lint check passed!')
  192. return True