doctor.py 8.2 KB

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