Coverage for src/homeassistant_repl/render.py: 92%

85 statements  

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

1"""Showing what the server-side session sends back. 

2 

3The server (custom_components/ha_repl_server/session.py) does no rendering 

4of its own - it runs inside Home Assistant, whose bundled rich is whatever 

5its own dependencies settle on. A value arrives as a tree describing its 

6shape and an error as its frames and their source lines; both are turned 

7back into something rich can draw here, where the rich version is ours to 

8choose. 

9""" 

10 

11from __future__ import annotations 

12 

13from dataclasses import dataclass, field 

14from typing import Any 

15 

16from rich.console import RenderResult, group 

17from rich.syntax import Syntax 

18from rich.text import Text 

19from rich.traceback import Frame, PathHighlighter, Stack, Trace, Traceback 

20 

21 

22class _Repr: 

23 """Stands in for an object that only exists inside Home Assistant - all 

24 there is of it here is its repr().""" 

25 

26 __slots__ = ("text",) 

27 

28 def __init__(self, text: str) -> None: 

29 self.text = text 

30 

31 def __repr__(self) -> str: 

32 return self.text 

33 

34 

35class _Struct: 

36 """Stands in for a dataclass, attrs instance or namedtuple: rich lays one 

37 of these out from __rich_repr__ just as it would the real thing.""" 

38 

39 def __init__(self, fields: list[tuple[str, Any]]) -> None: 

40 self._fields = fields 

41 

42 def __rich_repr__(self) -> Any: 

43 yield from self._fields 

44 

45 def __repr__(self) -> str: 

46 fields = ", ".join(f"{name}={value!r}" for name, value in self._fields) 

47 return f"{type(self).__name__}({fields})" 

48 

49 

50_CONTAINERS: dict[str, Any] = {"tuple": tuple, "set": set, "frozenset": frozenset} 

51 

52 

53def decode_value(node: Any) -> Any: 

54 """Rebuild the tree session.py's _encode_value() made of a value: real 

55 containers all the way down, with stand-ins at the leaves for whatever 

56 couldn't come across as itself.""" 

57 if isinstance(node, list): 

58 return [decode_value(item) for item in node] 

59 if not isinstance(node, dict): 

60 return node 

61 tag = node["t"] 

62 if tag == "repr": 

63 return _Repr(node["r"]) 

64 if tag == "dict": 

65 return {decode_value(k): decode_value(v) for k, v in node["v"]} 

66 if tag == "iter": 

67 return iter([decode_value(item) for item in node["v"]]) 

68 if tag == "obj": 

69 # A class of its own, since rich takes the name to show from the type. 

70 cls = type(node["n"], (_Struct,), {}) 

71 return cls([(name, decode_value(value)) for name, value in node["f"]]) 

72 return _CONTAINERS[tag](decode_value(item) for item in node["v"]) 

73 

74 

75@dataclass 

76class _RemoteFrame(Frame): 

77 # The lines around `lineno`, starting at line `first` - sent along with 

78 # the frame, since the file itself is on the Home Assistant host. 

79 source: list[str] = field(default_factory=list) 

80 first: int = 1 

81 

82 

83class _RemoteTraceback(Traceback): 

84 """A rich Traceback whose frames carry their own source, instead of 

85 being read from files on this machine.""" 

86 

87 def __init__(self, trace: Trace, hidden: dict[int, int]) -> None: 

88 super().__init__(trace) 

89 self._hidden = hidden 

90 

91 @group() 

92 def _render_stack(self, stack: Stack) -> RenderResult: 

93 path_highlighter = PathHighlighter() 

94 hidden = self._hidden.get(id(stack), 0) 

95 for index, frame in enumerate(stack.frames): 

96 assert isinstance(frame, _RemoteFrame) 

97 if hidden and index == len(stack.frames) // 2: 97 ↛ 98line 97 didn't jump to line 98 because the condition on line 97 was never true

98 yield Text( 

99 f"\n... {hidden} frames hidden ...", 

100 justify="center", 

101 style="traceback.error", 

102 ) 

103 if index: 103 ↛ 104line 103 didn't jump to line 104 because the condition on line 103 was never true

104 yield "" 

105 yield Text.assemble( 

106 path_highlighter(Text(frame.filename, style="pygments.string")), 

107 (":", "pygments.text"), 

108 (str(frame.lineno), "pygments.number"), 

109 " in ", 

110 (frame.name, "pygments.function"), 

111 style="pygments.text", 

112 ) 

113 if not frame.source: 113 ↛ 114line 113 didn't jump to line 114 because the condition on line 113 was never true

114 continue 

115 syntax = Syntax( 

116 # Without its last newline, or it counts as one more (empty) line. 

117 "".join(frame.source).removesuffix("\n"), 

118 "python", 

119 theme=self.theme, 

120 line_numbers=True, 

121 start_line=frame.first, 

122 highlight_lines={frame.lineno}, 

123 word_wrap=self.word_wrap, 

124 code_width=self.code_width, 

125 indent_guides=self.indent_guides, 

126 dedent=False, 

127 ) 

128 if frame.last_instruction is not None: 128 ↛ 130line 128 didn't jump to line 130 because the condition on line 128 was always true

129 _mark(syntax, frame) 

130 yield "" 

131 yield syntax 

132 

133 

134def _mark(syntax: Syntax, frame: _RemoteFrame) -> None: 

135 """Underline the part of the frame's source that failed, a line at a 

136 time so that indentation isn't underlined.""" 

137 assert frame.last_instruction is not None 

138 (start_line, start_col), (end_line, end_col) = frame.last_instruction 

139 for line in range(start_line, end_line + 1): 

140 index = line - frame.first 

141 if not 0 <= index < len(frame.source): 141 ↛ 142line 141 didn't jump to line 142 because the condition on line 141 was never true

142 continue 

143 text = frame.source[index].rstrip("\n") 

144 left = start_col if line == start_line else len(text) - len(text.lstrip()) 

145 right = end_col if line == end_line else len(text) 

146 # Positions are relative to the text given to Syntax, not `first`. 

147 syntax.stylize_range( 

148 "traceback.error_range", (index + 1, left), (index + 1, right) 

149 ) 

150 

151 

152def remote_traceback(error: dict[str, Any]) -> Traceback | None: 

153 """The traceback for an error the server reported, or None if it sent no 

154 frames for it (a SyntaxError, an exception group, or a server too old to 

155 send any) - its plain "traceback" text is all there is to show then.""" 

156 if not error.get("stacks"): 

157 return None 

158 stacks = [] 

159 hidden = {} 

160 for sent in error["stacks"]: 

161 stack = Stack( 

162 exc_type=sent["type"], 

163 exc_value=sent["message"], 

164 is_cause=sent["is_cause"], 

165 notes=sent["notes"], 

166 frames=[ 

167 _RemoteFrame( 

168 filename=f["file"], 

169 lineno=f["line"], 

170 name=f["name"], 

171 last_instruction=( 

172 ((f["position"][0], f["position"][1]), tuple(f["position"][2:])) 

173 if f["position"] 

174 else None 

175 ), 

176 source=[ 

177 line if line.endswith("\n") else line + "\n" 

178 for line in f["source"] 

179 ], 

180 first=f["first"], 

181 ) 

182 for f in sent["frames"] 

183 ], 

184 ) 

185 hidden[id(stack)] = sent["hidden"] 

186 stacks.append(stack) 

187 return _RemoteTraceback(Trace(stacks=stacks), hidden)