Coverage for src/homeassistant_repl/shellhelp.py: 91%
90 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"""IPython style `?` and `??` in the shells - recognised by the input loop,
2like quit(), and never run as code themselves.
4- `?` on its own: what this shell offers, for the mode it's in
5- `thing?` (or `?thing`): the shell's own help(thing), run where `thing`
6 lives - so `hass?` is answered inside Home Assistant. It never calls
7 anything: a call in `thing` is refused
8- `thing??`: where its source is, with a link to that line on GitHub at
9 the version running - found without running anything, see complete.py.
10 A link rather than the source itself, since what's running in Home
11 Assistant may be any version, and its files aren't here to show
12"""
14from __future__ import annotations
16import ast
17import re
18from collections.abc import Awaitable, Callable
19from typing import Any
21from rich.text import Text
23from .complete import Doc, Source
24from .local_session import console
26_REQUEST = re.compile(r"\s*(?P<before>\?\??)?(?P<expr>[^?\n]*?)\s*(?P<after>\?\??)?\s*")
28_NAMES = {
29 "live": [
30 ("hass", "Home Assistant itself, inside Home Assistant"),
31 ("obj", "the object tree: entities and actions by path - obj?"),
32 ("sql", "the Recorder database, results downloaded here - sql?"),
33 ("hass_api", "the REST API client, here"),
34 ],
35 "api": [
36 ("obj", "the object tree: entities and actions by path - obj?"),
37 ("hass_api", "the REST API client"),
38 ],
39}
41_COMMON = [
42 ("show(thing)", "what's inside an object, an attribute to a line"),
43 ("help(thing)", "what an object is for, and what to call on it"),
44 ("rebind()", "put back any of the names above, and run the plugins again"),
45 ("MODE, SERVER", "the mode, and the server's name"),
46]
48_KEYS = [
49 ("thing?", "help on thing, where it lives"),
50 ("thing??", "where thing's source is, with a GitHub link at the version running"),
51 (
52 "Ctrl-Space",
53 "what the name under the cursor is, or the call it's in, without running it",
54 ),
55 ("Tab", "complete; a menu also opens by itself after `.` and in keys"),
56 ("Enter", "run, once the statement is complete; Alt-Enter runs it now"),
57 ("Up", "bring back a whole earlier statement or block, to edit"),
58 ("Ctrl-C", "stop what's running, or clear what's typed"),
59 ("Ctrl-D", "leave"),
60]
63def help_request(source: str) -> tuple[str, str] | None:
64 """("?", "thing") for `thing?` or `?thing`, ("??", "thing") for
65 `thing??`, ("?", "") for `?` alone - None if `source` isn't one. A `?`
66 is never Python outside a string, so nothing that is gets taken."""
67 if "?" not in source or "\n" in source.strip():
68 return None
69 match = _REQUEST.fullmatch(source)
70 if match is None:
71 return None
72 before, after = match["before"], match["after"]
73 if bool(before) == bool(after):
74 return None
75 return before or after, match["expr"]
78async def answer(
79 request: tuple[str, str],
80 mode: str,
81 run: Callable[[str], Awaitable[Any]],
82 locate: Callable[[str], Awaitable[Source | None]],
83 describe: Callable[[str], Awaitable[Doc | None]],
84) -> None:
85 """Answer a help_request(): `run` runs code where the shell would,
86 `locate` finds a source as `thing??` wants, `describe` what `thing` is
87 without running it."""
88 kind, expr = request
89 if not expr: 89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true
90 console.print(shell_help(mode))
91 return
92 try:
93 node = ast.parse(expr, mode="eval")
94 except SyntaxError:
95 console.print(f"`{expr}` isn't a Python expression", style="red")
96 return
97 if any(isinstance(n, ast.Call) for n in ast.walk(node)):
98 console.print(
99 f"`{expr}{kind}` would call something to get there - "
100 "ask about what's called instead, without the brackets",
101 style="red",
102 )
103 return
104 if kind == "?":
105 found = await describe(expr)
106 if found is not None and found.owner:
107 # An attribute its class declares or documents: help() would
108 # only describe the value's type - `list`, say.
109 console.print(doc_text(found))
110 return
111 await run(f"help({expr})")
112 return
113 where = await locate(expr)
114 if where is None: 114 ↛ 115line 114 didn't jump to line 115 because the condition on line 114 was never true
115 console.print(
116 f"Can't tell where `{expr}` comes from without running it", style="red"
117 )
118 elif not where.file:
119 console.print(f"{where.name} is built in: it has no Python source")
120 else:
121 # Unwrapped, so the link stays one link at any width.
122 console.print(source_text(where), soft_wrap=True)
125def shell_help(mode: str) -> Text:
126 text = Text()
127 title = "Live mode" if mode == "live" else "API mode"
128 text.append(f"{title} - Python, with these to hand:\n\n", style="bold")
129 rows = [*_NAMES.get(mode, []), *_COMMON]
130 width = max(len(name) for name, _ in rows + _KEYS) + 2
131 for name, what in rows:
132 text.append(f" {name:<{width}}", style="cyan")
133 text.append(f"{what}\n")
134 if mode == "live":
135 text.append(
136 "\nA statement using hass, obj, or a variable an earlier one left "
137 "there, runs inside Home Assistant; anything else runs here.\n"
138 )
139 text.append("\n")
140 for name, what in _KEYS:
141 text.append(f" {name:<{width}}", style="cyan")
142 text.append(f"{what}\n")
143 return text
146def source_text(found: Source) -> Text:
147 text = Text()
148 text.append(found.name, style="bold")
149 text.append(f"\n {found.file}:{found.line}\n")
150 if found.url: 150 ↛ 154line 150 didn't jump to line 154 because the condition on line 150 was always true
151 text.append(" ")
152 text.append(found.url, style=f"link {found.url}")
153 text.append("\n")
154 return text
157def doc_text(found: Doc) -> Text:
158 """A description, as Ctrl-Space and `ha-repl inspect` show it."""
159 text = Text()
160 text.append(found.name, style="bold")
161 if found.signature:
162 text.append(found.signature, style="cyan")
163 text.append(f" {found.kind}", style="dim")
164 if found.kind == "instance":
165 text.append(f" of {found.type}", style="dim")
166 elif found.kind == "property" and found.type: 166 ↛ 167line 166 didn't jump to line 167 because the condition on line 166 was never true
167 text.append(f" -> {found.type}", style="dim")
168 if found.owner:
169 text.append(f", attribute of {found.owner}", style="dim")
170 if found.value:
171 text.append(f"\n{found.value}")
172 if found.doc: 172 ↛ 174line 172 didn't jump to line 174 because the condition on line 172 was always true
173 text.append(f"\n{found.doc}")
174 return text