doctor.py 11 KB

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