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