doctor.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 = [str(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. with open(rule_file, "r") as fd:
  110. for line in fd.readlines():
  111. line = line.strip()
  112. if not line.startswith("#") and len(line):
  113. current_rules.add(line)
  114. # Check if the desired rules are among the currently present rules
  115. for bootloader, rules in desired_rules.items():
  116. if not rules.issubset(current_rules):
  117. # If the rules for catalina are not present, check if ModemManager is running
  118. if bootloader == "caterina":
  119. if check_modem_manager():
  120. ok = False
  121. 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.")
  122. else:
  123. cli.log.warn("{bg_yellow}Missing udev rules for '%s' boards. You'll need to use `sudo` in order to flash them.", bootloader)
  124. return ok
  125. def check_modem_manager():
  126. """Returns True if ModemManager is running.
  127. """
  128. if shutil.which("systemctl"):
  129. mm_check = run(["systemctl", "--quiet", "is-active", "ModemManager.service"], timeout=10)
  130. if mm_check.returncode == 0:
  131. return True
  132. else:
  133. cli.log.warn("Can't find systemctl to check for ModemManager.")
  134. def is_executable(command):
  135. """Returns True if command exists and can be executed.
  136. """
  137. # Make sure the command is in the path.
  138. res = shutil.which(command)
  139. if res is None:
  140. cli.log.error("{fg_red}Can't find %s in your path.", command)
  141. return False
  142. # Make sure the command can be executed
  143. version_arg = ESSENTIAL_BINARIES[command].get('version_arg', '--version')
  144. check = run([command, version_arg], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=5, universal_newlines=True)
  145. ESSENTIAL_BINARIES[command]['output'] = check.stdout
  146. if check.returncode in [0, 1]: # Older versions of dfu-programmer exit 1
  147. cli.log.debug('Found {fg_cyan}%s', command)
  148. return True
  149. cli.log.error("{fg_red}Can't run `%s %s`", command, version_arg)
  150. return False
  151. def os_test_linux():
  152. """Run the Linux specific tests.
  153. """
  154. cli.log.info("Detected {fg_cyan}Linux.")
  155. ok = True
  156. if not check_udev_rules():
  157. ok = False
  158. return ok
  159. def os_test_macos():
  160. """Run the Mac specific tests.
  161. """
  162. cli.log.info("Detected {fg_cyan}macOS.")
  163. return True
  164. def os_test_windows():
  165. """Run the Windows specific tests.
  166. """
  167. cli.log.info("Detected {fg_cyan}Windows.")
  168. return True
  169. @cli.argument('-y', '--yes', action='store_true', arg_only=True, help='Answer yes to all questions.')
  170. @cli.argument('-n', '--no', action='store_true', arg_only=True, help='Answer no to all questions.')
  171. @cli.subcommand('Basic QMK environment checks')
  172. def doctor(cli):
  173. """Basic QMK environment checks.
  174. This is currently very simple, it just checks that all the expected binaries are on your system.
  175. TODO(unclaimed):
  176. * [ ] Compile a trivial program with each compiler
  177. """
  178. cli.log.info('QMK Doctor is checking your environment.')
  179. ok = True
  180. # Determine our OS and run platform specific tests
  181. platform_id = platform.platform().lower()
  182. if 'darwin' in platform_id or 'macos' in platform_id:
  183. if not os_test_macos():
  184. ok = False
  185. elif 'linux' in platform_id:
  186. if not os_test_linux():
  187. ok = False
  188. elif 'windows' in platform_id:
  189. if not os_test_windows():
  190. ok = False
  191. else:
  192. cli.log.error('Unsupported OS detected: %s', platform_id)
  193. ok = False
  194. # Make sure the basic CLI tools we need are available and can be executed.
  195. bin_ok = check_binaries()
  196. if not bin_ok:
  197. if yesno('Would you like to install dependencies?', default=True):
  198. run(['util/qmk_install.sh'])
  199. bin_ok = check_binaries()
  200. if bin_ok:
  201. cli.log.info('All dependencies are installed.')
  202. else:
  203. ok = False
  204. # Make sure the tools are at the correct version
  205. for check in (check_arm_gcc_version, check_avr_gcc_version, check_avrdude_version, check_dfu_util_version, check_dfu_programmer_version):
  206. if not check():
  207. ok = False
  208. # Check out the QMK submodules
  209. sub_ok = check_submodules()
  210. if sub_ok:
  211. cli.log.info('Submodules are up to date.')
  212. else:
  213. if yesno('Would you like to clone the submodules?', default=True):
  214. submodules.update()
  215. sub_ok = check_submodules()
  216. if not sub_ok:
  217. ok = False
  218. # Report a summary of our findings to the user
  219. if ok:
  220. cli.log.info('{fg_green}QMK is ready to go')
  221. else:
  222. cli.log.info('{fg_yellow}Problems detected, please fix these problems before proceeding.')
  223. # FIXME(skullydazed/unclaimed): Link to a document about troubleshooting, or discord or something