✨ Render Rich markup as HTML in Markdown docs (#847)
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 a6167b3 · Browse files · 6 files·+122 added−7 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>
Diff stats
6 files+122 added−7 removed
- tests:+75 added−0 removed
- other:+47 added−7 removed
Provenance
- Commit
5996fc1- Tree
ce87e5c- Author
Sofie Van Landeghem <svlandeg@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
a6167b3
6 files changed+122 added−7 removed
added:tests/assets/cli/rich_formatted_app.py+22 added
1+import typer2+from typing_extensions import Annotated3+4+app = typer.Typer(rich_markup_mode="rich")5+6+7+@app.command(help="Say [bold red]hello[/bold red] to the user.")8+def hello(9+ user_1: Annotated[10+ str,11+ typer.Argument(help="The [bold]cool[/bold] name of the [green]user[/green]"),12+ ],13+ user_2: Annotated[str, typer.Argument(help="The world")] = "The World",14+ force: Annotated[15+ bool, typer.Option(help="Force the welcome [red]message[/red]")16+ ] = False,17+):18+ print(f"Hello {user_1} and {user_2}") # pragma: no cover19+20+21+if __name__ == "__main__":22+ app()added:tests/assets/cli/richformattedapp-docs.md+21 added
123456789101112131415161718192021# Awesome CLI
Say <span style="color: #800000; text-decoration-color: #800000; font-weight: bold">hello</span> to the user.
**Usage**:
```console$ hello [OPTIONS] USER_1 [USER_2]```
**Arguments**:
* `USER_1`: The <span style="font-weight: bold">cool</span> name of the <span style="color: #008000; text-decoration-color: #008000">user</span> [required]* `[USER_2]`: The world [default: The World]
**Options**:
* `--force / --no-force`: Force the welcome <span style="color: #800000; text-decoration-color: #800000">message</span> [default: no-force]* `--install-completion`: Install completion for the current shell.* `--show-completion`: Show completion for the current shell, to copy it or customize the installation.* `--help`: Show this message and exit.modified:tests/test_cli/test_doc.py+32 added
1+import os2 import subprocess3 import sys4 from pathlib import Path5 134 unmodified lines140 capture_output=True,141 encoding="utf-8",142 )143 assert "Not a valid file or Python module:" in result.stderr144+145+146+def test_doc_html_output(tmp_path: Path):147+ out_file: Path = tmp_path / "out.md"148+ result = subprocess.run(149+ [150+ sys.executable,151+ "-m",152+ "coverage",153+ "run",154+ "-m",155+ "typer",156+ "tests.assets.cli.rich_formatted_app",157+ "utils",158+ "docs",159+ "--title",160+ "Awesome CLI",161+ "--output",162+ str(out_file),163+ ],164+ capture_output=True,165+ encoding="utf-8",166+ env={**os.environ, "PYTHONIOENCODING": "utf-8"},167+ )168+ docs_path: Path = (169+ Path(__file__).parent.parent / "assets" / "cli" / "richformattedapp-docs.md"170+ )171+ docs = docs_path.read_text(encoding="utf-8")172+ written_docs = out_file.read_text(encoding="utf-8")173+ assert docs in written_docs174+ assert "Docs saved to:" in result.stdoutmodified:typer/cli.py+20 added-4 removed
9 unmodified lines10 from click import Command, Group, Option11 12 from . import __version__13 14+try:15+ import rich16+17+ has_rich = True18+ from . import rich_utils19+20+except ImportError: # pragma: no cover21+ has_rich = False22+ rich = None # type: ignore23+24 default_app_names = ("app", "cli", "main")25 default_func_names = ("main", "cli", "app")26 27 app = typer.Typer()180 unmodified lines208 if not title:209 title = f"`{command_name}`" if command_name else "CLI"210 docs += f" {title}\n\n"211 if obj.help:202- docs += f"{obj.help}\n\n"212+ docs += f"{_parse_html(obj.help)}\n\n"213 usage_pieces = obj.collect_usage_pieces(ctx)214 if usage_pieces:215 docs += "**Usage**:\n\n"216 docs += "```console\n"15 unmodified lines232 docs += "**Arguments**:\n\n"233 for arg_name, arg_help in args:234 docs += f"* `{arg_name}`"235 if arg_help:226- docs += f": {arg_help}"236+ docs += f": {_parse_html(arg_help)}"237 docs += "\n"238 docs += "\n"239 if opts:240 docs += "**Options**:\n\n"241 for opt_name, opt_help in opts:242 docs += f"* `{opt_name}`"243 if opt_help:234- docs += f": {opt_help}"244+ docs += f": {_parse_html(opt_help)}"245 docs += "\n"246 docs += "\n"247 if obj.epilog:248 docs += f"{obj.epilog}\n\n"7 unmodified lines256 assert command_obj257 docs += f"* `{command_obj.name}`"258 command_help = command_obj.get_short_help_str()259 if command_help:250- docs += f": {command_help}"260+ docs += f": {_parse_html(command_help)}"261 docs += "\n"262 docs += "\n"263 for command in commands:264 command_obj = group.get_command(ctx, command)6 unmodified lines271 )272 return docs273 274 275+def _parse_html(input_text: str) -> str:276+ if not has_rich: # pragma: no cover277+ return input_text278+ return rich_utils.rich_to_html(input_text)279+280+281 @utils_app.command()282 def docs(283 ctx: typer.Context,284 name: str = typer.Option("", help="The name of the CLI program to use in docs."),31 unmodified linesmodified:typer/core.py+13 added-3 removed
364 unmodified lines365 extra.append(_("default: {default}").format(default=default_string))366 if self.required:367 extra.append(_("required"))368 if extra:369- extra_str = ";".join(extra)370- help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"369+ extra_str = "; ".join(extra)370+ extra_str = f"[{extra_str}]"371+ if rich is not None:372+ # This is needed for when we want to export to HTML373+ extra_str = rich.markup.escape(extra_str).strip()374+375+ help = f"{help} {extra_str}" if help else f"{extra_str}"376 return name, help377 378 def make_metavar(self) -> str:379 # Modified version of click.core.Argument.make_metavar()178 unmodified lines558 extra.append(_("required"))559 560 if extra:561 extra_str = "; ".join(extra)557- help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"562+ extra_str = f"[{extra_str}]"563+ if rich is not None:564+ # This is needed for when we want to export to HTML565+ extra_str = rich.markup.escape(extra_str).strip()566 567+ help = f"{help} {extra_str}" if help else f"{extra_str}"568+569 return ("; " if any_prefix_is_slash else " / ").join(rv), help570 571 572 def _typer_format_options(190 unmodified linesmodified:typer/rich_utils.py+14 added
707 unmodified lines708 def rich_abort_error() -> None:709 """Print richly formatted abort error."""710 console = _get_rich_console(stderr=True)711 console.print(ABORTED_TEXT, style=STYLE_ABORTED)712+713+714+def rich_to_html(input_text: str) -> str:715+ """Print the HTML version of a rich-formatted input string.716+717+ This function does not provide a full HTML page, but can be used to insert718+ HTML-formatted text spans into a markdown file.719+ """720+ console = Console(record=True, highlight=False)721+722+ with console.capture():723+ console.print(input_text, overflow="ignore", crop=False)724+725+ return console.export_html(inline_styles=True, code_format="{code}").strip()