doctor.py 8.3 KB

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