🐛 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
Provenance
- Commit
c0aeb6e- Tree
dd1c06c- Author
Sofie Van Landeghem <svlandeg@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
66acaed
5 files changed+91 added−9 removed
added:tests/assets/cli/multi_app_norich.py+37 added
1+import typer2+3+sub_app = typer.Typer()4+5+variable = "Some text"6+7+8+@sub_app.command()9+def hello(name: str = "World", age: int = typer.Option(0, help="The age of the user")):10+ """11+ Say Hello12+ """13+14+15+@sub_app.command()16+def hi(user: str = typer.Argument("World", help="The name of the user to greet")):17+ """18+ Say Hi19+ """20+21+22+@sub_app.command()23+def bye():24+ """25+ Say bye26+ """27+28+29+app = typer.Typer(help="Demo App", epilog="The end", rich_markup_mode=None)30+app.add_typer(sub_app, name="sub")31+32+33+@app.command()34+def top():35+ """36+ Top command37+ """modified:tests/test_cli/test_doc.py+24 added
84 unmodified lines85 assert docs in written_docs86 assert "Docs saved to:" in result.stdout87 88 89+def 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.stdout111+112+113 def test_doc_not_existing():114 result = subprocess.run(115 [116 sys.executable,82 unmodified linesmodified:tests/test_rich_markup_mode.py+1 added
19 unmodified lines20 result = runner.invoke(app, ["World"])21 assert "Hello World" in result.stdout22 23 result = runner.invoke(app, ["--help"])24+ assert "ARG [required]" in result.stdout25 assert all(c not in result.stdout for c in rounded)26 27 28 def test_rich_markup_mode_rich():263 unmodified linesmodified:typer/cli.py+16 added-7 removed
8 unmodified lines9 import typer.core10 from click import Command, Group, Option11 12 from . import __version__13-from .core import HAS_RICH13+from .core import HAS_RICH, MARKUP_MODE_KEY14 15 default_app_names = ("app", "cli", "main")16 default_func_names = ("main", "cli", "app")17 180 unmodified lines198 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 lines227 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 lines251 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 lines266 )267 return docs268 269 266-def _parse_html(input_text: str) -> str:267- if not HAS_RICH: # pragma: no cover270+def _parse_html(to_parse: bool, input_text: str) -> str:271+ if not to_parse:272 return input_text273 from . import rich_utils274 275 return rich_utils.rich_to_html(input_text)21 unmodified lines297 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 linesmodified:typer/core.py+13 added-2 removed
24 unmodified lines25 26 from ._typing import Literal27 28 MarkupMode = Literal["markdown", "rich", None]29+MARKUP_MODE_KEY = "TYPER_RICH_MARKUP_MODE"30 31 HAS_RICH = importlib.util.find_spec("rich") is not None32 HAS_SHELLINGHAM = importlib.util.find_spec("shellingham") is not None33 332 unmodified lines366 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_utils376 377 extra_str = rich_utils.escape_before_html_export(extra_str)210 unmodified lines588 589 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_utils598 599 extra_str = rich_utils.escape_before_html_export(extra_str)135 unmodified lines735 )736 737 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_utils745 746 return rich_utils.rich_format_help(94 unmodified lines