doctor.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. """QMK Doctor
  2. Check out the user's QMK environment and make sure it's ready to compile.
  3. """
  4. import platform
  5. import shutil
  6. import subprocess
  7. from pathlib import Path
  8. from milc import cli
  9. from qmk import submodules
  10. from qmk.questions import yesno
  11. from qmk.commands import run
  12. ESSENTIAL_BINARIES = {
  13. 'dfu-programmer': {},
  14. 'avrdude': {},
  15. 'dfu-util': {},
  16. 'avr-gcc': {
  17. 'version_arg': '-dumpversion'
  18. },
  19. 'arm-none-eabi-gcc': {
  20. 'version_arg': '-dumpversion'
  21. },
  22. 'bin/qmk': {},
  23. }
  24. def _udev_rule(vid, pid=None, *args):
  25. """ Helper function that return udev rules
  26. """
  27. rule = ""
  28. if pid:
  29. rule = 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", ATTRS{idProduct}=="%s", TAG+="uaccess", RUN{builtin}+="uaccess"' % (vid, pid)
  30. else:
  31. rule = 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", TAG+="uaccess", RUN{builtin}+="uaccess"' % vid
  32. if args:
  33. rule = ', '.join([rule, *args])
  34. return rule
  35. def _deprecated_udev_rule(vid, pid=None):
  36. """ Helper function that return udev rules
  37. Note: these are no longer the recommended rules, this is just used to check for them
  38. """
  39. if pid:
  40. return 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", ATTRS{idProduct}=="%s", MODE:="0666"' % (vid, pid)
  41. else:
  42. return 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", MODE:="0666"' % vid
  43. def check_arm_gcc_version():
  44. """Returns True if the arm-none-eabi-gcc version is not known to cause problems.
  45. """
  46. if 'output' in ESSENTIAL_BINARIES['arm-none-eabi-gcc']:
  47. version_number = ESSENTIAL_BINARIES['arm-none-eabi-gcc']['output'].strip()
  48. cli.log.info('Found arm-none-eabi-gcc version %s', version_number)
  49. return True # Right now all known arm versions are ok
  50. def check_avr_gcc_version():
  51. """Returns True if the avr-gcc version is not known to cause problems.
  52. """
  53. if 'output' in ESSENTIAL_BINARIES['avr-gcc']:
  54. version_number = ESSENTIAL_BINARIES['avr-gcc']['output'].strip()
  55. major, minor, rest = version_number.split('.', 2)
  56. if int(major) > 8:
  57. cli.log.error('We do not recommend avr-gcc newer than 8. Downgrading to 8.x is recommended.')
  58. return False
  59. cli.log.info('Found avr-gcc version %s', version_number)
  60. return True
  61. return False
  62. def check_avrdude_version():
  63. if 'output' in ESSENTIAL_BINARIES['avrdude']:
  64. last_line = ESSENTIAL_BINARIES['avrdude']['output'].split('\n')[-2]
  65. version_number = last_line.split()[2][:-1]
  66. cli.log.info('Found avrdude version %s', version_number)
  67. return True
  68. def check_dfu_util_version():
  69. if 'output' in ESSENTIAL_BINARIES['dfu-util']:
  70. first_line = ESSENTIAL_BINARIES['dfu-util']['output'].split('\n')[0]
  71. version_number = first_line.split()[1]
  72. cli.log.info('Found dfu-util version %s', version_number)
  73. return True
  74. def check_dfu_programmer_version():
  75. if 'output' in ESSENTIAL_BINARIES['dfu-programmer']:
  76. first_line = ESSENTIAL_BINARIES['dfu-programmer']['output'].split('\n')[0]
  77. version_number = first_line.split()[1]
  78. cli.log.info('Found dfu-programmer version %s', version_number)
  79. return True
  80. def check_binaries():
  81. """Iterates through ESSENTIAL_BINARIES and tests them.
  82. """
  83. ok = True
  84. for binary in sorted(ESSENTIAL_BINARIES):
  85. if not is_executable(binary):
  86. ok = False
  87. return ok
  88. def check_submodules():
  89. """Iterates through all submodules to make sure they're cloned and up to date.
  90. """
  91. ok = True
  92. for submodule in submodules.status().values():
  93. if submodule['status'] is None:
  94. cli.log.error('Submodule %s has not yet been cloned!', submodule['name'])
  95. ok = False
  96. elif not submodule['status']:
  97. cli.log.error('Submodule %s is not up to date!', submodule['name'])
  98. ok = False
  99. return ok
  100. def check_udev_rules():
  101. """Make sure the udev rules look good.
  102. """
  103. ok = True
  104. udev_dir = Path("/etc/udev/rules.d/")
  105. desired_rules = {
  106. 'dfu': {_udev_rule("03eb", "2ff4"), _udev_rule("03eb", "2ffb"), _udev_rule("03eb", "2ff0")},
  107. 'input_club': {_udev_rule("1c11", "b007")},
  108. 'stm32': {_udev_rule("1eaf", "0003"), _udev_rule("0483", "df11")},
  109. 'bootloadhid': {_udev_rule("16c0", "05df")},
  110. 'caterina': {
  111. _udev_rule("2341", "0036", 'ENV{ID_MM_DEVICE_IGNORE}="1"'),
  112. _udev_rule("1b4f", "9205", 'ENV{ID_MM_DEVICE_IGNORE}="1"'),
  113. _udev_rule("1b4f", "9203", 'ENV{ID_MM_DEVICE_IGNORE}="1"'),
  114. _udev_rule("2a03", "0036", 'ENV{ID_MM_DEVICE_IGNORE}="1"')
  115. }
  116. }
  117. # These rules are no longer recommended, only use them to check for their presence.
  118. deprecated_rules = {
  119. 'dfu': {_deprecated_udev_rule("03eb", "2ff4"), _deprecated_udev_rule("03eb", "2ffb"), _deprecated_udev_rule("03eb", "2ff0")},
  120. 'input_club': {_deprecated_udev_rule("1c11")},
  121. 'stm32': {_deprecated_udev_rule("1eaf", "0003"), _deprecated_udev_rule("0483", "df11")},
  122. 'bootloadhid': {_deprecated_udev_rule("16c0", "05df")},
  123. 'caterina': {'ATTRS{idVendor}=="2a03", ENV{ID_MM_DEVICE_IGNORE}="1"', 'ATTRS{idVendor}=="2341", ENV{ID_MM_DEVICE_IGNORE}="1"'}
  124. }
  125. if udev_dir.exists():
  126. udev_rules = [rule_file for rule_file in udev_dir.glob('*.rules')]
  127. current_rules = set()
  128. # Collect all rules from the config files
  129. for rule_file in udev_rules:
  130. for line in rule_file.read_text().split('\n'):
  131. line = line.strip()
  132. if not line.startswith("#") and len(line):
  133. current_rules.add(line)
  134. # Check if the desired rules are among the currently present rules
  135. for bootloader, rules in desired_rules.items():
  136. # For caterina, check if ModemManager is running
  137. if bootloader == "caterina":
  138. if check_modem_manager():
  139. ok = False
  140. cli.log.warn("{bg_yellow}Detected ModemManager without the necessary udev rules. Please either disable it or set the appropriate udev rules if you are using a Pro Micro.")
  141. if not rules.issubset(current_rules):
  142. deprecated_rule = deprecated_rules.get(bootloader)
  143. if deprecated_rule and deprecated_rule.issubset(current_rules):
  144. cli.log.warn("{bg_yellow}Found old, deprecated udev rules for '%s' boards. The new rules on https://docs.qmk.fm/#/faq_build?id=linux-udev-rules offer better security with the same functionality.", bootloader)
  145. else:
  146. cli.log.warn("{bg_yellow}Missing udev rules for '%s' boards. You'll need to use `sudo` in order to flash them.", bootloader)
  147. return ok
  148. def check_modem_manager():
  149. """Returns True if ModemManager is running.
  150. """
  151. if shutil.which("systemctl"):
  152. mm_check = run(["systemctl", "--quiet", "is-active", "ModemManager.service"], timeout=10)
  153. if mm_check.returncode == 0:
  154. return True
  155. else:
  156. cli.log.warn("Can't find systemctl to check for ModemManager.")
  157. def is_executable(command):
  158. """Returns True if command exists and can be executed.
  159. """
  160. # Make sure the command is in the path.
  161. res = shutil.which(command)
  162. if res is None:
  163. cli.log.error("{fg_red}Can't find %s in your path.", command)
  164. return False
  165. # Make sure the command can be executed
  166. version_arg = ESSENTIAL_BINARIES[command].get('version_arg', '--version')
  167. check = run([command, version_arg], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=5, universal_newlines=True)
  168. ESSENTIAL_BINARIES[command]['output'] = check.stdout
  169. if check.returncode in [0, 1]: # Older versions of dfu-programmer exit 1
  170. cli.log.debug('Found {fg_cyan}%s', command)
  171. return True
  172. cli.log.error("{fg_red}Can't run `%s %s`", command, version_arg)
  173. return False
  174. def os_test_linux():
  175. """Run the Linux specific tests.
  176. """
  177. cli.log.info("Detected {fg_cyan}Linux.")
  178. ok = True
  179. if not check_udev_rules():
  180. ok = False
  181. return ok
  182. def os_test_macos():
  183. """Run the Mac specific tests.
  184. """
  185. cli.log.info("Detected {fg_cyan}macOS.")
  186. return True
  187. def os_test_windows():
  188. """Run the Windows specific tests.
  189. """
  190. cli.log.info("Detected {fg_cyan}Windows.")
  191. return True
  192. @cli.argument('-y', '--yes', action='store_true', arg_only=True, help='Answer yes to all questions.')
  193. @cli.argument('-n', '--no', action='store_true', arg_only=True, help='Answer no to all questions.')
  194. @cli.subcommand('Basic QMK environment checks')
  195. def doctor(cli):
  196. """Basic QMK environment checks.
  197. This is currently very simple, it just checks that all the expected binaries are on your system.
  198. TODO(unclaimed):
  199. * [ ] Compile a trivial program with each compiler
  200. """
  201. cli.log.info('QMK Doctor is checking your environment.')
  202. ok = True
  203. # Determine our OS and run platform specific tests
  204. platform_id = platform.platform().lower()
  205. if 'darwin' in platform_id or 'macos' in platform_id:
  206. if not os_test_macos():
  207. ok = False
  208. elif 'linux' in platform_id:
  209. if not os_test_linux():
  210. ok = False
  211. elif 'windows' in platform_id:
  212. if not os_test_windows():
  213. ok = False
  214. else:
  215. cli.log.error('Unsupported OS detected: %s', platform_id)
  216. ok = False
  217. # Make sure the basic CLI tools we need are available and can be executed.
  218. bin_ok = check_binaries()
  219. if not bin_ok:
  220. if yesno('Would you like to install dependencies?', default=True):
  221. run(['util/qmk_install.sh'])
  222. bin_ok = check_binaries()
  223. if bin_ok:
  224. cli.log.info('All dependencies are installed.')
  225. else:
  226. ok = False
  227. # Make sure the tools are at the correct version
  228. for check in (check_arm_gcc_version, check_avr_gcc_version, check_avrdude_version, check_dfu_util_version, check_dfu_programmer_version):
  229. if not check():
  230. ok = False
  231. # Check out the QMK submodules
  232. sub_ok = check_submodules()
  233. if sub_ok:
  234. cli.log.info('Submodules are up to date.')
  235. else:
  236. if yesno('Would you like to clone the submodules?', default=True):
  237. submodules.update()
  238. sub_ok = check_submodules()
  239. if not sub_ok:
  240. ok = False
  241. # Report a summary of our findings to the user
  242. if ok:
  243. cli.log.info('{fg_green}QMK is ready to go')
  244. else:
  245. cli.log.info('{fg_yellow}Problems detected, please fix these problems before proceeding.')
  246. # FIXME(skullydazed/unclaimed): Link to a document about troubleshooting, or discord or something