From dedbeab44b9992962f8b2a9b24ea23b06c0fd121 Mon Sep 17 00:00:00 2001 From: Murilo Marinho Date: Mon, 26 Oct 2026 19:31:40 +0000 Subject: [PATCH] Linter: add shutdown_template_status() for programmatic template checks lint_source's messages say what is wrong but not what the template consists of. shutdown_template_status(source, path) returns, per spin call site, whether it is guarded, whether KeyboardInterrupt and ExternalShutdownException are caught explicitly or by a broad handler, whether a non-reraising except Exception/bare handler exists in the enclosing tries, and whether the operative handlers are just pass. Conformant is exactly the two styles the tutorial teaches: except (KeyboardInterrupt, ExternalShutdownException) + except Exception, or the old except KeyboardInterrupt + except Exception (ESE swallowed by the broad handler); no_broad (explicit handlers only) and unguarded or escaping sites are not. 11 status cases added. --- tools/murilos_ros2_linter.py | 91 ++++++++++++++++++++++++++++++- tools/test_murilos_ros2_linter.py | 71 +++++++++++++++++++++++- 2 files changed, 159 insertions(+), 3 deletions(-) diff --git a/tools/murilos_ros2_linter.py b/tools/murilos_ros2_linter.py index e7be8c3..718df6a 100755 --- a/tools/murilos_ros2_linter.py +++ b/tools/murilos_ros2_linter.py @@ -83,6 +83,16 @@ elsewhere (``def run(): rclpy.spin(n)``) is reported as unguarded -- the template calls spin inside main()'s try directly. +Programmatic API (importable, no I/O besides reading the given files): +``lint_source(source, path, ...)`` and ``lint_package(pkg_dir)`` return +(lineno, severity, message) findings; ``shutdown_template_status(source, +path)`` returns per-spin-site dicts (guarded, keyboard/shutdown caught +explicitly or by a broad handler, has_broad_handler, ...) so scripts can +check the shutdown template of a source programmatically instead of +reading findings: conformant is guarded, with both exceptions caught +(explicitly or by the broad handler) and a broad ``except Exception`` +present -- the two styles the tutorial teaches. + Usage:: ./murilos_ros2_linter.py [paths ...] [--strict] [--quiet] @@ -503,6 +513,83 @@ def _ancestors(node, parents): yield cur +def shutdown_template_status(source: str, path: str = ""): + """Per-spin() call site template status, for scripts that need to know + whether a source follows the shutdown template without reading the + findings as text (or running a live Ctrl-C). + + Returns one dict per spin call site (same set of sites the template + checks above report on), each with: + + lineno line of the spin call + parsed False if the module does not parse (reason set) + guarded a try/except with handlers encloses the spin + keyboard 'explicit' | 'broad' | None (escapes to top) + for KeyboardInterrupt + shutdown same for ExternalShutdownException + has_broad_handler an enclosing try also has a non-reraising + ``except Exception``/bare handler (the template's + ``except Exception as e: print(e)``) + handlers_pass every operative handler is just ``pass`` + callback_form spin is a thread/callback target, uninspectable + + A site is template-conformant when ``guarded`` and both ``keyboard`` + and ``shutdown`` are caught and ``has_broad_handler`` holds: exactly + the two styles the tutorial teaches -- + ``except (KeyboardInterrupt, ExternalShutdownException)`` + + ``except Exception``, or the old ``except KeyboardInterrupt`` + + ``except Exception`` (which catches ESE by swallowing). + """ + try: + tree = ast.parse(source, filename=path) + except SyntaxError as err: + return [{"lineno": err.lineno or 1, "parsed": False, + "guarded": False, "keyboard": None, "shutdown": None, + "has_broad_handler": False, "handlers_pass": False, + "callback_form": False, + "reason": f"could not parse: {err.msg}"}] + parents = _parents(tree) + statuses = [] + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + if _is_spin(node): + guarded = any(isinstance(n, ast.Try) and n.handlers + for n in _ancestors(node, parents)) + kinds, handlers = {}, [] + for exc in EXCEPTIONS: + found = (_operative_handler(exc, node, parents) + if guarded else None) + kinds[exc] = found[1] if found else None + if found: + handlers.append(found[0]) + has_broad = any( + (handler.type is None + or "Exception" in ([_name(t) for t in handler.type.elts] + if isinstance(handler.type, ast.Tuple) + else [_name(handler.type)])) + and not _reises(handler) + for anc in _ancestors(node, parents) + if isinstance(anc, ast.Try) + for handler in anc.handlers) + statuses.append({ + "lineno": node.lineno, "parsed": True, "guarded": guarded, + "keyboard": kinds["KeyboardInterrupt"], + "shutdown": kinds["ExternalShutdownException"], + "has_broad_handler": has_broad, + "handlers_pass": bool(handlers) + and all(_just_pass(h) for h in handlers), + "callback_form": False}) + continue + target = _spin_callback(node) + if target is not None: + statuses.append({"lineno": node.lineno, "parsed": True, + "guarded": False, "keyboard": None, + "shutdown": None, "has_broad_handler": False, + "handlers_pass": False, "callback_form": True}) + return statuses + + def iter_python_files(paths): for p in (Path(x) for x in paths): if p.is_file(): @@ -549,8 +636,8 @@ def _console_scripts(setup_py: Path): def lint_package(pkg_dir: Path): """ROS 2 package structure checks (package.xml vs folder, setup.py - console_scripts vs modules, resource marker). Importable so zip-based - flows (e.g. marking) can call it on an extracted tree.""" + console_scripts vs modules, resource marker). Importable so scripts can + call it on an unpacked tree (e.g. extracted from a zip).""" # resolve(): Path('.').name is '', which would report every package as a # folder mismatch when the linter is run from inside the package folder. pkg_dir = Path(pkg_dir).resolve() diff --git a/tools/test_murilos_ros2_linter.py b/tools/test_murilos_ros2_linter.py index 6a641aa..10010da 100644 --- a/tools/test_murilos_ros2_linter.py +++ b/tools/test_murilos_ros2_linter.py @@ -5,7 +5,8 @@ import tempfile from pathlib import Path -from murilos_ros2_linter import ERROR, WARNING, lint_package, lint_source +from murilos_ros2_linter import (ERROR, WARNING, lint_package, lint_source, + shutdown_template_status) TEMPLATE = """ import rclpy @@ -489,6 +490,73 @@ def main(): ] +NO_BROAD = """ +import rclpy +from rclpy.executors import ExternalShutdownException + +def main(): + try: + rclpy.spin(node) + except (KeyboardInterrupt, ExternalShutdownException): + pass +""" + +LOGS_WITH_BROAD = """ +import rclpy +from rclpy.executors import ExternalShutdownException + +def main(): + try: + rclpy.spin(node) + except (KeyboardInterrupt, ExternalShutdownException): + get_logger().info("bye") + except Exception as e: + print(e) +""" + + +def _conformant(statuses): + return bool(statuses) and all( + s["parsed"] and s["guarded"] and s["keyboard"] and s["shutdown"] + and s["has_broad_handler"] for s in statuses) + + +STATUS_CASES = [ + ("template", TEMPLATE, True), + ("old_style", OLD_TUTORIAL, True), + ("bare_except", BARE_EXCEPT, True), + ("handler_logs_no_broad", HANDLER_LOGS, False), + ("handler_logs_with_broad", LOGS_WITH_BROAD, True), + ("no_broad", NO_BROAD, False), + ("no_try", NO_TRY, False), + ("thread_partial_callback", THREAD_PARTIAL, False), + ("thread_target_wrapped_template", THREAD_TARGET_WRAPPED, True), + ("syntax_error", SYNTAX_ERROR, False), +] + + +def run_status_cases(): + failures = 0 + for name, source, expected in STATUS_CASES: + statuses = shutdown_template_status(source, "x_node.py") + got = _conformant(statuses) + ok = got == expected + print(f"status {name:28s}: {'ok' if ok else 'FAIL'} {statuses}") + if not ok: + failures += 1 + st = shutdown_template_status(TEMPLATE, "x_node.py")[0] + if not (st["keyboard"] == "explicit" and st["shutdown"] == "explicit" + and st["handlers_pass"]): + print(f"status template fields : FAIL {st}") + failures += 1 + st = shutdown_template_status(OLD_TUTORIAL, "x_node.py")[0] + if not (st["keyboard"] == "explicit" and st["shutdown"] == "broad" + and st["has_broad_handler"]): + print(f"status old_style fields : FAIL {st}") + failures += 1 + return failures + + def main(): failures = 0 for i, (source, path, suffix, expected) in enumerate(CASES): @@ -504,6 +572,7 @@ def main(): print(f" got: {findings}") failures += run_pkg_cases() failures += run_pkg_dot_case() + failures += run_status_cases() print("FAILED" if failures else "all tests passed") return 1 if failures else 0