Coverage for src/homeassistant_repl/local_session.py: 88%

111 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-17 19:05 +0000

1"""API client mode's exec engine: runs snippets right here in the CLI 

2process, not on a remote Home Assistant session - there's no server to send 

3code to, since API client mode talks to Home Assistant only through its 

4standard API (see api_objtree.py). Deliberately mirrors 

5custom_components/ha_repl_server/session.py's exec model (top-level await, 

6trailing-expression echo) rather than importing it: 

7that module lives in a separate Marketplace-deployed package with its own packaging 

8boundary, and duplicating ~100 lines here is simpler than bridging it. 

9 

10Simpler than session.py in one respect: output goes straight to the real 

11terminal, so there's no print()/help() capturing-and-shipping-back machinery, 

12and rich's Console can auto-detect color/width instead of being told. 

13""" 

14 

15from __future__ import annotations 

16 

17import ast 

18import asyncio 

19import builtins 

20import inspect 

21import itertools 

22import linecache 

23import sys 

24import traceback 

25from dataclasses import dataclass 

26from typing import Any 

27 

28from rich.console import Console 

29from rich.pretty import Pretty 

30from rich.traceback import Traceback 

31 

32from .local_help import make_help, show 

33 

34_cell_counter = itertools.count(1) 

35 

36console = Console() 

37error_console = Console(stderr=True) 

38 

39 

40@dataclass 

41class LocalSession: 

42 """A namespace that persists between `run()` calls until the process exits.""" 

43 

44 globals_: dict[str, Any] 

45 auto_await: bool = True 

46 

47 def __post_init__(self) -> None: 

48 self.globals_.setdefault("__name__", "__ha_repl_api__") 

49 self.globals_.setdefault("__builtins__", builtins) 

50 self.globals_.setdefault("_maybe_await", _maybe_await) 

51 self.globals_.setdefault("unawait", unawait) 

52 self.globals_.setdefault("help", make_help(console)) 

53 self.globals_.setdefault("show", show) 

54 

55 async def run(self, source: str, *, echo: bool = True) -> bool: 

56 """Execute source, printing the trailing expression's value (if any, 

57 and unless `echo` is off) or a traceback directly to the real 

58 terminal. Returns False if it raised.""" 

59 try: 

60 value = await self.evaluate(source, echo=echo) 

61 except asyncio.CancelledError: 

62 # Cancellation of the caller (a timeout) must propagate, not be 

63 # reported as the snippet's own error. 

64 raise 

65 except BaseException as err: # noqa: BLE001 - report everything, incl. SystemExit 

66 _print_error(err) 

67 return False 

68 if value is not None and echo: 

69 # A value that knows how to render itself (the Table show() 

70 # returns) is shown as-is rather than through Pretty's 

71 # repr-style output. 

72 rich_aware = not isinstance(value, type) and ( 

73 hasattr(value, "__rich__") or hasattr(value, "__rich_console__") 

74 ) 

75 console.print(value if rich_aware else Pretty(value)) 

76 return True 

77 

78 async def evaluate(self, source: str, *, echo: bool = True) -> Any: 

79 """Execute source and return the trailing expression's value (None 

80 if there isn't one), letting anything it raises propagate - for a 

81 caller that reports results its own way. `_` is set as run() would.""" 

82 value = await self._execute(source) 

83 if value is not None and echo: 

84 self.globals_["_"] = value 

85 return value 

86 

87 async def _execute(self, source: str) -> Any: 

88 # Not "<ha_repl-N>": rich.traceback refuses to show source for any 

89 # filename starting with "<" (treats it like "<stdin>"), no matter what 

90 # linecache holds. An absolute-looking path sidesteps that - rich joins a 

91 # relative one onto the cwd before the linecache lookup, which would miss. 

92 filename = f"/ha_repl/api_cell_{next(_cell_counter)}" 

93 linecache.cache[filename] = ( 

94 len(source), 

95 None, 

96 # Always newline-terminated: rich's traceback rendering fails 

97 # ("substring not found") on a source with no newline in it at 

98 # all, i.e. any one-line command. 

99 (source if source.endswith("\n") else source + "\n").splitlines( 

100 keepends=True 

101 ), 

102 filename, 

103 ) 

104 tree = ast.parse(source, filename, "exec") 

105 if self.auto_await: 105 ↛ 109line 105 didn't jump to line 109 because the condition on line 105 was always true

106 tree = _AutoAwait().visit(tree) 

107 ast.fix_missing_locations(tree) 

108 

109 last_expr = None 

110 last_stmt = tree.body[-1] if tree.body else None 

111 if isinstance(last_stmt, ast.Expr): 

112 tree.body.pop() 

113 last_expr = ast.Expression(last_stmt.value) 

114 

115 flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT 

116 # dont_inherit=True: compile() otherwise inherits this module's own 

117 # `from __future__ import annotations`, which would make every 

118 # annotation in the user's code a plain string instead of a real value. 

119 if tree.body: 

120 await _run_code( 

121 compile(tree, filename, "exec", flags=flags, dont_inherit=True), 

122 self.globals_, 

123 ) 

124 if last_expr is None: 

125 return None 

126 return await _run_code( 

127 compile(last_expr, filename, "eval", flags=flags, dont_inherit=True), 

128 self.globals_, 

129 ) 

130 

131 

132async def _maybe_await(value: Any) -> Any: 

