|
| 1 | +from typing import Any, Optional, Sequence |
| 2 | + |
| 3 | +import click |
| 4 | + |
| 5 | + |
| 6 | +class AliasedCommand(click.Command): |
| 7 | + def __init__(self, *args: Any, aliases: Sequence[str] = [], **kwargs: Any) -> None: |
| 8 | + super().__init__(*args, **kwargs) |
| 9 | + self.aliases = aliases |
| 10 | + |
| 11 | + |
| 12 | +class AliasedGroup(click.Group): |
| 13 | + def get_command(self, ctx: click.Context, cmd_name: str) -> Optional[click.Command]: |
| 14 | + rv = super().get_command(ctx, cmd_name) |
| 15 | + if rv is not None: |
| 16 | + return rv |
| 17 | + |
| 18 | + for name, cmd in self.commands.items(): |
| 19 | + if isinstance(cmd, AliasedCommand) and cmd_name in cmd.aliases: |
| 20 | + return cmd |
| 21 | + |
| 22 | + return None |
| 23 | + |
| 24 | + def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: |
| 25 | + super().format_commands(ctx, formatter) |
| 26 | + |
| 27 | + commands = [] |
| 28 | + for subcommand in self.list_commands(ctx): |
| 29 | + cmd = self.get_command(ctx, subcommand) |
| 30 | + if cmd is None: |
| 31 | + continue |
| 32 | + if cmd.hidden: |
| 33 | + continue |
| 34 | + |
| 35 | + if isinstance(cmd, AliasedCommand) and cmd.aliases: |
| 36 | + subcommand = f"{', '.join(cmd.aliases)}" |
| 37 | + commands.append((subcommand, cmd)) |
| 38 | + |
| 39 | + if len(commands): |
| 40 | + limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands) |
| 41 | + |
| 42 | + rows = [] |
| 43 | + for subcommand, cmd in commands: |
| 44 | + help = cmd.get_short_help_str(limit) |
| 45 | + rows.append((subcommand, help)) |
| 46 | + rows.append(("", f"(Alias for `{cmd.name}` command)")) |
| 47 | + if rows: |
| 48 | + with formatter.section("Aliases"): |
| 49 | + formatter.write_dl(rows) |
0 commit comments