cli.py
This file
Path
typer/cli.py
317 lines 路 9.9 KiB 路 Python
Last changed by
馃悰 Fix escaping in help text when `rich` is installed but not used (#1089)Sofie Van Landeghembefore adoptionc0aeb6e
History of this fileTake it
1import importlib.util2import re3import sys4from pathlib import Path5from typing import Any, Optional67import click8import typer9import typer.core10from click import Command, Group, Option1112from . import __version__13from .core import HAS_RICH, MARKUP_MODE_KEY1415default_app_names = ("app", "cli", "main")16default_func_names = ("main", "cli", "app")1718app = typer.Typer()19utils_app = typer.Typer(help="Extra utility commands for Typer apps.")20app.add_typer(utils_app, name="utils")212223class State:24 def __init__(self) -> None:25 self.app: Optional[str] = None26 self.func: Optional[str] = None27 self.file: Optional[Path] = None28 self.module: Optional[str] = None293031state = State()323334def maybe_update_state(ctx: click.Context) -> None:35 path_or_module = ctx.params.get("path_or_module")36 if path_or_module:37 file_path = Path(path_or_module)38 if file_path.exists() and file_path.is_file():39 state.file = file_path40 else:41 if not re.fullmatch(r"[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*", path_or_module):42 typer.echo(43 f"Not a valid file or Python module: {path_or_module}", err=True44 )45 sys.exit(1)46 state.module = path_or_module47 app_name = ctx.params.get("app")48 if app_name:49 state.app = app_name50 func_name = ctx.params.get("func")51 if func_name:52 state.func = func_name535455class TyperCLIGroup(typer.core.TyperGroup):56 def list_commands(self, ctx: click.Context) -> list[str]:57 self.maybe_add_run(ctx)58 return super().list_commands(ctx)5960 def get_command(self, ctx: click.Context, name: str) -> Optional[Command]:61 self.maybe_add_run(ctx)62 return super().get_command(ctx, name)6364 def invoke(self, ctx: click.Context) -> Any:65 self.maybe_add_run(ctx)66 return super().invoke(ctx)6768 def maybe_add_run(self, ctx: click.Context) -> None:69 maybe_update_state(ctx)70 maybe_add_run_to_cli(self)717273def get_typer_from_module(module: Any) -> Optional[typer.Typer]:74 # Try to get defined app75 if state.app:76 obj = getattr(module, state.app, None)77 if not isinstance(obj, typer.Typer):78 typer.echo(f"Not a Typer object: --app {state.app}", err=True)79 sys.exit(1)80 return obj81 # Try to get defined function82 if state.func:83 func_obj = getattr(module, state.func, None)84 if not callable(func_obj):85 typer.echo(f"Not a function: --func {state.func}", err=True)86 sys.exit(1)87 sub_app = typer.Typer()88 sub_app.command()(func_obj)89 return sub_app90 # Iterate and get a default object to use as CLI91 local_names = dir(module)92 local_names_set = set(local_names)93 # Try to get a default Typer app94 for name in default_app_names:95 if name in local_names_set:96 obj = getattr(module, name, None)97 if isinstance(obj, typer.Typer):98 return obj99 # Try to get any Typer app100 for name in local_names_set - set(default_app_names):101 obj = getattr(module, name)102 if isinstance(obj, typer.Typer):103 return obj104 # Try to get a default function105 for func_name in default_func_names:106 func_obj = getattr(module, func_name, None)107 if callable(func_obj):108 sub_app = typer.Typer()109 sub_app.command()(func_obj)110 return sub_app111 # Try to get any func app112 for func_name in local_names_set - set(default_func_names):113 func_obj = getattr(module, func_name)114 if callable(func_obj):115 sub_app = typer.Typer()116 sub_app.command()(func_obj)117 return sub_app118 return None119120121def get_typer_from_state() -> Optional[typer.Typer]:122 spec = None123 if state.file:124 module_name = state.file.name125 spec = importlib.util.spec_from_file_location(module_name, str(state.file))126 elif state.module:127 spec = importlib.util.find_spec(state.module)128 if spec is None:129 if state.file:130 typer.echo(f"Could not import as Python file: {state.file}", err=True)131 else:132 typer.echo(f"Could not import as Python module: {state.module}", err=True)133 sys.exit(1)134 module = importlib.util.module_from_spec(spec)135 spec.loader.exec_module(module) # type: ignore136 obj = get_typer_from_module(module)137 return obj138139140def maybe_add_run_to_cli(cli: click.Group) -> None:141 if "run" not in cli.commands:142 if state.file or state.module:143 obj = get_typer_from_state()144 if obj:145 obj._add_completion = False146 click_obj = typer.main.get_command(obj)147 click_obj.name = "run"148 if not click_obj.help:149 click_obj.help = "Run the provided Typer app."150 cli.add_command(click_obj)151152153def print_version(ctx: click.Context, param: Option, value: bool) -> None:154 if not value or ctx.resilient_parsing:155 return156 typer.echo(f"Typer version: {__version__}")157 raise typer.Exit()158159160@app.callback(cls=TyperCLIGroup, no_args_is_help=True)161def callback(162 ctx: typer.Context,163 *,164 path_or_module: str = typer.Argument(None),165 app: str = typer.Option(None, help="The typer app object/variable to use."),166 func: str = typer.Option(None, help="The function to convert to Typer."),167 version: bool = typer.Option(168 False,169 "--version",170 help="Print version and exit.",171 callback=print_version,172 ),173) -> None:174 """175 Run Typer scripts with completion, without having to create a package.176177 You probably want to install completion for the typer command:178179 $ typer --install-completion180181 https://typer.tiangolo.com/182 """183 maybe_update_state(ctx)184185186def get_docs_for_click(187 *,188 obj: Command,189 ctx: typer.Context,190 indent: int = 0,191 name: str = "",192 call_prefix: str = "",193 title: Optional[str] = None,194) -> str:195 docs = "#" * (1 + indent)196 command_name = name or obj.name197 if call_prefix: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: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"212 docs += "$ "213 if command_name:214 docs += f"{command_name} "215 docs += f"{' '.join(usage_pieces)}\n"216 docs += "```\n\n"217 args = []218 opts = []219 for param in obj.get_params(ctx):220 rv = param.get_help_record(ctx)221 if rv is not None:222 if param.param_type_name == "argument":223 args.append(rv)224 elif param.param_type_name == "option":225 opts.append(rv)226 if args:227 docs += "**Arguments**:\n\n"228 for arg_name, arg_help in args:229 docs += f"* `{arg_name}`"230 if 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: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"244 if isinstance(obj, Group):245 group = obj246 commands = group.list_commands(ctx)247 if commands:248 docs += "**Commands**:\n\n"249 for command in commands:250 command_obj = group.get_command(ctx, command)251 assert command_obj252 docs += f"* `{command_obj.name}`"253 command_help = command_obj.get_short_help_str()254 if 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)260 assert command_obj261 use_prefix = ""262 if command_name:263 use_prefix += f"{command_name}"264 docs += get_docs_for_click(265 obj=command_obj, ctx=ctx, indent=indent + 1, call_prefix=use_prefix266 )267 return docs268269270def _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)276277278@utils_app.command()279def docs(280 ctx: typer.Context,281 name: str = typer.Option("", help="The name of the CLI program to use in docs."),282 output: Optional[Path] = typer.Option(283 None,284 help="An output file to write docs to, like README.md.",285 file_okay=True,286 dir_okay=False,287 ),288 title: Optional[str] = typer.Option(289 None,290 help="The title for the documentation page. If not provided, the name of "291 "the program is used.",292 ),293) -> None:294 """295 Generate Markdown docs for a Typer app.296 """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:310 output.write_text(clean_docs)311 typer.echo(f"Docs saved to: {output}")312 else:313 typer.echo(clean_docs)314315316def main() -> Any:317 return app()