1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
|
#!/usr/bin/env python3
"""
GTK signal handler & widget reference validator for fungus-launcher.
Scans Python source files for connect() calls and verifies that:
1. Every self.on_* / self.* callback referenced in connect() exists as a method on the same class.
2. Every self.widget_name used with .connect() or accessed via property is assigned somewhere.
Usage: python3 scripts/check_handlers.py [--files ...]
(If no files given, scans all .py files under the project root.)
Exit code 0 = clean, 1 = issues found.
"""
import ast
import logging
import re
import sys
from pathlib import Path
logging.basicConfig(
format="[%(name)s] %(levelname)s %(message)s",
level=logging.INFO,
stream=sys.stderr,
)
# ---------------------------------------------------------------------------
# AST-based class / method extraction (with inheritance resolution)
# ---------------------------------------------------------------------------
def _get_base_names(node: ast.ClassDef) -> list[str]:
"""Extract simple identifier base class names from a class definition."""
bases: list[str] = []
for base in node.bases:
if isinstance(base, ast.Name):
bases.append(base.id)
elif isinstance(base, ast.Attribute):
# e.g. Gtk.Dialog — grab the final attribute name
bases.append(base.attr)
return bases
def _extract_classes(tree: ast.Module):
"""Yield (class_name, set of method names) for all top-level classes."""
for node in ast.iter_child_nodes(tree):
if isinstance(node, ast.ClassDef):
methods = {
n.name for n in node.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
}
yield node.name, methods
def _collect_inherited_methods(
class_name: str,
all_classes: dict[str, set[str]],
file_classes: dict[str, set[str]],
class_bases: dict[str, list[str]],
visited: set[str] | None = None,
) -> set[str]:
"""Collect methods from *class_name* and every ancestor."""
if visited is None:
visited = set()
if class_name in visited:
return set()
visited.add(class_name)
cls_methods = all_classes.get(class_name) or file_classes.get(class_name)
if cls_methods is None:
return set()
result = set(cls_methods)
for base_name in class_bases.get(class_name, []):
result |= _collect_inherited_methods(base_name, all_classes, file_classes, class_bases, visited)
return result
# ---------------------------------------------------------------------------
# Regex-based connect() extraction (works across modules without gi imported)
# ---------------------------------------------------------------------------
# Matches: self.something.connect("signal", self.method_name [, extra_args])
CONNECT_RE = re.compile(
r"""self\.(\w+)\.connect\s*\(\s*"([^"]+)"\s*,\s*self\.(\w+)""",
)
def _find_connect_calls(source: str, filepath: Path):
"""Return list of (line_no, widget_attr, signal, handler_method)."""
results = []
for lineno, line in enumerate(source.splitlines(), start=1):
stripped = line.strip()
# Skip comments and blank lines
if not stripped or stripped.startswith("#"):
continue
for m in CONNECT_RE.finditer(line):
widget_attr = m.group(1)
signal = m.group(2)
handler_method = m.group(3)
results.append((lineno, widget_attr, signal, handler_method))
return results
# ---------------------------------------------------------------------------
# Widget assignment detection
# ---------------------------------------------------------------------------
WIDGET_ASSIGN_RE = re.compile(r"""self\.(\w+)\s*=\s*(?!.*def\s)(.*)""")
def _find_widget_assignments(source: str):
"""Return set of widget attribute names assigned in the file."""
return {m.group(1) for m in WIDGET_ASSIGN_RE.finditer(source)}
# ---------------------------------------------------------------------------
# Main validation logic
# ---------------------------------------------------------------------------
def validate_file(filepath: Path, all_classes: dict[str, set[str]],
file_widgets: dict[Path, set[str]]) -> list[str]:
"""Validate a single Python source file. Return list of error strings."""
errors = []
try:
source = filepath.read_text(encoding="utf-8", errors="replace")
except Exception as exc:
return [f"{filepath}: cannot read — {exc}"]
connect_calls = _find_connect_calls(source, filepath)
if not connect_calls:
return errors
assigned_widgets = file_widgets.get(filepath, set())
# Build class -> methods map for this file, and collect bases
try:
tree = ast.parse(source, filename=str(filepath))
except SyntaxError as exc:
return [f"{filepath}: syntax error — {exc}"]
file_classes: dict[str, set[str]] = {}
class_bases: dict[str, list[str]] = {}
for node in ast.iter_child_nodes(tree):
if isinstance(node, ast.ClassDef):
methods = {
n.name for n in node.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
}
file_classes[node.name] = methods
class_bases[node.name] = _get_base_names(node)
for lineno, widget_attr, signal, handler_method in connect_calls:
# Check: does the handler method exist on any class in this file,
# including methods inherited from mixins / base classes?
found_handler = False
for cls_name in file_classes:
inherited = _collect_inherited_methods(cls_name, all_classes, file_classes, class_bases)
if handler_method in inherited:
found_handler = True
break
# Also check global functions (e.g. lambda, _validate_text)
global_funcs = {
n.name for n in ast.iter_child_nodes(tree)
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
}
if not found_handler and handler_method not in global_funcs:
errors.append(
f"{filepath}:{lineno}: CONNECT — signal '{signal}' references "
f"handler 'self.{handler_method}' which is not defined as a method "
f"in any class (file scope has methods: {', '.join(sorted(global_funcs))})"
)
# Check: does the widget attribute get assigned somewhere?
if widget_attr and widget_attr not in assigned_widgets:
errors.append(
f"{filepath}:{lineno}: WIDGET — 'self.{widget_attr}' is used in "
f"connect() but never assigned (no 'self.{widget_attr} = ...' found)"
)
return errors
def main():
project_root = Path(__file__).resolve().parent.parent
py_files = sorted(project_root.glob("**/*.py"))
# Phase 1: Extract all classes & methods across the entire codebase
all_classes: dict[str, set[str]] = {}
file_widgets: dict[Path, set[str]] = {}
for fpath in py_files:
try:
source = fpath.read_text(encoding="utf-8", errors="replace")
except Exception:
continue
# Extract classes
try:
tree = ast.parse(source)
except SyntaxError:
continue
for cls_name, methods in _extract_classes(tree):
all_classes.setdefault(cls_name, set()).update(methods)
# Extract widget assignments
file_widgets[fpath] = _find_widget_assignments(source)
# Phase 2: Validate each file
all_errors: list[str] = []
for fpath in py_files:
errors = validate_file(fpath, all_classes, file_widgets)
all_errors.extend(errors)
if all_errors:
logging.error("\n".join(all_errors))
logging.error("--- %d issue(s) found ---", len(all_errors))
sys.exit(1)
else:
logging.info("All connect() handlers and widget references validated successfully.")
sys.exit(0)
if __name__ == "__main__":
main()
|