doctor.py 8.2 KB

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