aliases.py
This file
Path
examples/aliases/aliases.py
143 lines · 4.0 KiB · Python
Last changed by
add codespell pre-commit hook (#3373)David Lordbefore adoption8bd8b4a
History of this fileTake it
The walk stopped after 200 commits: lines older than 9ce34f2 point at it.
Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 1–42why, one step back1import configparser2import os34import click567class Config:8 """The config in this example only holds aliases."""910 def __init__(self):11 self.path = os.getcwd()12 self.aliases = {}1314 def add_alias(self, alias, cmd):15 self.aliases.update({alias: cmd})1617 def read_config(self, filename):18 parser = configparser.RawConfigParser()19 parser.read([filename])20 try:21 self.aliases.update(parser.items("aliases"))22 except configparser.NoSectionError:23 pass2425 def write_config(self, filename):26 parser = configparser.RawConfigParser()27 parser.add_section("aliases")28 for key, value in self.aliases.items():29 parser.set("aliases", key, value)30 with open(filename, "wb") as file:31 parser.write(file)323334pass_config = click.make_pass_decorator(Config, ensure=True)353637class AliasedGroup(click.Group):38 """This subclass of a group supports looking up aliases in a config39 file and with a bit of magic.40 """4142 def get_command(self, ctx, cmd_name):add codespell pre-commit hook (#3373)David Lordbefore adoption8bd8b4a
line 43why, one step back43 # Step one: built-in commands as normalMake faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2
lines 44–143why, one step back44 rv = click.Group.get_command(self, ctx, cmd_name)45 if rv is not None:46 return rv4748 # Step two: find the config object and ensure it's there. This49 # will create the config object is missing.50 cfg = ctx.ensure_object(Config)5152 # Step three: look up an explicit command alias in the config53 if cmd_name in cfg.aliases:54 actual_cmd = cfg.aliases[cmd_name]55 return click.Group.get_command(self, ctx, actual_cmd)5657 # Alternative option: if we did not find an explicit alias we58 # allow automatic abbreviation of the command. "status" for59 # instance will match "st". We only allow that however if60 # there is only one command.61 matches = [62 x for x in self.list_commands(ctx) if x.lower().startswith(cmd_name.lower())63 ]64 if not matches:65 return None66 elif len(matches) == 1:67 return click.Group.get_command(self, ctx, matches[0])68 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")6970 def resolve_command(self, ctx, args):71 # always return the command's name, not the alias72 _, cmd, args = super().resolve_command(ctx, args)73 return cmd.name, cmd, args747576def read_config(ctx, param, value):77 """Callback that is used whenever --config is passed. We use this to78 always load the correct config. This means that the config is loaded79 even if the group itself never executes so our aliases stay always80 available.81 """82 cfg = ctx.ensure_object(Config)83 if value is None:84 value = os.path.join(os.path.dirname(__file__), "aliases.ini")85 cfg.read_config(value)86 return value878889@click.command(cls=AliasedGroup)90@click.option(91 "--config",92 type=click.Path(exists=True, dir_okay=False),93 callback=read_config,94 expose_value=False,95 help="The config file to use instead of the default.",96)97def cli():98 """An example application that supports aliases."""99100101@cli.command()102def push():103 """Pushes changes."""104 click.echo("Push")105106107@cli.command()108def pull():109 """Pulls changes."""110 click.echo("Pull")111112113@cli.command()114def clone():115 """Clones a repository."""116 click.echo("Clone")117118119@cli.command()120def commit():121 """Commits pending changes."""122 click.echo("Commit")123124125@cli.command()126@pass_config127def status(config):128 """Shows the status."""129 click.echo(f"Status for {config.path}")130131132@cli.command()133@pass_config134@click.argument("alias_", metavar="ALIAS", type=click.STRING)135@click.argument("cmd", type=click.STRING)136@click.option(137 "--config_file", type=click.Path(exists=True, dir_okay=False), default="aliases.ini"138)139def alias(config, alias_, cmd, config_file):140 """Adds an alias to the specified configuration file."""141 config.add_alias(alias_, cmd)142 config.write_config(config_file)143 click.echo(f"Added '{alias_}' as alias for '{cmd}'")