| 1 |
"""Example from https://click.palletsprojects.com/en/stable/advanced/#command-aliases""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from typing_extensions import assert_type |
| 6 |
|
| 7 |
import asyncclick as click |
| 8 |
|
| 9 |
|
| 10 |
class AliasedGroup(click.Group): |
| 11 |
def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None: |
| 12 |
rv = click.Group.get_command(self, ctx, cmd_name) |
| 13 |
if rv is not None: |
| 14 |
return rv |
| 15 |
matches = [x for x in self.list_commands(ctx) if x.startswith(cmd_name)] |
| 16 |
if not matches: |
| 17 |
return None |
| 18 |
elif len(matches) == 1: |
| 19 |
return click.Group.get_command(self, ctx, matches[0]) |
| 20 |
ctx.fail(f"Too many matches: {', '.join(sorted(matches))}") |
| 21 |
|
| 22 |
async def resolve_command( |
| 23 |
self, ctx: click.Context, args: list[str] |
| 24 |
) -> tuple[str | None, click.Command, list[str]]: |
| 25 |
# always return the full command name |
| 26 |
_, cmd, args = await super().resolve_command(ctx, args) |
| 27 |
assert cmd is not None |
| 28 |
return cmd.name, cmd, args |
| 29 |
|
| 30 |
|
| 31 |
@click.command(cls=AliasedGroup) |
| 32 |
def cli() -> None: |
| 33 |
pass |
| 34 |
|
| 35 |
|
| 36 |
assert_type(cli, AliasedGroup) |
| 37 |
|
| 38 |
|
| 39 |
@cli.command() |
| 40 |
def push() -> None: |
| 41 |
pass |
| 42 |
|
| 43 |
|
| 44 |
@cli.command() |
| 45 |
def pop() -> None: |
| 46 |
pass |