You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

368 lines
12 KiB

4 years ago
4 years ago
4 years ago
Configuration system for CLI (#6708) * Rework how bin/qmk handles subcommands * qmk config wip * Code to show all configs * Fully working `qmk config` command * Mark some CLI arguments so they don't pollute the config file * Fleshed out config support, nicer subcommand support * sync with installable cli * pyformat * Add a test for subcommand_modules * Documentation for the `qmk config` command * split config_token on space so qmk config is more predictable * Rework how subcommands are imported * Document `arg_only` * Document deleting from CLI * Document how multiple operations work * Add cli config to the doc index * Add tests for the cli commands * Make running the tests more reliable * Be more selective about building all default keymaps * Update new-keymap to fit the new subcommand style * Add documentation about writing CLI scripts * Document new-keyboard * Update docs/cli_configuration.md Co-Authored-By: noroadsleft <18669334+noroadsleft@users.noreply.github.com> * Update docs/cli_development.md Co-Authored-By: noroadsleft <18669334+noroadsleft@users.noreply.github.com> * Update docs/cli_development.md Co-Authored-By: noroadsleft <18669334+noroadsleft@users.noreply.github.com> * Update docs/cli_development.md Co-Authored-By: noroadsleft <18669334+noroadsleft@users.noreply.github.com> * Address yan's comments. * Apply suggestions from code review suggestions from @noahfrederick Co-Authored-By: Noah Frederick <code@noahfrederick.com> * Apply suggestions from code review Co-Authored-By: Noah Frederick <code@noahfrederick.com> * Remove pip3 from the test runner
4 years ago
  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 re
  6. import shutil
  7. import subprocess
  8. from pathlib import Path
  9. from milc import cli
  10. from qmk import submodules
  11. from qmk.constants import QMK_FIRMWARE
  12. from qmk.questions import yesno
  13. from qmk.commands import run
  14. ESSENTIAL_BINARIES = {
  15. 'dfu-programmer': {},
  16. 'avrdude': {},
  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. def _udev_rule(vid, pid=None, *args):
  27. """ Helper function that return udev rules
  28. """
  29. rule = ""
  30. if pid:
  31. rule = 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", ATTRS{idProduct}=="%s", TAG+="uaccess", RUN{builtin}+="uaccess"' % (vid, pid)
  32. else:
  33. rule = 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", TAG+="uaccess", RUN{builtin}+="uaccess"' % vid
  34. if args:
  35. rule = ', '.join([rule, *args])
  36. return rule
  37. def _deprecated_udev_rule(vid, pid=None):
  38. """ Helper function that return udev rules
  39. Note: these are no longer the recommended rules, this is just used to check for them
  40. """
  41. if pid:
  42. return 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", ATTRS{idProduct}=="%s", MODE:="0666"' % (vid, pid)
  43. else:
  44. return 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", MODE:="0666"' % vid
  45. def parse_gcc_version(version):
  46. m = re.match(r"(\d+)(?:\.(\d+))?(?:\.(\d+))?", version)
  47. return {
  48. 'major': int(m.group(1)),
  49. 'minor': int(m.group(2)) if m.group(2) else 0,
  50. 'patch': int(m.group(3)) if m.group(3) else 0,
  51. }
  52. def check_arm_gcc_version():
  53. """Returns True if the arm-none-eabi-gcc version is not known to cause problems.
  54. """
  55. if 'output' in ESSENTIAL_BINARIES['arm-none-eabi-gcc']:
  56. version_number = ESSENTIAL_BINARIES['arm-none-eabi-gcc']['output'].strip()
  57. cli.log.info('Found arm-none-eabi-gcc version %s', version_number)
  58. return True # Right now all known arm versions are ok
  59. def check_avr_gcc_version():
  60. """Returns True if the avr-gcc version is not known to cause problems.
  61. """
  62. if 'output' in ESSENTIAL_BINARIES['avr-gcc']:
  63. version_number = ESSENTIAL_BINARIES['avr-gcc']['output'].strip()
  64. parsed_version = parse_gcc_version(version_number)
  65. if parsed_version['major'] > 8:
  66. cli.log.error('We do not recommend avr-gcc newer than 8. Downgrading to 8.x is recommended.')
  67. return False
  68. cli.log.info('Found avr-gcc version %s', version_number)
  69. return True
  70. return False
  71. def check_avrdude_version():
  72. if 'output' in ESSENTIAL_BINARIES['avrdude']:
  73. last_line = ESSENTIAL_BINARIES['avrdude']['output'].split('\n')[-2]
  74. version_number = last_line.split()[2][:-1]
  75. cli.log.info('Found avrdude version %s', version_number)
  76. return True
  77. def check_dfu_util_version():
  78. if 'output' in ESSENTIAL_BINARIES['dfu-util']:
  79. first_line = ESSENTIAL_BINARIES['dfu-util']['output'].split('\n')[0]
  80. version_number = first_line.split()[1]
  81. cli.log.info('Found dfu-util version %s', version_number)
  82. return True
  83. def check_dfu_programmer_version():
  84. if 'output' in ESSENTIAL_BINARIES['dfu-programmer']:
  85. first_line = ESSENTIAL_BINARIES['dfu-programmer']['output'].split('\n')[0]
  86. version_number = first_line.split()[1]
  87. cli.log.info('Found dfu-programmer version %s', version_number)
  88. return True
  89. def check_binaries():
  90. """Iterates through ESSENTIAL_BINARIES and tests them.
  91. """
  92. ok = True
  93. for binary in sorted(ESSENTIAL_BINARIES):
  94. if not is_executable(binary):
  95. ok = False
  96. return ok
  97. def check_submodules():
  98. """Iterates through all submodules to make sure they're cloned and up to date.
  99. """
  100. ok = True
  101. for submodule in submodules.status().values():
  102. if submodule['status'] is None:
  103. cli.log.error('Submodule %s has not yet been cloned!', submodule['name'])
  104. ok = False
  105. elif not submodule['status']:
  106. cli.log.error('Submodule %s is not up to date!', submodule['name'])
  107. ok = False
  108. return ok
  109. def check_udev_rules():
  110. """Make sure the udev rules look good.
  111. """
  112. ok = True
  113. udev_dir = Path("/etc/udev/rules.d/")
  114. desired_rules = {
  115. 'atmel-dfu': {
  116. _udev_rule("03EB", "2FEF"), # ATmega16U2
  117. _udev_rule("03EB", "2FF0"), # ATmega32U2
  118. _udev_rule("03EB", "2FF3"), # ATmega16U4
  119. _udev_rule("03EB", "2FF4"), # ATmega32U4
  120. _udev_rule("03EB", "2FF9"), # AT90USB64
  121. _udev_rule("03EB", "2FFB") # AT90USB128
  122. },
  123. 'kiibohd': {
  124. _udev_rule("1C11", "B007")
  125. },
  126. 'stm32': {
  127. _udev_rule("1EAF", "0003"), # STM32duino
  128. _udev_rule("0483", "DF11") # STM32 DFU
  129. },
  130. 'bootloadhid': {
  131. _udev_rule("16C0", "05DF")
  132. },
  133. 'usbasploader': {
  134. _udev_rule("16C0", "05DC")
  135. },
  136. 'massdrop': {
  137. _udev_rule("03EB", "6124")
  138. },
  139. 'caterina': {
  140. # Spark Fun Electronics
  141. _udev_rule("1B4F", "9203", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Pro Micro 3V3/8MHz
  142. _udev_rule("1B4F", "9205", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Pro Micro 5V/16MHz
  143. _udev_rule("1B4F", "9207", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # LilyPad 3V3/8MHz (and some Pro Micro clones)
  144. # Pololu Electronics
  145. _udev_rule("1FFB", "0101", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # A-Star 32U4
  146. # Arduino SA
  147. _udev_rule("2341", "0036", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Leonardo
  148. _udev_rule("2341", "0037", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Micro
  149. # Adafruit Industries LLC
  150. _udev_rule("239A", "000C", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Feather 32U4
  151. _udev_rule("239A", "000D", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # ItsyBitsy 32U4 3V3/8MHz
  152. _udev_rule("239A", "000E", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # ItsyBitsy 32U4 5V/16MHz
  153. # dog hunter AG
  154. _udev_rule("2A03", "0036", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Leonardo
  155. _udev_rule("2A03", "0037", 'ENV{ID_MM_DEVICE_IGNORE}="1"') # Micro
  156. }
  157. }
  158. # These rules are no longer recommended, only use them to check for their presence.
  159. deprecated_rules = {
  160. 'atmel-dfu': {_deprecated_udev_rule("03eb", "2ff4"), _deprecated_udev_rule("03eb", "2ffb"), _deprecated_udev_rule("03eb", "2ff0")},
  161. 'kiibohd': {_deprecated_udev_rule("1c11")},
  162. 'stm32': {_deprecated_udev_rule("1eaf", "0003"), _deprecated_udev_rule("0483", "df11")},
  163. 'bootloadhid': {_deprecated_udev_rule("16c0", "05df")},
  164. 'caterina': {'ATTRS{idVendor}=="2a03", ENV{ID_MM_DEVICE_IGNORE}="1"', 'ATTRS{idVendor}=="2341", ENV{ID_MM_DEVICE_IGNORE}="1"'},
  165. 'tmk': {_deprecated_udev_rule("feed")}
  166. }
  167. if udev_dir.exists():
  168. udev_rules = [rule_file for rule_file in udev_dir.glob('*.rules')]
  169. current_rules = set()
  170. # Collect all rules from the config files
  171. for rule_file in udev_rules:
  172. for line in rule_file.read_text().split('\n'):
  173. line = line.strip()
  174. if not line.startswith("#") and len(line):
  175. current_rules.add(line)
  176. # Check if the desired rules are among the currently present rules
  177. for bootloader, rules in desired_rules.items():
  178. # For caterina, check if ModemManager is running
  179. if bootloader == "caterina":
  180. if check_modem_manager():
  181. ok = False
  182. cli.log.warn("{bg_yellow}Detected ModemManager without the necessary udev rules. Please either disable it or set the appropriate udev rules if you are using a Pro Micro.")
  183. if not rules.issubset(current_rules):
  184. deprecated_rule = deprecated_rules.get(bootloader)
  185. if deprecated_rule and deprecated_rule.issubset(current_rules):
  186. cli.log.warn("{bg_yellow}Found old, deprecated udev rules for '%s' boards. The new rules on https://docs.qmk.fm/#/faq_build?id=linux-udev-rules offer better security with the same functionality.", bootloader)
  187. else:
  188. cli.log.warn("{bg_yellow}Missing udev rules for '%s' boards. See https://docs.qmk.fm/#/faq_build?id=linux-udev-rules for more details.", bootloader)
  189. return ok
  190. def check_modem_manager():
  191. """Returns True if ModemManager is running.
  192. """
  193. if shutil.which("systemctl"):
  194. mm_check = run(["systemctl", "--quiet", "is-active", "ModemManager.service"], timeout=10)
  195. if mm_check.returncode == 0:
  196. return True
  197. else:
  198. cli.log.warn("Can't find systemctl to check for ModemManager.")
  199. def is_executable(command):
  200. """Returns True if command exists and can be executed.
  201. """
  202. # Make sure the command is in the path.
  203. res = shutil.which(command)
  204. if res is None:
  205. cli.log.error("{fg_red}Can't find %s in your path.", command)
  206. return False
  207. # Make sure the command can be executed
  208. version_arg = ESSENTIAL_BINARIES[command].get('version_arg', '--version')
  209. check = run([command, version_arg], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=5, universal_newlines=True)
  210. ESSENTIAL_BINARIES[command]['output'] = check.stdout
  211. if check.returncode in [0, 1]: # Older versions of dfu-programmer exit 1
  212. cli.log.debug('Found {fg_cyan}%s', command)
  213. return True
  214. cli.log.error("{fg_red}Can't run `%s %s`", command, version_arg)
  215. return False
  216. def os_test_linux():
  217. """Run the Linux specific tests.
  218. """
  219. cli.log.info("Detected {fg_cyan}Linux.")
  220. ok = True
  221. if not check_udev_rules():
  222. ok = False
  223. return ok
  224. def os_test_macos():
  225. """Run the Mac specific tests.
  226. """
  227. cli.log.info("Detected {fg_cyan}macOS.")
  228. return True
  229. def os_test_windows():
  230. """Run the Windows specific tests.
  231. """
  232. cli.log.info("Detected {fg_cyan}Windows.")
  233. return True
  234. @cli.argument('-y', '--yes', action='store_true', arg_only=True, help='Answer yes to all questions.')
  235. @cli.argument('-n', '--no', action='store_true', arg_only=True, help='Answer no to all questions.')
  236. @cli.subcommand('Basic QMK environment checks')
  237. def doctor(cli):
  238. """Basic QMK environment checks.
  239. This is currently very simple, it just checks that all the expected binaries are on your system.
  240. TODO(unclaimed):
  241. * [ ] Compile a trivial program with each compiler
  242. """
  243. cli.log.info('QMK Doctor is checking your environment.')
  244. ok = True
  245. # Determine our OS and run platform specific tests
  246. platform_id = platform.platform().lower()
  247. if 'darwin' in platform_id or 'macos' in platform_id:
  248. if not os_test_macos():
  249. ok = False
  250. elif 'linux' in platform_id:
  251. if not os_test_linux():
  252. ok = False
  253. elif 'windows' in platform_id:
  254. if not os_test_windows():
  255. ok = False
  256. else:
  257. cli.log.error('Unsupported OS detected: %s', platform_id)
  258. ok = False
  259. cli.log.info('QMK home: {fg_cyan}%s', QMK_FIRMWARE)
  260. # Make sure the basic CLI tools we need are available and can be executed.
  261. bin_ok = check_binaries()
  262. if not bin_ok:
  263. if yesno('Would you like to install dependencies?', default=True):
  264. run(['util/qmk_install.sh'])
  265. bin_ok = check_binaries()
  266. if bin_ok:
  267. cli.log.info('All dependencies are installed.')
  268. else:
  269. ok = False
  270. # Make sure the tools are at the correct version
  271. for check in (check_arm_gcc_version, check_avr_gcc_version, check_avrdude_version, check_dfu_util_version, check_dfu_programmer_version):
  272. if not check():
  273. ok = False
  274. # Check out the QMK submodules
  275. sub_ok = check_submodules()
  276. if sub_ok:
  277. cli.log.info('Submodules are up to date.')
  278. else:
  279. if yesno('Would you like to clone the submodules?', default=True):
  280. submodules.update()
  281. sub_ok = check_submodules()
  282. if not sub_ok:
  283. ok = False
  284. # Report a summary of our findings to the user
  285. if ok:
  286. cli.log.info('{fg_green}QMK is ready to go')
  287. else:
  288. cli.log.info('{fg_yellow}Problems detected, please fix these problems before proceeding.')
  289. # FIXME(skullydazed/unclaimed): Link to a document about troubleshooting, or discord or something
  290. return ok