🐛 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
Provenance
- Commit
263e427- Tree
2253467- Author
Gabriel Arjones <arjones@arjones.com>- Committer
GitHub <noreply@github.com>- Parent
f99defb
4 files changed+53 added−14 removed
modified:tests/test_rich_utils.py+20 added
1+import sys2+3 import typer4 import typer.completion5 from typer.testing import CliRunner6 73 unmodified lines80 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.stdout84+85+86+def 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")92+93+ app = typer.Typer(rich_markup_mode=None)94+95+ @app.command()96+ def main(bar: str):97+ pass # pragma: no cover98+99+ result = runner.invoke(app, ["--help"])100+ assert "Usage" in result.stdout101+ assert "BAR" in result.stdoutmodified:typer/core.py+6 added-2 removed
370 unmodified lines371 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_utils376 377+ extra_str = rich_utils.escape_before_html_export(extra_str)378+379 help = f"{help} {extra_str}" if help else f"{extra_str}"380 return name, help381 382 def make_metavar(self, ctx: Union[click.Context, None] = None) -> str:201 unmodified lines584 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_utils589 590+ extra_str = rich_utils.escape_before_html_export(extra_str)591+592 help = f"{help} {extra_str}" if help else f"{extra_str}"593 594 return ("; " if any_prefix_is_slash else " / ").join(rv), help595 196 unmodified linesmodified:typer/main.py+3 added-12 removed
73 unmodified lines74 _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 Traceback82-81 from . import rich_utils82 85- 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 linesmodified:typer/rich_utils.py+24 added
14 unmodified lines15 from rich.console import Console, RenderableType, group16 from rich.emoji import Emoji17 from rich.highlighter import RegexHighlighter18 from rich.markdown import Markdown19+from rich.markup import escape20 from rich.padding import Padding21 from rich.panel import Panel22 from rich.table import Table23 from rich.text import Text24 from rich.theme import Theme25+from rich.traceback import Traceback26+from typer.models import DeveloperExceptionConfig27 28 if sys.version_info >= (3, 9):29 from typing import Literal30 else:698 unmodified lines729 console = _get_rich_console(stderr=True)730 console.print(ABORTED_TEXT, style=STYLE_ABORTED)731 732 733+def 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()736+737+738 def rich_to_html(input_text: str) -> str:739 """Print the HTML version of a rich-formatted input string.740 741 This function does not provide a full HTML page, but can be used to insert9 unmodified lines751 def 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")755+756+757+def 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