|
| 1 | +""" AliasedGroup class for click_with_alias. """ |
| 2 | + |
| 3 | +import click |
| 4 | + |
| 5 | + |
| 6 | +class AliasedGroup(click.Group): |
| 7 | + """A Click group that supports aliasing.""" |
| 8 | + |
| 9 | + def add_command(self, cmd: click.Command, name=None) -> None: |
| 10 | + """ |
| 11 | + Add a command to the group. |
| 12 | +
|
| 13 | + Args: |
| 14 | + cmd: click.Command - The command to add. |
| 15 | + name: str - The name of the command. |
| 16 | + Returns: |
| 17 | + None |
| 18 | + Raises: |
| 19 | + ValueError: If the command name is already taken. |
| 20 | + """ |
| 21 | + aliases = getattr(cmd, "aliases", []) |
| 22 | + super().add_command(cmd, name) |
| 23 | + for alias in aliases: |
| 24 | + super().add_command(cmd, alias) |
| 25 | + |
| 26 | + def format_commands( |
| 27 | + self, ctx: click.Context, formatter: click.HelpFormatter |
| 28 | + ) -> None: |
| 29 | + """ |
| 30 | + Format the commands for the group. |
| 31 | +
|
| 32 | + Args: |
| 33 | + ctx: click.Context - The click context. |
| 34 | + formatter: click.HelpFormatter - The help formatter. |
| 35 | + Returns: |
| 36 | + None |
| 37 | + Raises: |
| 38 | + None |
| 39 | + """ |
| 40 | + commands = {} |
| 41 | + for name, cmd in self.commands.items(): |
| 42 | + if name == cmd.name: |
| 43 | + aliases = getattr(cmd, "aliases", []) |
| 44 | + if aliases: |
| 45 | + name = f"{name} ({', '.join(aliases)})" |
| 46 | + commands[name] = cmd |
| 47 | + |
| 48 | + rows = [ |
| 49 | + (name, cmd.get_short_help_str()) for name, cmd in commands.items() |
| 50 | + ] |
| 51 | + |
| 52 | + if rows: |
| 53 | + with formatter.section("Commands"): |
| 54 | + formatter.write_dl(rows) |
0 commit comments