Coverage for src/homeassistant_repl/cli.py: 58%
187 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"""ha-repl - run Python against a live Home Assistant.
3 ha-repl interactive API client shell (default)
4 `obj` only, read-only, no Marketplace component needed
5 ha-repl live interactive custom-component shell
6 local Python with `sql` + `hass_api`; anything
7 using `hass`/`obj` runs inside Home Assistant;
8 needs the ha_repl_server component
9 ha-repl exec 'hass.states.get("sun.sun")' run a snippet the way the live shell would
10 ha-repl exec 'sql("select ...").show()' (local Python + sql, hass/obj inside HA)
11 ha-repl --json exec 'sql("select ...")' result as JSON: {stdout, value, error, ...};
12 a sql result's value is {columns, rows, ...}
13 ha-repl exec -f snippet.py run a file
14 ha-repl exec - <<'EOF' ... EOF read the snippet from stdin
15 ha-repl reset / ha-repl sessions manage live-mode server-side sessions
16 ha-repl --server house live connect to a server named in config.toml
17 ha-repl servers list the servers configured
18 ha-repl trust allow this repo's .ha-repl directory
20Connection: HASS_SERVER (default http://homeassistant.local:8123), HASS_TOKEN, HASS_SESSION.
21Both HASS_SERVER/HASS_TOKEN also fall back to a `.env` file in the current directory, below real env vars.
22Configuration: ~/.config/ha-repl/config.toml names servers, so --server/HASS_SERVER can be a name
23as well as a URL, and `default` picks one when neither is given. Python files in
24~/.config/ha-repl/plugins/ run at the start of every session, exec included (--no-plugins skips them).
25A repo's own .ha-repl/ directory is layered over both, once allowed with `ha-repl trust`.
26API client mode: --ttl seconds before the cached snapshot is refreshed (default 30).
27Exit status of exec is 1 when the snippet raised, 2 on connection/usage errors.
28"""
30from __future__ import annotations
32import argparse
33import asyncio
34import json
35import os
36import shutil
37import sys
38import time
39from typing import Any
41from rich.pretty import Pretty
43from .client import Client, HaReplError
44from .config import (
45 REPO_DIR,
46 Config,
47 Connection,
48 display_path,
49 find_repo_dir,
50 load_config,
51 resolve_connection,
52 trust,
53)
54from .local_session import console, error_console
55from .render import decode_value, remote_traceback
58def main() -> None:
59 args = _parser().parse_args()
60 try:
61 sys.exit(_run(args))
62 except HaReplError as err:
63 print(f"ha-repl: {err}", file=sys.stderr)
64 sys.exit(2)
65 except KeyboardInterrupt:
66 sys.exit(130)
69def _parser() -> argparse.ArgumentParser:
70 parser = argparse.ArgumentParser(
71 prog="ha-repl",
72 description=__doc__,
73 formatter_class=argparse.RawDescriptionHelpFormatter,
74 )
75 parser.add_argument(
76 "--server",
77 default=None,
78 help="a server named in config.toml, or a URL; defaults to $HASS_SERVER, "
79 "then config.toml's `default`",
80 )
81 parser.add_argument(
82 "--token",
83 default=None,
84 help="defaults to the named server's own token, or $HASS_TOKEN for a URL",
85 )
86 parser.add_argument(
87 "-s",
88 "--session",
89 default=None,
90 help="defaults to $HASS_SESSION, then config.toml's `session`, then 'default'",
91 )
92 parser.add_argument("--json", action="store_true", help="print raw JSON results")
93 parser.add_argument(
94 "--ttl",
95 type=float,
96 default=None,
97 help="API client mode: seconds before the cached snapshot is refreshed (default: 30)",
98 )
99 parser.add_argument(
100 "--auto-await",
101 action=argparse.BooleanOptionalAction,
102 default=None,
103 help="--no-auto-await: don't automatically await a call you forgot to "
104 "`await` - report it as an unawaited coroutine instead, as plain Python would",
105 )
106 parser.add_argument(
107 "--no-plugins", action="store_true", help="don't run the plugins"
108 )
109 sub = parser.add_subparsers(dest="command")
111 exec_ = sub.add_parser(
112 "exec", help="run code and print output and result (live mode only)"
113 )
114 exec_.add_argument("code", nargs="?", help="code to run, or - for stdin")
115 exec_.add_argument("-f", "--file", help="run the contents of a file")
116 exec_.add_argument("-t", "--timeout", type=float, help="cancel after N seconds")
117 exec_.add_argument(
118 "--reset", action="store_true", help="reset the session before running"
119 )
121 inspect_ = sub.add_parser(
122 "inspect",
123 help="what an expression names - its type, signature and docstring - found "
124 "without running it, and decided where as exec would (live mode only)",
125 )
126 inspect_.add_argument(
127 "expression", help="a name or attribute chain, e.g. hass.states"
128 )
129 inspect_.add_argument(
130 "--source",
131 action="store_true",
132 help="also where its source is, with a GitHub link at the version running",
133 )
135 sub.add_parser(
136 "api",
137 help="interactive API client shell (the default): obj only, no Marketplace component needed",
138 )
139 sub.add_parser(
140 "live",
141 help="interactive custom-component shell: local Python + sql, with hass + obj "
142 "run inside Home Assistant; needs the ha_repl_server component",
143 )
144 sub.add_parser("reset", help="discard the live-mode session's variables")
145 sub.add_parser("sessions", help="list live-mode sessions on the server")
146 sub.add_parser("servers", help="list the servers named in config.toml")
147 sub.add_parser(
148 "trust", help=f"allow this repo's {REPO_DIR} directory, as it stands now"
149 )
150 return parser
153def _run(args: argparse.Namespace) -> int:
154 if args.command == "trust":
155 return _trust()
156 config = load_config()
157 for warning in config.warnings: 157 ↛ 158line 157 didn't jump to line 158 because the loop on line 157 never started
158 print(f"ha-repl: {warning}", file=sys.stderr)
159 if args.command == "servers": 159 ↛ 164line 159 didn't jump to line 164 because the condition on line 159 was always true
160 return _servers(args, config)
162 # Each setting: the flag, then (for the session) the environment, then
163 # config.toml, then the built-in default.
164 if args.session is None:
165 args.session = os.environ.get("HASS_SESSION") or config.session or "default"
166 if args.ttl is None:
167 args.ttl = 30.0 if config.ttl is None else float(config.ttl)
168 if args.auto_await is None:
169 args.auto_await = config.auto_await is not False
170 args.plugins = [] if args.no_plugins else config.plugins
171 connection = resolve_connection(args.server, args.token, config)
172 args.server_name = connection.name
173 return asyncio.run(_dispatch(args, connection))
176def _trust() -> int:
177 directory = find_repo_dir()
178 if directory is None:
179 raise HaReplError(f"no {REPO_DIR} directory here, or above in this repo")
180 files = trust(directory)
181 print(f"trusted {display_path(directory)}")
182 for path in files:
183 print(f" {path.relative_to(directory).as_posix()}")
184 return 0
187def _servers(args: argparse.Namespace, config: Config) -> int:
188 """List the configured servers - where each token comes from, never the token."""
189 servers = list(config.servers.values())
190 if not servers: 190 ↛ 191line 190 didn't jump to line 191 because the condition on line 190 was never true
191 text = "no servers configured"
192 else:
193 width = max(len(server.name) for server in servers)
194 text = "\n".join(
195 f"{'*' if server.name == config.default else ' '} "
196 f"{server.name:<{width}} {server.url}"
197 f" ({server.token_source or 'no token'})"
198 for server in servers
199 )
200 listing = [
201 {
202 "name": server.name,
203 "url": server.url,
204 "token_source": server.token_source,
205 "default": server.name == config.default,
206 }
207 for server in servers
208 ]
209 _emit(args, {"default": config.default, "servers": listing}, text)
210 return 0
213async def _dispatch(args: argparse.Namespace, connection: Connection) -> int:
214 async with Client(connection.url, connection.token) as client:
215 match args.command:
216 case "exec":
217 return await _exec(client, args)
218 case "inspect":
219 return await _inspect(client, args)
220 case "reset":
221 result = await client.call("ha_repl_server/reset", session=args.session)
222 _emit(args, result, "reset" if result["reset"] else "no such session")
223 return 0
224 case "sessions":
225 result = await client.call("ha_repl_server/sessions")
226 _emit(args, result, _format_sessions(result["sessions"]))
227 return 0
228 case "live":
229 from .repl import run_repl
231 return await run_repl(
232 client,
233 args.session,
234 auto_await=args.auto_await,
235 server_name=connection.name,
236 plugins=args.plugins,
237 )
238 case _: # "api", or no subcommand at all - API client mode is the default
239 from .apirepl import run_api_repl
241 return await run_api_repl(
242 client,
243 args.ttl,
244 auto_await=args.auto_await,
245 server_name=connection.name,
246 plugins=args.plugins,
247 )
250async def _exec(client: Client, args: argparse.Namespace) -> int:
251 if args.file:
252 # One-shot CLI read, not a hot path - a threaded read would be overkill.
253 with open(args.file, encoding="utf-8") as fp: # noqa: ASYNC230
254 code = fp.read()
255 elif args.code in (None, "-"):
256 if args.code is None and sys.stdin.isatty():
257 raise HaReplError("exec needs code, -f FILE, or - to read stdin")
258 code = sys.stdin.read()
259 else:
260 code = args.code
261 if args.reset:
262 await client.call("ha_repl_server/reset", session=args.session)
264 from .repl import Captured
266 capture = Captured() if args.json else None
267 live = await _exec_session(client, args, capture=capture, timeout=args.timeout)
268 start = time.perf_counter()
269 try:
270 ok = await asyncio.wait_for(live.run(code), args.timeout)
271 except TimeoutError:
272 ok = False
273 message = f"timed out after {args.timeout:g}s"
274 if capture is None:
275 print(f"ha-repl: {message}", file=sys.stderr)
276 else:
277 capture.error = {
278 "type": "TimeoutError",
279 "message": message,
280 "traceback": f"TimeoutError: {message}\n",
281 }
282 if capture is not None:
283 print(
284 json.dumps(
285 {
286 "stdout": capture.stdout,
287 "value": capture.value,
288 "error": capture.error,
289 "duration": time.perf_counter() - start,
290 "truncated": capture.truncated,
291 },
292 indent=2,
293 )
294 )
295 return 0 if ok else 1
298async def _exec_session(
299 client: Client,
300 args: argparse.Namespace,
301 *,
302 capture: Any = None,
303 timeout: float | None = None,
304) -> Any:
305 """The same local-plus-server session the interactive shell uses, so a
306 snippet means the same thing here: `sql` and plain Python run in this
307 process, statements using `hass`/`obj` inside Home Assistant - with the
308 same names, plugins included."""
309 from .plugins import bind_context, run_plugins
310 from .repl import bind_live_rebind, connect_live
312 live = await connect_live(
313 client,
314 args.session,
315 auto_await=args.auto_await,
316 capture=capture,
317 timeout=timeout,
318 )
319 bind_context(live.local.globals_, "exec", args.server_name)
320 bind_live_rebind(live, args.plugins)
321 await run_plugins(args.plugins, live.run_quiet)
322 return live
325async def _inspect(client: Client, args: argparse.Namespace) -> int:
326 """`ha-repl inspect`: Ctrl-Space's description, for an agent - and with
327 --source, `thing??`'s location. Nothing in the expression is run."""
328 from .completer import HaCompleter
329 from .shellhelp import doc_text, source_text
331 live = await _exec_session(client, args)
332 try:
333 info = await client.call("ha_repl_server/info")
334 except HaReplError:
335 info = {}
336 completer = HaCompleter(live.local.globals_, live)
337 completer.remote = "complete" in info.get("commands", ())
338 found = await completer.describe(args.expression)
339 where = (
340 await completer.locate(args.expression) if args.source or args.json else None
341 )
342 if args.json:
343 print(
344 json.dumps(
345 {
346 "doc": found.as_dict() if found else None,
347 "source": where.as_dict() if where else None,
348 },
349 indent=2,
350 )
351 )
352 elif found is None:
353 print(
354 f"ha-repl: can't tell what `{args.expression}` is without running it",
355 file=sys.stderr,
356 )
357 else:
358 console.print(doc_text(found))
359 if where is not None and where.file: 359 ↛ 361line 359 didn't jump to line 361 because the condition on line 359 was always true
360 console.print(source_text(where), soft_wrap=True)
361 return 0 if found else 1
364def display_options() -> dict[str, Any]:
365 """Color/width hints for what the server does still lay out itself:
366 help() output, and the plain-text form of a value.
368 Decided here, not there: the server only sees a websocket, not a terminal,
369 and stdout here might be piped (a script, a redirected log) rather than a
370 person watching it live.
371 """
372 color = sys.stdout.isatty() and not os.environ.get("NO_COLOR")
373 width = shutil.get_terminal_size((88, 24)).columns
374 return {"color": color, "width": width}
377def print_result(result: dict[str, Any]) -> None:
378 if result["stdout"]: 378 ↛ 379line 378 didn't jump to line 379 because the condition on line 378 was never true
379 sys.stdout.write(result["stdout"])
380 if not result["stdout"].endswith("\n"):
381 sys.stdout.write("\n")
382 if result["value"] is not None:
383 tree = result.get("value_tree")
384 if tree is None:
385 # Too big to have been sent as a tree, or an older server.
386 print(result["value"])
387 else:
388 console.print(Pretty(decode_value(tree)))
389 if result["error"]:
390 traceback = remote_traceback(result["error"])
391 if traceback is None:
392 sys.stderr.write(result["error"]["traceback"])
393 else:
394 error_console.print(traceback)
395 if result.get("truncated"): 395 ↛ 396line 395 didn't jump to line 396 because the condition on line 395 was never true
396 print("[ha-repl: output truncated]", file=sys.stderr)
397 sys.stdout.flush()
400def _emit(args: argparse.Namespace, result: Any, text: str) -> None:
401 print(json.dumps(result, indent=2) if args.json else text)
404def _format_sessions(sessions: list[dict[str, Any]]) -> str:
405 if not sessions:
406 return "no sessions"
407 return "\n".join(
408 f"{s['name']}: {s['executions']} runs, vars: {', '.join(s['variables'])}"
409 for s in sessions
410 )