Coverage for src/homeassistant_repl/plugins.py: 96%
73 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-17 19:05 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-17 19:05 +0000
1"""Plugins: plain Python run at the start of a session, as though
2typed at the prompt - one top-level statement at a time, so in live mode
3each goes to whichever side it belongs on (see repl.py's LiveSession).
5Unlike the prompt, nothing is echoed, and a statement that fails is only a
6warning: the rest of the file and the remaining files still run, so a
7session always starts. Both the warnings and anything a file prints go to
8stderr, leaving stdout to what `ha-repl exec` was actually asked for.
10A file can tell where it's running from `MODE` and `SERVER` (see
11bind_context), so one file can serve the live shell, exec and API client mode alike.
12"""
14from __future__ import annotations
16import ast
17import asyncio
18import contextlib
19import sys
20from collections.abc import Awaitable, Callable, Iterable, Sequence
21from pathlib import Path
22from typing import Any
24from .config import display_path
25from .local_session import LocalSession, format_error
27# Runs one statement quietly, handing back its error (in the shape the
28# server reports one) or None.
29Runner = Callable[[str], Awaitable[dict[str, Any] | None]]
32def bind_context(globals_: dict[str, Any], mode: str, server: str | None) -> None:
33 """Bind `MODE` ("live", "exec" or "api") and `SERVER` (the configured server's
34 name, None if connected by URL) in a session's local namespace.
36 Ordinary local variables, not the shell's own like `sql`: being plain
37 data they're copied over with any statement that runs inside Home
38 Assistant, so `if MODE != "api": x = hass...` works on either side.
39 """
40 globals_["MODE"] = mode
41 globals_["SERVER"] = server
44def bind_rebind(
45 globals_: dict[str, Any],
46 files: Sequence[Path],
47 run: Runner,
48 remote: Iterable[str] = (),
49) -> None:
50 """Bind `rebind()` in a session's local namespace, to put back what the
51 shell itself bound there - everything in it as this is called, so call
52 it once those are in place and before any plugin has run. `remote` are
53 the names that live inside Home Assistant and have nothing local to
54 put back (`hass` and `obj` in live mode): a local variable in the way
55 of one is removed. `files` and `run` are as run_plugins() takes them.
56 """
57 remote = tuple(remote)
58 running = False
60 async def rebind(*, plugins: bool = True) -> None:
61 """Put back the shell's own names - `obj`, `hass`, `sql`,
62 `hass_api`, `show`, `help` and the rest - where any has been
63 assigned over, and run the plugins again unless `plugins` is
64 False. Nothing else in the session is touched."""
65 nonlocal running
66 for name in remote:
67 globals_.pop(name, None)
68 globals_.update(originals)
69 if not plugins or running: # a plugin calling this doesn't start them all again
70 return
71 running = True
72 try:
73 await run_plugins(files, run)
74 finally:
75 running = False
77 globals_["rebind"] = rebind
78 originals = dict(globals_)
81def split_statements(source: str) -> list[tuple[int, str]]:
82 """A file's top-level statements, each as (first line, source text)."""
83 lines = source.splitlines()
84 spans: list[list[int]] = []
85 for stmt in ast.parse(source).body:
86 start = min([
87 stmt.lineno,
88 *(d.lineno for d in getattr(stmt, "decorator_list", [])),
89 ])
90 end = stmt.end_lineno or stmt.lineno
91 if spans and start <= spans[-1][1]:
92 # Sharing a line (`a = 1; b = 2`) - can't be cut apart by line.
93 spans[-1][1] = max(spans[-1][1], end)
94 else:
95 spans.append([start, end])
96 return [(start, "\n".join(lines[start - 1 : end])) for start, end in spans]
99async def run_plugins(files: Iterable[Path], run: Runner) -> list[Path]:
100 """Run each file through `run`. Returns the files that were loaded."""
101 loaded: list[Path] = []
102 for path in files:
103 try:
104 # A handful of small files, once, before the prompt appears.
105 statements = split_statements(path.read_text(encoding="utf-8"))
106 except (OSError, SyntaxError, ValueError) as err:
107 line = getattr(err, "lineno", None)
108 _warn(path, line, f"{type(err).__name__}: {getattr(err, 'msg', err)}")
109 continue
110 loaded.append(path)
111 for line, text in statements:
112 error = await run(text)
113 if error:
114 _warn(path, line, _summary(error))
115 return loaded
118def local_runner(session: LocalSession) -> Runner:
119 """A Runner for a session that's entirely local (API client mode)."""
121 async def run(source: str) -> dict[str, Any] | None:
122 try:
123 with contextlib.redirect_stdout(sys.stderr):
124 await session.evaluate(source, echo=False)
125 except asyncio.CancelledError:
126 raise
127 except BaseException as err: # noqa: BLE001 - report everything, incl. SystemExit
128 return format_error(err)
129 return None
131 return run
134def _summary(error: dict[str, Any]) -> str:
135 if error.get("type"): 135 ↛ 137line 135 didn't jump to line 137 because the condition on line 135 was always true
136 return f"{error['type']}: {error.get('message', '')}"
137 lines = str(error.get("traceback", "")).strip().splitlines()
138 return lines[-1] if lines else "failed"
141def _warn(path: Path, line: int | None, message: str) -> None:
142 where = display_path(path) + (f":{line}" if line else "")
143 print(f"ha-repl: plugin: {where}: {message}", file=sys.stderr)