lint.py 7.4 KB

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