#!/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()