doctor.py 8.3 KB

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