I tried @Stephan Rauch's solution and was met with some challenges like help text output so I expanded on it. This was before I saw there's a library for this so I haven't tried that as what I built is working the way I want it to.
Adds a aliases=['foo', 'bar']
argument to the command while copying the help information from the base command.
Class:
class CustomCliGroup(click.Group):
"""Custom Cli Group for Click"""
def command(self, *args, **kwargs):
"""Adds the ability to add `aliases` to commands."""
def decorator(f):
aliases = kwargs.pop("aliases", None)
if aliases and isinstance(aliases, list):
name = kwargs.pop("name", None)
if not name:
raise click.UsageError("`name` command argument is required when using aliases.")
base_command = super(CustomCliGroup, self).command(
name, *args, **kwargs
)(f)
for alias in aliases:
cmd = super(CustomCliGroup, self).command(alias, *args, **kwargs)(f)
cmd.help = f"Alias for '{name}'.\n\n{cmd.help}"
cmd.params = base_command.params
else:
cmd = super(CustomCliGroup, self).command(*args, **kwargs)(f)
return cmd
return decorator
Usage:
import click
@click.group(
context_settings=dict(help_option_names=["-h", "--help"]), cls=CustomCliGroup
)
def cli():
"""My Excellent CLI"""
@cli.command()
def hello():
"""Says hello"""
click.echo("Hello, World!")
@cli.command(name="do", aliases=["stuff"])
@click.argument("name")
@click.option("--times", "-t", default=1, help="Number of times to do the thing")
def my_command(name, times):
"""This is my command"""
click.echo(f"Doing {name} {times} times.")
if __name__ == "__main__":
cli()
Output:
> python test.py -h
Usage: test.py [OPTIONS] COMMAND [ARGS]...
My Excellent CLI
Options:
-h, --help Show this message and exit.
Commands:
do This is my command
hello Says hello
stuff Alias for 'do'.
------------------------
> python test.py do -h
Usage: test.py do [OPTIONS] NAME
This is my command
Options:
-t, --times INTEGER Number of times to do the thing
-h, --help Show this message and exit.
------------------------
> python test.py stuff -h
Usage: test.py stuff [OPTIONS] NAME
Alias for 'do'.
This is my command
Options:
-t, --times INTEGER Number of times to do the thing
-h, --help Show this message and exit.
mycli my-command
andmycli my-cmd
for the same command/function – Charette