Debian Codegraph @

setup/type_check.py

raw
1 #!/usr/bin/env python
2 # License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
3
4 import glob
5 import os
6 import re
7 import subprocess
8
9 from setup import Command, iswindows
10
11
12 class TypeCheck(Command):
13 description = 'Run the ty type checker over the calibre source code'
14 usage_help = 'To type check specific files, specify them as command line arguments'
15 require_venv = True
16
17 def patch_qt_stubs(self, version: int = 1):
18 def patch(mod: str, changes: dict[str, list[str]]) -> str:
19 core = glob.glob(f'.venv/lib/python*/site-packages/PyQt*/{mod}.pyi')[0]
20 with open(core) as f:
21 raw = f.read()
22 sentinel = f'# calibre-patch-version: {version}'
23 if raw.startswith(sentinel):
24 return
25 raw = sentinel + '\n' + raw
26 prefix = '\n '
27 for cls, lines in changes.items():
28 if cls.startswith('!'):
29 raw = re.sub(cls[1:], lines[0], raw)
30 continue
31 body = prefix.join(lines)
32 raw = re.sub(rf'(class {cls}\(.+)', rf'\1{prefix}{body}', raw)
33 os.unlink(core) # uv uses hard links apparently
34 with open(core, 'w') as f:
35 f.write(raw)
36
37 patch(
38 'QtCore',
39 {
40 # QByteArray supports Buffer protocol
41 'QByteArray': ['def __buffer__(self, flags: int, /) -> memoryview: ...'],
42 # signal.connect() accepts type parameter
43 '!' + re.escape("def connect(self, slot: 'PYQT_SLOT') -> 'QMetaObject.Connection': ..."): [
44 "def connect(self, slot: 'PYQT_SLOT', type: Qt.ConnectionType = ...) -> 'QMetaObject.Connection': ..."
45 ],
46 # QObject::findChild() can return None
47 '!'
48 + re.escape(
49 'def findChild(self, type: type[QObjectT], name: typing.Optional[str] = ..., options: Qt.FindChildOption = ...) -> QObjectT: ...'
50 ): ['def findChild(self, type: type[QObjectT], name: typing.Optional[str] = ..., options: Qt.FindChildOption = ...) -> QObjectT | None: ...'],
51 '!'
52 + re.escape(
53 'def findChild(self, types: tuple[type[QObjectT], ...],'
54 ' name: typing.Optional[str] = ..., options: Qt.FindChildOption = ...) -> QObjectT: ...'
55 ): [
56 (
57 'def findChild('
58 'self, types: tuple[type[QObjectT], ...], name: typing.Optional[str] = ..., options: Qt.FindChildOption = ...) -> QObjectT | None: ...'
59 )
60 ],
61 },
62 )
63 patch(
64 'QtGui',
65 {
66 'QIcon': '''\
67 @classmethod
68 def ic(cls, name: str | QIcon | None, fallback: bytes = b'') -> QIcon: ...
69 @classmethod
70 def icon_as_png(cls, name: str, as_bytearray: bool = False, compression_level: int = 9) -> QIcon: ...
71 @classmethod
72 def cached_icon(cls, name: str) -> QIcon: ...
73 def is_ok(self) -> bool: ...
74 '''.splitlines(),
75 'QPalette': '''\
76 def is_dark_theme(self) -> bool: ...
77 def serialize_as_bytes(self) -> bytes: ...
78 def serialize_as_python(self) -> str: ...
79 def unserialize_from_bytes(self, b: bytes) -> None: ...
80 '''.splitlines(),
81 },
82 )
83 patch(
84 'QtWidgets',
85 {
86 # QLayout.getContentsMargins() never returns None
87 '!'
88 + re.escape(
89 ' def getContentsMargins(self) -> typing.Tuple['
90 'typing.Optional[int], typing.Optional[int], typing.Optional[int], typing.Optional[int]]: ...'
91 ): [' def getContentsMargins(self) -> typing.Tuple[int, int, int, int]: ...'],
92 'QWidget': '''\
93 def save_geometry(self, prefs: Prefs, name: str) -> None: ...
94 def restore_geometry(self, prefs: Prefs, name: str, get_legacy_saved_geometry: typing.Callable[[], bytes] | None = None) -> bool: ...
95 def raise_and_focus(self) -> None: ...
96 def raise_without_focus(self) -> None: ...
97 '''.splitlines(),
98 },
99 )
100
101 def run(self, opts):
102 ty = self.j(self.PROJECT_ROOT, '.venv/bin/ty')
103 if iswindows:
104 ty += '.exe'
105 self.patch_qt_stubs()
106 cp = subprocess.run([ty, 'check'] + list(opts.cli_args), cwd=self.PROJECT_ROOT)
107 if cp.returncode != 0:
108 raise SystemExit(cp.returncode)