133 """Finish a coroutine (or other awaitable) the user forgot to `await`; 

134 anything else passes straight through. Used both by the AST rewrite below 

135 (an unawaited call nested inside a larger expression) and _run_code's own 

136 check (a bare reference to one created earlier, e.g. `c = f(); c`).""" 

137 return await value if inspect.isawaitable(value) else value 

138 

139 

140def unawait(value: Any) -> Any: 

141 """Identity function and auto-await escape hatch: `unawait(f())` returns 

142 f()'s bare, un-awaited result (a coroutine, if f is async) - for when 

143 that's genuinely wanted, e.g. batching into `asyncio.gather(*[unawait(f()) 

144 for f in ...])`. Recognised by name in the `_AutoAwait` rewrite below, 

145 which skips its whole argument rather than calling this at runtime; this 

146 plain version only runs if auto-await itself is off (--no-auto-await) or 

147 `unawait` is used somewhere the rewrite doesn't reach. 

148 """ 

149 return value 

150 

151 

152class _AutoAwait(ast.NodeTransformer): 

153 """Rewrites every call not already explicitly awaited to go through 

154 _maybe_await() first, so `obj.async_method()` works whether or not the 

155 user remembered `await` - including nested inside attribute access 

156 (`obj.async_method().attr`), a comprehension, or an argument list. 

157 Leaves nested (synchronous) function/lambda bodies alone: `await` there 

158 is a SyntaxError, and those calls run later, not as part of this 

159 statement anyway. `unawait(expr)` is the escape hatch - its argument is 

160 left completely untouched for when the bare coroutine is wanted. 

161 """ 

162 

163 def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef: 

164 return node 

165 

166 def visit_Lambda(self, node: ast.Lambda) -> ast.Lambda: 

167 return node 

168 

169 def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef: 

170 # A class body runs synchronously, so nothing evaluated in it can be 

171 # awaited: not its own statements, nor its decorators and bases, nor 

172 # the decorators and defaults of its methods. Only what's inside an 

173 # async method's body can be. 

174 for stmt in node.body: 

175 if isinstance(stmt, ast.AsyncFunctionDef): 

176 stmt.body = [self.visit(inner) for inner in stmt.body] 

177 elif isinstance(stmt, ast.ClassDef): 177 ↛ 178line 177 didn't jump to line 178 because the condition on line 177 was never true

178 self.visit(stmt) 

179 return node 

180 

181 def visit_Await(self, node: ast.Await) -> ast.Await: 

182 # Already explicit: don't double-await this call, but still rewrite 

183 # anything nested inside its own arguments. 

184 if isinstance(node.value, ast.Call): 

185 node.value.func = self.visit(node.value.func) 

186 node.value.args = [self.visit(a) for a in node.value.args] 

187 node.value.keywords = [self.visit(k) for k in node.value.keywords] 

188 else: 

189 node.value = self.visit(node.value) 

190 return node 

191 

192 def visit_Call(self, node: ast.Call) -> ast.AST: 

193 if ( 193 ↛ 199line 193 didn't jump to line 199 because the condition on line 193 was never true

194 isinstance(node.func, ast.Name) 

195 and node.func.id == "unawait" 

196 and len(node.args) == 1 

197 and not node.keywords 

198 ): 

199 return node.args[0] 

200 self.generic_visit(node) 

201 wrapped = ast.Call( 

202 func=ast.Name(id="_maybe_await", ctx=ast.Load()), args=[node], keywords=[] 

203 ) 

204 return ast.Await(value=wrapped) 

205 

206 

207async def _run_code(code: Any, globals_: dict[str, Any]) -> Any: 

208 # No separate "bare coroutine" backstop here: when auto_await is on, the 

209 # _AutoAwait rewrite already resolves every call site, and NOT doing so 

210 # unconditionally is exactly what `unawait(...)` asks for - a backstop 

211 # here would silently defeat it for a trailing `unawait(f())`. 

212 result = eval(code, globals_) # nosec B307 - the whole point of a dev shell 

213 if code.co_flags & inspect.CO_COROUTINE: 

214 result = await result 

215 return result 

216 

217 

218def _user_traceback(err: BaseException) -> Any: 

219 # Drop the shell's own leading frames so the traceback starts at user 

220 # code (compiled under /ha_repl/, see _execute) - whichever module of 

221 # ours called in. An error with no user frame at all is left whole. 

222 tb = err.__traceback__ 

223 while tb is not None and not tb.tb_frame.f_code.co_filename.startswith("/ha_repl/"): 

224 tb = tb.tb_next 

225 return tb or err.__traceback__ 

226 

227 

228def format_error(err: BaseException) -> dict[str, str]: 

229 """An error as plain data - the same shape the server reports one in.""" 

230 return { 

231 "type": type(err).__name__, 

232 "message": str(err), 

233 "traceback": "".join( 

234 traceback.format_exception(type(err), err, _user_traceback(err)) 

235 ), 

236 } 

237 

238 

239def _print_error(err: BaseException) -> None: 

240 tb = _user_traceback(err) 

241 if isinstance(err, SyntaxError): 

242 # No frames worth showing for this one - plain is fine. 

243 print( 

244 "".join(traceback.format_exception_only(type(err), err)), 

245 end="", 

246 file=sys.stderr, 

247 ) 

248 return 

249 error_console.print(Traceback.from_exception(type(err), err, tb))