doctor.py 6.8 KB

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