Skip to content
Myr

🐛 Fix escaping in help text when `rich` is installed but not used (#1089)

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

authored by Sofie Van Landeghem · committed by GitHub · parent 66acaed · Browse files · 5 files+91 added−9 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: Sebastián Ramírez <tiangolo@gmail.com>
  • Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>

Diff stats

5 files+91 added−9 removed

  • tests:+62 added−0 removed
  • other:+29 added−9 removed

5 files+91 added−9 removed

added:tests/assets/cli/multi_app_norich.py+37 added
1import typer23sub_app = typer.Typer()45variable = "Some text"678@sub_app.command()9def hello(name: str = "World", age: int = typer.Option(0, help="The age of the user")):10 """11 Say Hello12 """131415@sub_app.command()16def hi(user: str = typer.Argument("World", help="The name of the user to greet")):17 """18 Say Hi19 """202122@sub_app.command()23def bye():24 """25 Say bye26 """272829app = typer.Typer(help="Demo App", epilog="The end", rich_markup_mode=None)30app.add_typer(sub_app, name="sub")313233@app.command()34def top():35 """36 Top command37 """
modified:tests/test_cli/test_doc.py+24 added
84 unmodified lines
85 assert docs in written_docs86 assert "Docs saved to:" in result.stdout878889def test_doc_no_rich():90 result = subprocess.run(91 [92 sys.executable,93 "-m",94 "coverage",95 "run",96 "-m",97 "typer",98 "tests.assets.cli.multi_app_norich",99 "utils",100 "docs",101 "--name",102 "multiapp",103 ],104 capture_output=True,105 encoding="utf-8",106 )107 docs_path: Path = Path(__file__).parent.parent / "assets/cli/multiapp-docs.md"108 docs = docs_path.read_text()109 assert docs in result.stdout110 assert "**Arguments**" in result.stdout111112113def test_doc_not_existing():114 result = subprocess.run(115 [116 sys.executable,
82 unmodified lines
modified:tests/test_rich_markup_mode.py+1 added
19 unmodified lines
20 result = runner.invoke(app, ["World"])21 assert "Hello World" in result.stdout2223 result = runner.invoke(app, ["--help"])24 assert "ARG [required]" in result.stdout25 assert all(c not in result.stdout for c in rounded)262728def test_rich_markup_mode_rich():
263 unmodified lines
modified:typer/cli.py+16 added-7 removed
8 unmodified lines
9import typer.core10from click import Command, Group, Option1112from . import __version__13from .core import HAS_RICH13from .core import HAS_RICH, MARKUP_MODE_KEY1415default_app_names = ("app", "cli", "main")16default_func_names = ("main", "cli", "app")17
180 unmodified lines
198 command_name = f"{call_prefix} {command_name}"199 if not title:200 title = f"`{command_name}`" if command_name else "CLI"201 docs += f" {title}\n\n"202 rich_markup_mode = None203 if hasattr(ctx, "obj") and isinstance(ctx.obj, dict):204 rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None)205 to_parse: bool = bool(HAS_RICH and (rich_markup_mode == "rich"))206 if obj.help:203 docs += f"{_parse_html(obj.help)}\n\n"207 docs += f"{_parse_html(to_parse, obj.help)}\n\n"208 usage_pieces = obj.collect_usage_pieces(ctx)209 if usage_pieces:210 docs += "**Usage**:\n\n"211 docs += "```console\n"
15 unmodified lines
227 docs += "**Arguments**:\n\n"228 for arg_name, arg_help in args:229 docs += f"* `{arg_name}`"230 if arg_help:227 docs += f": {_parse_html(arg_help)}"231 docs += f": {_parse_html(to_parse, arg_help)}"232 docs += "\n"233 docs += "\n"234 if opts:235 docs += "**Options**:\n\n"236 for opt_name, opt_help in opts:237 docs += f"* `{opt_name}`"238 if opt_help:235 docs += f": {_parse_html(opt_help)}"239 docs += f": {_parse_html(to_parse, opt_help)}"240 docs += "\n"241 docs += "\n"242 if obj.epilog:243 docs += f"{obj.epilog}\n\n"
7 unmodified lines
251 assert command_obj252 docs += f"* `{command_obj.name}`"253 command_help = command_obj.get_short_help_str()254 if command_help:251 docs += f": {_parse_html(command_help)}"255 docs += f": {_parse_html(to_parse, command_help)}"256 docs += "\n"257 docs += "\n"258 for command in commands:259 command_obj = group.get_command(ctx, command)
6 unmodified lines
266 )267 return docs268269266def _parse_html(input_text: str) -> str:267 if not HAS_RICH: # pragma: no cover270def _parse_html(to_parse: bool, input_text: str) -> str:271 if not to_parse:272 return input_text273 from . import rich_utils274275 return rich_utils.rich_to_html(input_text)
21 unmodified lines
297 typer_obj = get_typer_from_state()298 if not typer_obj:299 typer.echo("No Typer app found", err=True)300 raise typer.Abort()301 if hasattr(typer_obj, "rich_markup_mode"):302 if not hasattr(ctx, "obj") or ctx.obj is None:303 ctx.ensure_object(dict)304 if isinstance(ctx.obj, dict):305 ctx.obj[MARKUP_MODE_KEY] = typer_obj.rich_markup_mode306 click_obj = typer.main.get_command(typer_obj)307 docs = get_docs_for_click(obj=click_obj, ctx=ctx, name=name, title=title)308 clean_docs = f"{docs.strip()}\n"309 if output:
8 unmodified lines
modified:typer/core.py+13 added-2 removed
24 unmodified lines
2526from ._typing import Literal2728MarkupMode = Literal["markdown", "rich", None]29MARKUP_MODE_KEY = "TYPER_RICH_MARKUP_MODE"3031HAS_RICH = importlib.util.find_spec("rich") is not None32HAS_SHELLINGHAM = importlib.util.find_spec("shellingham") is not None33
332 unmodified lines
366 extra.append(_("required"))367 if extra:368 extra_str = "; ".join(extra)369 extra_str = f"[{extra_str}]"369 if HAS_RICH:370 rich_markup_mode = None371 if hasattr(ctx, "obj") and isinstance(ctx.obj, dict):372 rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None)373 if HAS_RICH and rich_markup_mode == "rich":374 # This is needed for when we want to export to HTML375 from . import rich_utils376377 extra_str = rich_utils.escape_before_html_export(extra_str)
210 unmodified lines
588589 if extra:590 extra_str = "; ".join(extra)591 extra_str = f"[{extra_str}]"588 if HAS_RICH:592 rich_markup_mode = None593 if hasattr(ctx, "obj") and isinstance(ctx.obj, dict):594 rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None)595 if HAS_RICH and rich_markup_mode == "rich":596 # This is needed for when we want to export to HTML597 from . import rich_utils598599 extra_str = rich_utils.escape_before_html_export(extra_str)
135 unmodified lines
735 )736737 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:738 if not HAS_RICH or self.rich_markup_mode is None:739 if not hasattr(ctx, "obj") or ctx.obj is None:740 ctx.ensure_object(dict)741 if isinstance(ctx.obj, dict):742 ctx.obj[MARKUP_MODE_KEY] = self.rich_markup_mode743 return super().format_help(ctx, formatter)744 from . import rich_utils745746 return rich_utils.rich_format_help(
94 unmodified lines