Skip to content
Myr

✨ 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

6 files+122 added−7 removed

added:tests/assets/cli/rich_formatted_app.py+22 added
1import typer2from typing_extensions import Annotated34app = typer.Typer(rich_markup_mode="rich")567@app.command(help="Say [bold red]hello[/bold red] to the user.")8def 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 cover192021if __name__ == "__main__":22 app()
added:tests/assets/cli/richformattedapp-docs.md+21 added
modified:tests/test_cli/test_doc.py+32 added
1import os2import subprocess3import sys4from pathlib import Path5
134 unmodified lines
140 capture_output=True,141 encoding="utf-8",142 )143 assert "Not a valid file or Python module:" in result.stderr144145146def 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.stdout
modified:typer/cli.py+20 added-4 removed
9 unmodified lines
10from click import Command, Group, Option1112from . import __version__1314try:15 import rich1617 has_rich = True18 from . import rich_utils1920except ImportError: # pragma: no cover21 has_rich = False22 rich = None # type: ignore2324default_app_names = ("app", "cli", "main")25default_func_names = ("main", "cli", "app")2627app = typer.Typer()
180 unmodified lines
208 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 lines
232 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 lines
256 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 lines
271 )272 return docs273274275def _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)279280281@utils_app.command()282def docs(283 ctx: typer.Context,284 name: str = typer.Option("", help="The name of the CLI program to use in docs."),
31 unmodified lines
modified:typer/core.py+13 added-3 removed
364 unmodified lines
365 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()374375 help = f"{help} {extra_str}" if help else f"{extra_str}"376 return name, help377378 def make_metavar(self) -> str:379 # Modified version of click.core.Argument.make_metavar()
178 unmodified lines
558 extra.append(_("required"))559560 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()566567 help = f"{help} {extra_str}" if help else f"{extra_str}"568569 return ("; " if any_prefix_is_slash else " / ").join(rv), help570571572def _typer_format_options(
190 unmodified lines
modified:typer/rich_utils.py+14 added
707 unmodified lines
708def 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)712713714def rich_to_html(input_text: str) -> str:715 """Print the HTML version of a rich-formatted input string.716717 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)721722 with console.capture():723 console.print(input_text, overflow="ignore", crop=False)724725 return console.export_html(inline_styles=True, code_format="{code}").strip()