aboutsummaryrefslogtreecommitdiff
path: root/lib/python/qmk/cli/doctor
diff options
context:
space:
mode:
authorZach White <skullydazed@gmail.com>2021-06-22 11:50:53 -0700
committerGitHub <noreply@github.com>2021-06-22 19:50:53 +0100
commite87d23164522371b0c9560e81f36ed08caadc0ff (patch)
tree481bff93f77418ac7603d8ad4af492b4c86a02c2 /lib/python/qmk/cli/doctor
parentd61e5c0027e289ccf48652afa4c442342e7ccf04 (diff)
downloadqmk_firmware-e87d23164522371b0c9560e81f36ed08caadc0ff.tar.gz
qmk_firmware-e87d23164522371b0c9560e81f36ed08caadc0ff.zip
Refactor doctor.py into a directory (#13298)
Diffstat (limited to 'lib/python/qmk/cli/doctor')
-rwxr-xr-xlib/python/qmk/cli/doctor/__init__.py5
-rw-r--r--lib/python/qmk/cli/doctor/check.py164
-rw-r--r--lib/python/qmk/cli/doctor/linux.py162
-rw-r--r--lib/python/qmk/cli/doctor/macos.py13
-rwxr-xr-xlib/python/qmk/cli/doctor/main.py103
-rw-r--r--lib/python/qmk/cli/doctor/windows.py14
6 files changed, 461 insertions, 0 deletions
diff --git a/lib/python/qmk/cli/doctor/__init__.py b/lib/python/qmk/cli/doctor/__init__.py
new file mode 100755
index 000000000..272e04202
--- /dev/null
+++ b/lib/python/qmk/cli/doctor/__init__.py
@@ -0,0 +1,5 @@
1"""QMK Doctor
2
3Check out the user's QMK environment and make sure it's ready to compile.
4"""
5from .main import doctor
diff --git a/lib/python/qmk/cli/doctor/check.py b/lib/python/qmk/cli/doctor/check.py
new file mode 100644
index 000000000..a0bbb2816
--- /dev/null
+++ b/lib/python/qmk/cli/doctor/check.py
@@ -0,0 +1,164 @@
1"""Check for specific programs.
2"""
3from enum import Enum
4import re
5import shutil
6from subprocess import DEVNULL
7
8from milc import cli
9from qmk import submodules
10from qmk.constants import QMK_FIRMWARE
11
12
13class CheckStatus(Enum):
14 OK = 1
15 WARNING = 2
16 ERROR = 3
17
18
19ESSENTIAL_BINARIES = {
20 'dfu-programmer': {},
21 'avrdude': {},
22 'dfu-util': {},
23 'avr-gcc': {
24 'version_arg': '-dumpversion'
25 },
26 'arm-none-eabi-gcc': {
27 'version_arg': '-dumpversion'
28 },
29 'bin/qmk': {},
30}
31
32
33def _parse_gcc_version(version):
34 m = re.match(r"(\d+)(?:\.(\d+))?(?:\.(\d+))?", version)
35
36 return {
37 'major': int(m.group(1)),
38 'minor': int(m.group(2)) if m.group(2) else 0,
39 'patch': int(m.group(3)) if m.group(3) else 0,
40 }
41
42
43def _check_arm_gcc_version():
44 """Returns True if the arm-none-eabi-gcc version is not known to cause problems.
45 """
46 if 'output' in ESSENTIAL_BINARIES['arm-none-eabi-gcc']:
47 version_number = ESSENTIAL_BINARIES['arm-none-eabi-gcc']['output'].strip()
48 cli.log.info('Found arm-none-eabi-gcc version %s', version_number)
49
50 return CheckStatus.OK # Right now all known arm versions are ok
51
52
53def _check_avr_gcc_version():
54 """Returns True if the avr-gcc version is not known to cause problems.
55 """
56 rc = CheckStatus.ERROR
57 if 'output' in ESSENTIAL_BINARIES['avr-gcc']:
58 version_number = ESSENTIAL_BINARIES['avr-gcc']['output'].strip()
59
60 cli.log.info('Found avr-gcc version %s', version_number)
61 rc = CheckStatus.OK
62
63 parsed_version = _parse_gcc_version(version_number)
64 if parsed_version['major'] > 8:
65 cli.log.warning('{fg_yellow}We do not recommend avr-gcc newer than 8. Downgrading to 8.x is recommended.')
66 rc = CheckStatus.WARNING
67
68 return rc
69
70
71def _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
77 return CheckStatus.OK
78
79
80def _check_dfu_util_version():
81 if 'output' in ESSENTIAL_BINARIES['dfu-util']:
82 first_line = ESSENTIAL_BINARIES['dfu-util']['output'].split('\n')[0]
83 version_number = first_line.split()[1]
84 cli.log.info('Found dfu-util version %s', version_number)
85
86 return CheckStatus.OK
87
88
89def _check_dfu_programmer_version():
90 if 'output' in ESSENTIAL_BINARIES['dfu-programmer']:
91 first_line = ESSENTIAL_BINARIES['dfu-programmer']['output'].split('\n')[0]
92 version_number = first_line.split()[1]
93 cli.log.info('Found dfu-programmer version %s', version_number)
94
95 return CheckStatus.OK
96
97
98def check_binaries():
99 """Iterates through ESSENTIAL_BINARIES and tests them.
100 """
101 ok = True
102
103 for binary in sorted(ESSENTIAL_BINARIES):
104 if not is_executable(binary):
105 ok = False
106
107 return ok
108
109
110def check_binary_versions():
111 """Check the versions of ESSENTIAL_BINARIES
112 """
113 versions = []
114 for check in (_check_arm_gcc_version, _check_avr_gcc_version, _check_avrdude_version, _check_dfu_util_version, _check_dfu_programmer_version):
115 versions.append(check())
116 return versions
117
118
119def check_submodules():
120 """Iterates through all submodules to make sure they're cloned and up to date.
121 """
122 for submodule in submodules.status().values():
123 if submodule['status'] is None:
124 cli.log.error('Submodule %s has not yet been cloned!', submodule['name'])
125 return CheckStatus.ERROR
126 elif not submodule['status']:
127 cli.log.warning('Submodule %s is not up to date!', submodule['name'])
128 return CheckStatus.WARNING
129
130 return CheckStatus.OK
131
132
133def is_executable(command):
134 """Returns True if command exists and can be executed.
135 """
136 # Make sure the command is in the path.
137 res = shutil.which(command)
138 if res is None:
139 cli.log.error("{fg_red}Can't find %s in your path.", command)
140 return False
141
142 # Make sure the command can be executed
143 version_arg = ESSENTIAL_BINARIES[command].get('version_arg', '--version')
144 check = cli.run([command, version_arg], combined_output=True, stdin=DEVNULL, timeout=5)
145
146 ESSENTIAL_BINARIES[command]['output'] = check.stdout
147
148 if check.returncode in [0, 1]: # Older versions of dfu-programmer exit 1
149 cli.log.debug('Found {fg_cyan}%s', command)
150 return True
151
152 cli.log.error("{fg_red}Can't run `%s %s`", command, version_arg)
153 return False
154
155
156def check_git_repo():
157 """Checks that the .git directory exists inside QMK_HOME.
158
159 This is a decent enough indicator that the qmk_firmware directory is a
160 proper Git repository, rather than a .zip download from GitHub.
161 """
162 dot_git_dir = QMK_FIRMWARE / '.git'
163
164 return CheckStatus.OK if dot_git_dir.is_dir() else CheckStatus.WARNING
diff --git a/lib/python/qmk/cli/doctor/linux.py b/lib/python/qmk/cli/doctor/linux.py
new file mode 100644
index 000000000..c0b77216a
--- /dev/null
+++ b/lib/python/qmk/cli/doctor/linux.py
@@ -0,0 +1,162 @@
1"""OS-specific functions for: Linux
2"""
3import platform
4import shutil
5from pathlib import Path
6
7from milc import cli
8
9from qmk.constants import QMK_FIRMWARE
10from .check import CheckStatus
11
12
13def _udev_rule(vid, pid=None, *args):
14 """ Helper function that return udev rules
15 """
16 rule = ""
17 if pid:
18 rule = 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", ATTRS{idProduct}=="%s", TAG+="uaccess"' % (
19 vid,
20 pid,
21 )
22 else:
23 rule = 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", TAG+="uaccess"' % vid
24 if args:
25 rule = ', '.join([rule, *args])
26 return rule
27
28
29def _deprecated_udev_rule(vid, pid=None):
30 """ Helper function that return udev rules
31
32 Note: these are no longer the recommended rules, this is just used to check for them
33 """
34 if pid:
35 return 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", ATTRS{idProduct}=="%s", MODE:="0666"' % (vid, pid)
36 else:
37 return 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", MODE:="0666"' % vid
38
39
40def check_udev_rules():
41 """Make sure the udev rules look good.
42 """
43 rc = CheckStatus.OK
44 udev_dir = Path("/etc/udev/rules.d/")
45 desired_rules = {
46 'atmel-dfu': {
47 _udev_rule("03eb", "2fef"), # ATmega16U2
48 _udev_rule("03eb", "2ff0"), # ATmega32U2
49 _udev_rule("03eb", "2ff3"), # ATmega16U4
50 _udev_rule("03eb", "2ff4"), # ATmega32U4
51 _udev_rule("03eb", "2ff9"), # AT90USB64
52 _udev_rule("03eb", "2ffa"), # AT90USB162
53 _udev_rule("03eb", "2ffb") # AT90USB128
54 },
55 'kiibohd': {_udev_rule("1c11", "b007")},
56 'stm32': {
57 _udev_rule("1eaf", "0003"), # STM32duino
58 _udev_rule("0483", "df11") # STM32 DFU
59 },
60 'bootloadhid': {_udev_rule("16c0", "05df")},
61 'usbasploader': {_udev_rule("16c0", "05dc")},
62 'massdrop': {_udev_rule("03eb", "6124", 'ENV{ID_MM_DEVICE_IGNORE}="1"')},
63 'caterina': {
64 # Spark Fun Electronics
65 _udev_rule("1b4f", "9203", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Pro Micro 3V3/8MHz
66 _udev_rule("1b4f", "9205", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Pro Micro 5V/16MHz
67 _udev_rule("1b4f", "9207", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # LilyPad 3V3/8MHz (and some Pro Micro clones)
68 # Pololu Electronics
69 _udev_rule("1ffb", "0101", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # A-Star 32U4
70 # Arduino SA
71 _udev_rule("2341", "0036", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Leonardo
72 _udev_rule("2341", "0037", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Micro
73 # Adafruit Industries LLC
74 _udev_rule("239a", "000c", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Feather 32U4
75 _udev_rule("239a", "000d", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # ItsyBitsy 32U4 3V3/8MHz
76 _udev_rule("239a", "000e", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # ItsyBitsy 32U4 5V/16MHz
77 # dog hunter AG
78 _udev_rule("2a03", "0036", 'ENV{ID_MM_DEVICE_IGNORE}="1"'), # Leonardo
79 _udev_rule("2a03", "0037", 'ENV{ID_MM_DEVICE_IGNORE}="1"') # Micro
80 }
81 }
82
83 # These rules are no longer recommended, only use them to check for their presence.
84 deprecated_rules = {
85 'atmel-dfu': {_deprecated_udev_rule("03eb", "2ff4"), _deprecated_udev_rule("03eb", "2ffb"), _deprecated_udev_rule("03eb", "2ff0")},
86 'kiibohd': {_deprecated_udev_rule("1c11")},
87 'stm32': {_deprecated_udev_rule("1eaf", "0003"), _deprecated_udev_rule("0483", "df11")},
88 'bootloadhid': {_deprecated_udev_rule("16c0", "05df")},
89 'caterina': {'ATTRS{idVendor}=="2a03", ENV{ID_MM_DEVICE_IGNORE}="1"', 'ATTRS{idVendor}=="2341", ENV{ID_MM_DEVICE_IGNORE}="1"'},
90 'tmk': {_deprecated_udev_rule("feed")}
91 }
92
93 if udev_dir.exists():
94 udev_rules = [rule_file for rule_file in udev_dir.glob('*.rules')]
95 current_rules = set()
96
97 # Collect all rules from the config files
98 for rule_file in udev_rules:
99 for line in rule_file.read_text(encoding='utf-8').split('\n'):
100 line = line.strip()
101 if not line.startswith("#") and len(line):
102 current_rules.add(line)
103
104 # Check if the desired rules are among the currently present rules
105 for bootloader, rules in desired_rules.items():
106 if not rules.issubset(current_rules):
107 deprecated_rule = deprecated_rules.get(bootloader)
108 if deprecated_rule and deprecated_rule.issubset(current_rules):
109 cli.log.warning("{fg_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)
110 else:
111 # For caterina, check if ModemManager is running
112 if bootloader == "caterina":
113 if check_modem_manager():
114 rc = CheckStatus.WARNING
115 cli.log.warning("{fg_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.")
116 rc = CheckStatus.WARNING
117 cli.log.warning("{fg_yellow}Missing or outdated udev rules for '%s' boards. Run 'sudo cp %s/util/udev/50-qmk.rules /etc/udev/rules.d/'.", bootloader, QMK_FIRMWARE)
118
119 else:
120 cli.log.warning("{fg_yellow}'%s' does not exist. Skipping udev rule checking...", udev_dir)
121
122 return rc
123
124
125def check_systemd():
126 """Check if it's a systemd system
127 """
128 return bool(shutil.which("systemctl"))
129
130
131def check_modem_manager():
132 """Returns True if ModemManager is running.
133
134 """
135 if check_systemd():
136 mm_check = cli.run(["systemctl", "--quiet", "is-active", "ModemManager.service"], timeout=10)
137 if mm_check.returncode == 0:
138 return True
139 else:
140 """(TODO): Add check for non-systemd systems
141 """
142 return False
143
144
145def os_test_linux():
146 """Run the Linux specific tests.
147 """
148 # Don't bother with udev on WSL, for now
149 if 'microsoft' in platform.uname().release.lower():
150 cli.log.info("Detected {fg_cyan}Linux (WSL){fg_reset}.")
151
152 # https://github.com/microsoft/WSL/issues/4197
153 if QMK_FIRMWARE.as_posix().startswith("/mnt"):
154 cli.log.warning("I/O performance on /mnt may be extremely slow.")
155 return CheckStatus.WARNING
156
157 return CheckStatus.OK
158 else:
159 cli.log.info("Detected {fg_cyan}Linux{fg_reset}.")
160 from .linux import check_udev_rules
161
162 return check_udev_rules()
diff --git a/lib/python/qmk/cli/doctor/macos.py b/lib/python/qmk/cli/doctor/macos.py
new file mode 100644
index 000000000..00fb27285
--- /dev/null
+++ b/lib/python/qmk/cli/doctor/macos.py
@@ -0,0 +1,13 @@
1import platform
2
3from milc import cli
4
5from .check import CheckStatus
6
7
8def os_test_macos():
9 """Run the Mac specific tests.
10 """
11 cli.log.info("Detected {fg_cyan}macOS %s{fg_reset}.", platform.mac_ver()[0])
12
13 return CheckStatus.OK
diff --git a/lib/python/qmk/cli/doctor/main.py b/lib/python/qmk/cli/doctor/main.py
new file mode 100755
index 000000000..45b0203b6
--- /dev/null
+++ b/lib/python/qmk/cli/doctor/main.py
@@ -0,0 +1,103 @@
1"""QMK Doctor
2
3Check out the user's QMK environment and make sure it's ready to compile.
4"""
5import platform
6from subprocess import DEVNULL
7
8from milc import cli
9from milc.questions import yesno
10
11from qmk import submodules
12from qmk.constants import QMK_FIRMWARE
13from .check import CheckStatus, check_binaries, check_binary_versions, check_submodules, check_git_repo
14
15
16def os_tests():
17 """Determine our OS and run platform specific tests
18 """
19 platform_id = platform.platform().lower()
20
21 if 'darwin' in platform_id or 'macos' in platform_id:
22 from .macos import os_test_macos
23 return os_test_macos()
24 elif 'linux' in platform_id:
25 from .linux import os_test_linux
26 return os_test_linux()
27 elif 'windows' in platform_id:
28 from .windows import os_test_windows
29 return os_test_windows()
30 else:
31 cli.log.warning('Unsupported OS detected: %s', platform_id)
32 return CheckStatus.WARNING
33
34
35@cli.argument('-y', '--yes', action='store_true', arg_only=True, help='Answer yes to all questions.')
36@cli.argument('-n', '--no', action='store_true', arg_only=True, help='Answer no to all questions.')
37@cli.subcommand('Basic QMK environment checks')
38def doctor(cli):
39 """Basic QMK environment checks.
40
41 This is currently very simple, it just checks that all the expected binaries are on your system.
42
43 TODO(unclaimed):
44 * [ ] Compile a trivial program with each compiler
45 """
46 cli.log.info('QMK Doctor is checking your environment.')
47 cli.log.info('QMK home: {fg_cyan}%s', QMK_FIRMWARE)
48
49 status = os_tests()
50
51 # Make sure our QMK home is a Git repo
52 git_ok = check_git_repo()
53
54 if git_ok == CheckStatus.WARNING:
55 cli.log.warning("QMK home does not appear to be a Git repository! (no .git folder)")
56 status = CheckStatus.WARNING
57
58 # Make sure the basic CLI tools we need are available and can be executed.
59 bin_ok = check_binaries()
60
61 if not bin_ok:
62 if yesno('Would you like to install dependencies?', default=True):
63 cli.run(['util/qmk_install.sh', '-y'], stdin=DEVNULL, capture_output=False)
64 bin_ok = check_binaries()
65
66 if bin_ok:
67 cli.log.info('All dependencies are installed.')
68 else:
69 status = CheckStatus.ERROR
70
71 # Make sure the tools are at the correct version
72 ver_ok = check_binary_versions()
73 if CheckStatus.ERROR in ver_ok:
74 status = CheckStatus.ERROR
75 elif CheckStatus.WARNING in ver_ok and status == CheckStatus.OK:
76 status = CheckStatus.WARNING
77
78 # Check out the QMK submodules
79 sub_ok = check_submodules()
80
81 if sub_ok == CheckStatus.OK:
82 cli.log.info('Submodules are up to date.')
83 else:
84 if yesno('Would you like to clone the submodules?', default=True):
85 submodules.update()
86 sub_ok = check_submodules()
87
88 if sub_ok == CheckStatus.ERROR:
89 status = CheckStatus.ERROR
90 elif sub_ok == CheckStatus.WARNING and status == CheckStatus.OK:
91 status = CheckStatus.WARNING
92
93 # Report a summary of our findings to the user
94 if status == CheckStatus.OK:
95 cli.log.info('{fg_green}QMK is ready to go')
96 return 0
97 elif status == CheckStatus.WARNING:
98 cli.log.info('{fg_yellow}QMK is ready to go, but minor problems were found')
99 return 1
100 else:
101 cli.log.info('{fg_red}Major problems detected, please fix these problems before proceeding.')
102 cli.log.info('{fg_blue}Check out the FAQ (https://docs.qmk.fm/#/faq_build) or join the QMK Discord (https://discord.gg/Uq7gcHh) for help.')
103 return 2
diff --git a/lib/python/qmk/cli/doctor/windows.py b/lib/python/qmk/cli/doctor/windows.py
new file mode 100644
index 000000000..381ab36fd
--- /dev/null
+++ b/lib/python/qmk/cli/doctor/windows.py
@@ -0,0 +1,14 @@
1import platform
2
3from milc import cli
4
5from .check import CheckStatus
6
7
8def os_test_windows():
9 """Run the Windows specific tests.
10 """
11 win32_ver = platform.win32_ver()
12 cli.log.info("Detected {fg_cyan}Windows %s (%s){fg_reset}.", win32_ver[0], win32_ver[1])
13
14 return CheckStatus.OK