diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-06-28 11:08:57 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-06-28 11:08:57 +0300 |
| commit | af86bc399660126b5a33c88eb96d115107d842b4 (patch) | |
| tree | 26bc4f641184a18941a997201f53e0b51a8cc628 /scripts | |
| parent | cf0bde330895d47247fd1102506608e086f42536 (diff) | |
| download | fungus-launcher-af86bc399660126b5a33c88eb96d115107d842b4.tar.gz fungus-launcher-af86bc399660126b5a33c88eb96d115107d842b4.tar.xz | |
add basic ruff lint job
Diffstat (limited to 'scripts')
| -rw-r--r-- | scripts/check_handlers.py | 174 |
1 files changed, 174 insertions, 0 deletions
diff --git a/scripts/check_handlers.py b/scripts/check_handlers.py new file mode 100644 index 0000000..f5056e8 --- /dev/null +++ b/scripts/check_handlers.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +""" +GTK signal handler & widget reference validator for faugus-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 re +import sys +from pathlib import Path + + +# --------------------------------------------------------------------------- +# AST-based class / method extraction +# --------------------------------------------------------------------------- + +def _extract_classes(tree: ast.Module): + """Yield (class_name, list 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 + + +# --------------------------------------------------------------------------- +# 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 + try: + tree = ast.parse(source, filename=str(filepath)) + except SyntaxError as exc: + return [f"{filepath}: syntax error — {exc}"] + + file_classes = {} # class_name -> set of method names + for cls_name, methods in _extract_classes(tree): + file_classes[cls_name] = methods + + for lineno, widget_attr, signal, handler_method in connect_calls: + # Check: does the handler method exist on any class in this file? + found_handler = False + for cls_methods in file_classes.values(): + if handler_method in cls_methods: + 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: + print("\n".join(all_errors)) + print(f"\n--- {len(all_errors)} issue(s) found ---") + sys.exit(1) + else: + print("All connect() handlers and widget references validated successfully.") + sys.exit(0) + + +if __name__ == "__main__": + main() |
