doctor.py 9.1 KB

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