Skip to content

Instantly share code, notes, and snippets.

@gar1t
Last active September 11, 2023 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gar1t/481cda3a0069bd61c5b08fda22d8b84c to your computer and use it in GitHub Desktop.
Save gar1t/481cda3a0069bd61c5b08fda22d8b84c to your computer and use it in GitHub Desktop.
import re
import typer
import typer.core
class AliasGroup(typer.core.TyperGroup):
"""Typer Group subclass that supports commands with aliases.
To alias a command, include the aliases in the command name,
separated by commas.
"""
_CMD_SPLIT_P = re.compile(r", ?")
def get_command(self, ctx, cmd_name):
cmd_name = self._group_cmd_name(self.commands.values(), cmd_name)
return super().get_command(ctx, cmd_name)
def _group_cmd_name(self, group_command_names, default_name):
for cmd in group_command_names:
if cmd.name and default_name in self._CMD_SPLIT_P.split(cmd.name):
return cmd.name
return default_name
app = typer.Typer(cls=AliasGroup, add_completion=False, no_args_is_help=True)
@app.command("foo, f")
def foo():
"""Print a message and exit."""
print("Works as command `foo` or its alias `f`")
@app.callback()
def main():
pass
app()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment