aliases.py
This file
Path
examples/aliases/aliases.py
111 lines · 3.0 KiB · Python
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than b707ec7 point at it.
Implemented first pass of unprocessed option handling.Armin Ronacherbefore adoptionb707ec7
lines 1–111why, one step back1import os2import click34try:5 import ConfigParser as configparser6except ImportError:7 import configparser8910class Config(object):11 """The config in this example only holds aliases."""1213 def __init__(self):14 self.path = os.getcwd()15 self.aliases = {}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 pass242526pass_config = click.make_pass_decorator(Config, ensure=True)272829class AliasedGroup(click.Group):30 """This subclass of a group supports looking up aliases in a config31 file and with a bit of magic.32 """3334 def get_command(self, ctx, cmd_name):35 # Step one: bulitin commands as normal36 rv = click.Group.get_command(self, ctx, cmd_name)37 if rv is not None:38 return rv3940 # Step two: find the config object and ensure it's there. This41 # will create the config object is missing.42 cfg = ctx.ensure_object(Config)4344 # Step three: lookup an explicit command aliase in the config45 if cmd_name in cfg.aliases:46 actual_cmd = cfg.aliases[cmd_name]47 return click.Group.get_command(self, ctx, actual_cmd)4849 # Alternative option: if we did not find an explicit alias we50 # allow automatic abbreviation of the command. "status" for51 # instance will match "st". We only allow that however if52 # there is only one command.53 matches = [x for x in self.list_commands(ctx)54 if x.lower().startswith(cmd_name.lower())]55 if not matches:56 return None57 elif len(matches) == 1:58 return click.Group.get_command(self, ctx, matches[0])59 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))606162def read_config(ctx, param, value):63 """Callback that is used whenever --config is passed. We use this to64 always load the correct config. This means that the config is loaded65 even if the group itself never executes so our aliases stay always66 available.67 """68 cfg = ctx.ensure_object(Config)69 if value is None:70 value = os.path.join(os.path.dirname(__file__), 'aliases.ini')71 cfg.read_config(value)72 return value737475@click.command(cls=AliasedGroup)76@click.option('--config', type=click.Path(exists=True, dir_okay=False),77 callback=read_config, expose_value=False,78 help='The config file to use instead of the default.')79def cli():80 """An example application that supports aliases."""818283@cli.command()84def push():85 """Pushes changes."""86 click.echo('Push')878889@cli.command()90def pull():91 """Pulls changes."""92 click.echo('Pull')939495@cli.command()96def clone():97 """Clones a repository."""98 click.echo('Clone')99100101@cli.command()102def commit():103 """Commits pending changes."""104 click.echo('Commit')105106107@cli.command()108@pass_config109def status(config):110 """Shows the status."""111 click.echo('Status for %s' % config.path)