Skip to content
Myr

cli.py

This file

Path

typer/cli.py

299 lines · 9.2 KiB · Python

Last changed by

✨ Add support for `typer ./someprogram.py utils docs --title` (#782)Sebastián Ramírezbefore adoptionbdaa5c6

History of this file

Take it

1import importlib.util2import re3import sys4from pathlib import Path5from typing import Any, List, Optional67import click8import typer9import typer.core10from click import Command, Group, Option1112from . import __version__1314default_app_names = ("app", "cli", "main")15default_func_names = ("main", "cli", "app")1617app = typer.Typer()18utils_app = typer.Typer(help="Extra utility commands for Typer apps.")19app.add_typer(utils_app, name="utils")202122class State:23    def __init__(self) -> None:24        self.app: Optional[str] = None25        self.func: Optional[str] = None26        self.file: Optional[Path] = None27        self.module: Optional[str] = None282930state = State()313233def maybe_update_state(ctx: click.Context) -> None:34    path_or_module = ctx.params.get("path_or_module")35    if path_or_module:36        file_path = Path(path_or_module)37        if file_path.exists() and file_path.is_file():38            state.file = file_path39        else:40            if not re.fullmatch(r"[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*", path_or_module):41                typer.echo(42                    f"Not a valid file or Python module: {path_or_module}", err=True43                )44                sys.exit(1)45            state.module = path_or_module46    app_name = ctx.params.get("app")47    if app_name:48        state.app = app_name49    func_name = ctx.params.get("func")50    if func_name:51        state.func = func_name525354class TyperCLIGroup(typer.core.TyperGroup):55    def list_commands(self, ctx: click.Context) -> List[str]:56        self.maybe_add_run(ctx)57        return super().list_commands(ctx)5859    def get_command(self, ctx: click.Context, name: str) -> Optional[Command]:60        self.maybe_add_run(ctx)61        return super().get_command(ctx, name)6263    def invoke(self, ctx: click.Context) -> Any:64        self.maybe_add_run(ctx)65        return super().invoke(ctx)6667    def maybe_add_run(self, ctx: click.Context) -> None:68        maybe_update_state(ctx)69        maybe_add_run_to_cli(self)707172def get_typer_from_module(module: Any) -> Optional[typer.Typer]:73    # Try to get defined app74    if state.app:75        obj = getattr(module, state.app, None)76        if not isinstance(obj, typer.Typer):77            typer.echo(f"Not a Typer object: --app {state.app}", err=True)78            sys.exit(1)79        return obj80    # Try to get defined function81    if state.func:82        func_obj = getattr(module, state.func, None)83        if not callable(func_obj):84            typer.echo(f"Not a function: --func {state.func}", err=True)85            sys.exit(1)86        sub_app = typer.Typer()87        sub_app.command()(func_obj)88        return sub_app89    # Iterate and get a default object to use as CLI90    local_names = dir(module)91    local_names_set = set(local_names)92    # Try to get a default Typer app93    for name in default_app_names:94        if name in local_names_set:95            obj = getattr(module, name, None)96            if isinstance(obj, typer.Typer):97                return obj98    # Try to get any Typer app99    for name in local_names_set - set(default_app_names):100        obj = getattr(module, name)101        if isinstance(obj, typer.Typer):102            return obj103    # Try to get a default function104    for func_name in default_func_names:105        func_obj = getattr(module, func_name, None)106        if callable(func_obj):107            sub_app = typer.Typer()108            sub_app.command()(func_obj)109            return sub_app110    # Try to get any func app111    for func_name in local_names_set - set(default_func_names):112        func_obj = getattr(module, func_name)113        if callable(func_obj):114            sub_app = typer.Typer()115            sub_app.command()(func_obj)116            return sub_app117    return None118119120def get_typer_from_state() -> Optional[typer.Typer]:121    spec = None122    if state.file:123        module_name = state.file.name124        spec = importlib.util.spec_from_file_location(module_name, str(state.file))125    elif state.module:126        spec = importlib.util.find_spec(state.module)127    if spec is None:128        if state.file:129            typer.echo(f"Could not import as Python file: {state.file}", err=True)130        else:131            typer.echo(f"Could not import as Python module: {state.module}", err=True)132        sys.exit(1)133    module = importlib.util.module_from_spec(spec)134    spec.loader.exec_module(module)  # type: ignore135    obj = get_typer_from_module(module)136    return obj137138139def maybe_add_run_to_cli(cli: click.Group) -> None:140    if "run" not in cli.commands:141        if state.file or state.module:142            obj = get_typer_from_state()143            if obj:144                obj._add_completion = False145                click_obj = typer.main.get_command(obj)146                click_obj.name = "run"147                if not click_obj.help:148                    click_obj.help = "Run the provided Typer app."149                cli.add_command(click_obj)150151152def print_version(ctx: click.Context, param: Option, value: bool) -> None:153    if not value or ctx.resilient_parsing:154        return155    typer.echo(f"Typer version: {__version__}")156    raise typer.Exit()157158159@app.callback(cls=TyperCLIGroup, no_args_is_help=True)160def callback(161    ctx: typer.Context,162    *,163    path_or_module: str = typer.Argument(None),164    app: str = typer.Option(None, help="The typer app object/variable to use."),165    func: str = typer.Option(None, help="The function to convert to Typer."),166    version: bool = typer.Option(167        False,168        "--version",169        help="Print version and exit.",170        callback=print_version,171    ),172) -> None:173    """174    Run Typer scripts with completion, without having to create a package.175176    You probably want to install completion for the typer command:177178    $ typer --install-completion179180    https://typer.tiangolo.com/181    """182    maybe_update_state(ctx)183184185def get_docs_for_click(186    *,187    obj: Command,188    ctx: typer.Context,189    indent: int = 0,190    name: str = "",191    call_prefix: str = "",192    title: Optional[str] = None,193) -> str:194    docs = "#" * (1 + indent)195    command_name = name or obj.name196    if call_prefix:197        command_name = f"{call_prefix} {command_name}"198    if not title:199        title = f"`{command_name}`" if command_name else "CLI"200    docs += f" {title}\n\n"201    if obj.help:202        docs += f"{obj.help}\n\n"203    usage_pieces = obj.collect_usage_pieces(ctx)204    if usage_pieces:205        docs += "**Usage**:\n\n"206        docs += "```console\n"207        docs += "$ "208        if command_name:209            docs += f"{command_name} "210        docs += f"{' '.join(usage_pieces)}\n"211        docs += "```\n\n"212    args = []213    opts = []214    for param in obj.get_params(ctx):215        rv = param.get_help_record(ctx)216        if rv is not None:217            if param.param_type_name == "argument":218                args.append(rv)219            elif param.param_type_name == "option":220                opts.append(rv)221    if args:222        docs += "**Arguments**:\n\n"223        for arg_name, arg_help in args:224            docs += f"* `{arg_name}`"225            if arg_help:226                docs += f": {arg_help}"227            docs += "\n"228        docs += "\n"229    if opts:230        docs += "**Options**:\n\n"231        for opt_name, opt_help in opts:232            docs += f"* `{opt_name}`"233            if opt_help:234                docs += f": {opt_help}"235            docs += "\n"236        docs += "\n"237    if obj.epilog:238        docs += f"{obj.epilog}\n\n"239    if isinstance(obj, Group):240        group = obj241        commands = group.list_commands(ctx)242        if commands:243            docs += "**Commands**:\n\n"244            for command in commands:245                command_obj = group.get_command(ctx, command)246                assert command_obj247                docs += f"* `{command_obj.name}`"248                command_help = command_obj.get_short_help_str()249                if command_help:250                    docs += f": {command_help}"251                docs += "\n"252            docs += "\n"253        for command in commands:254            command_obj = group.get_command(ctx, command)255            assert command_obj256            use_prefix = ""257            if command_name:258                use_prefix += f"{command_name}"259            docs += get_docs_for_click(260                obj=command_obj, ctx=ctx, indent=indent + 1, call_prefix=use_prefix261            )262    return docs263264265@utils_app.command()266def docs(267    ctx: typer.Context,268    name: str = typer.Option("", help="The name of the CLI program to use in docs."),269    output: Optional[Path] = typer.Option(270        None,271        help="An output file to write docs to, like README.md.",272        file_okay=True,273        dir_okay=False,274    ),275    title: Optional[str] = typer.Option(276        None,277        help="The title for the documentation page. If not provided, the name of "278        "the program is used.",279    ),280) -> None:281    """282    Generate Markdown docs for a Typer app.283    """284    typer_obj = get_typer_from_state()285    if not typer_obj:286        typer.echo("No Typer app found", err=True)287        raise typer.Abort()288    click_obj = typer.main.get_command(typer_obj)289    docs = get_docs_for_click(obj=click_obj, ctx=ctx, name=name, title=title)290    clean_docs = f"{docs.strip()}\n"291    if output:292        output.write_text(clean_docs)293        typer.echo(f"Docs saved to: {output}")294    else:295        typer.echo(clean_docs)296297298def main() -> Any:299    return app()