Skip to content
Myr

🐛 Make sure `rich.markup` is imported when rendering help text (#1290)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Gabriel Arjones · committed by GitHub · parent f99defb · Browse files · 4 files+53 added−14 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Co-authored-by: svlandeg <svlandeg@github.com>

Diff stats

4 files+53 added−14 removed

  • tests:+20 added−0 removed
  • other:+33 added−14 removed

4 files+53 added−14 removed

modified:tests/test_rich_utils.py+20 added
1import sys23import typer4import typer.completion5from typer.testing import CliRunner6
73 unmodified lines
80 result = runner.invoke(app, ["Rick", "--option-2=Morty"])81 assert "Hello Rick" in result.stdout82 assert "First: option_1_default" in result.stdout83 assert "Second: Morty" in result.stdout848586def test_rich_markup_import_regression():87 # Remove rich.markup if it was imported by other tests88 if "rich" in sys.modules:89 rich_module = sys.modules["rich"]90 if hasattr(rich_module, "markup"):91 delattr(rich_module, "markup")9293 app = typer.Typer(rich_markup_mode=None)9495 @app.command()96 def main(bar: str):97 pass # pragma: no cover9899 result = runner.invoke(app, ["--help"])100 assert "Usage" in result.stdout101 assert "BAR" in result.stdout
modified:typer/core.py+6 added-2 removed
370 unmodified lines
371 extra_str = "; ".join(extra)372 extra_str = f"[{extra_str}]"373 if rich is not None:374 # This is needed for when we want to export to HTML375 extra_str = rich.markup.escape(extra_str).strip()375 from . import rich_utils376377 extra_str = rich_utils.escape_before_html_export(extra_str)378379 help = f"{help} {extra_str}" if help else f"{extra_str}"380 return name, help381382 def make_metavar(self, ctx: Union[click.Context, None] = None) -> str:
201 unmodified lines
584 extra_str = "; ".join(extra)585 extra_str = f"[{extra_str}]"586 if rich is not None:587 # This is needed for when we want to export to HTML586 extra_str = rich.markup.escape(extra_str).strip()588 from . import rich_utils589590 extra_str = rich_utils.escape_before_html_export(extra_str)591592 help = f"{help} {extra_str}" if help else f"{extra_str}"593594 return ("; " if any_prefix_is_slash else " / ").join(rv), help595
196 unmodified lines
modified:typer/main.py+3 added-12 removed
73 unmodified lines
74 _original_except_hook(exc_type, exc_value, tb)75 return76 typer_path = os.path.dirname(__file__)77 click_path = os.path.dirname(click.__file__)78 supress_internal_dir_names = [typer_path, click_path]78 internal_dir_names = [typer_path, click_path]79 exc = exc_value80 if rich:81 from rich.traceback import Traceback8281 from . import rich_utils8285 rich_tb = Traceback.from_exception(86 type(exc),87 exc,88 exc.__traceback__,89 show_locals=exception_config.pretty_exceptions_show_locals,90 suppress=supress_internal_dir_names,91 width=rich_utils.MAX_WIDTH,92 )83 rich_tb = rich_utils.get_traceback(exc, exception_config, internal_dir_names)84 console_stderr = rich_utils._get_rich_console(stderr=True)85 console_stderr.print(rich_tb)86 return87 tb_exc = traceback.TracebackException.from_exception(exc)88 stack: List[FrameSummary] = []89 for frame in tb_exc.stack:99 if any(frame.filename.startswith(path) for path in supress_internal_dir_names):90 if any(frame.filename.startswith(path) for path in internal_dir_names):91 if not exception_config.pretty_exceptions_short:92 # Hide the line for internal libraries, Typer and Click93 stack.append(94 traceback.FrameSummary(
1042 unmodified lines
modified:typer/rich_utils.py+24 added
14 unmodified lines
15from rich.console import Console, RenderableType, group16from rich.emoji import Emoji17from rich.highlighter import RegexHighlighter18from rich.markdown import Markdown19from rich.markup import escape20from rich.padding import Padding21from rich.panel import Panel22from rich.table import Table23from rich.text import Text24from rich.theme import Theme25from rich.traceback import Traceback26from typer.models import DeveloperExceptionConfig2728if sys.version_info >= (3, 9):29 from typing import Literal30else:
698 unmodified lines
729 console = _get_rich_console(stderr=True)730 console.print(ABORTED_TEXT, style=STYLE_ABORTED)731732733def escape_before_html_export(input_text: str) -> str:734 """Ensure that the input string can be used for HTML export."""735 return escape(input_text).strip()736737738def rich_to_html(input_text: str) -> str:739 """Print the HTML version of a rich-formatted input string.740741 This function does not provide a full HTML page, but can be used to insert
9 unmodified lines
751def rich_render_text(text: str) -> str:752 """Remove rich tags and render a pure text representation"""753 console = _get_rich_console()754 return "".join(segment.text for segment in console.render(text)).rstrip("\n")755756757def get_traceback(758 exc: BaseException,759 exception_config: DeveloperExceptionConfig,760 internal_dir_names: List[str],761) -> Traceback:762 rich_tb = Traceback.from_exception(763 type(exc),764 exc,765 exc.__traceback__,766 show_locals=exception_config.pretty_exceptions_show_locals,767 suppress=internal_dir_names,768 width=MAX_WIDTH,769 )770 return rich_tb