codekingpro/portable-devtools
114k
1import os2 3from typing import Iterator4from contextlib import contextmanager5 6from rich.console import Console, RenderableType7from rich.highlighter import Highlighter8 9from httpie.output.ui.rich_palette import _make_rich_color_theme10 11 12def render_as_string(renderable: RenderableType) -> str:13 """Render any `rich` object in a fake console and14 return a *style-less* version of it as a string."""15 16 with open(os.devnull, 'w') as null_stream:17 fake_console = Console(file=null_stream, record=True, theme=_make_rich_color_theme())18 fake_console.print(renderable)19 return fake_console.export_text()20 21 22@contextmanager23def enable_highlighter(24 console: Console,25 highlighter: Highlighter,26) -> Iterator[Console]:27 """Enable a highlighter temporarily."""28 29 original_highlighter = console.highlighter30 try:31 console.highlighter = highlighter32 yield console33 finally:34 console.highlighter = original_highlighter35 