Skip to content
Myr

aliases.py

This file

Path

examples/aliases/aliases.py

135 lines · 3.9 KiB · Python

Last changed by

Merge pull request #1331 from chusband/GH-1042David Lordbefore adoption68c9328

History of this file

Take it

1import 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 add_alias(self, alias, cmd):18        self.aliases.update({alias: cmd})1920    def read_config(self, filename):21        parser = configparser.RawConfigParser()22        parser.read([filename])23        try:24            self.aliases.update(parser.items('aliases'))25        except configparser.NoSectionError:26            pass2728    def write_config(self, filename):29        parser = configparser.RawConfigParser()30        parser.add_section('aliases')31        for key, value in self.aliases.items():32            parser.set('aliases', key, value)33        with open(filename, 'wb') as file:34            parser.write(file)353637pass_config = click.make_pass_decorator(Config, ensure=True)383940class AliasedGroup(click.Group):41    """This subclass of a group supports looking up aliases in a config42    file and with a bit of magic.43    """4445    def get_command(self, ctx, cmd_name):46        # Step one: bulitin commands as normal47        rv = click.Group.get_command(self, ctx, cmd_name)48        if rv is not None:49            return rv5051        # Step two: find the config object and ensure it's there.  This52        # will create the config object is missing.53        cfg = ctx.ensure_object(Config)5455        # Step three: lookup an explicit command aliase in the config56        if cmd_name in cfg.aliases:57            actual_cmd = cfg.aliases[cmd_name]58            return click.Group.get_command(self, ctx, actual_cmd)5960        # Alternative option: if we did not find an explicit alias we61        # allow automatic abbreviation of the command.  "status" for62        # instance will match "st".  We only allow that however if63        # there is only one command.64        matches = [x for x in self.list_commands(ctx)65                   if x.lower().startswith(cmd_name.lower())]66        if not matches:67            return None68        elif len(matches) == 1:69            return click.Group.get_command(self, ctx, matches[0])70        ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))717273def read_config(ctx, param, value):74    """Callback that is used whenever --config is passed.  We use this to75    always load the correct config.  This means that the config is loaded76    even if the group itself never executes so our aliases stay always77    available.78    """79    cfg = ctx.ensure_object(Config)80    if value is None:81        value = os.path.join(os.path.dirname(__file__), 'aliases.ini')82    cfg.read_config(value)83    return value848586@click.command(cls=AliasedGroup)87@click.option('--config', type=click.Path(exists=True, dir_okay=False),88              callback=read_config, expose_value=False,89              help='The config file to use instead of the default.')90def cli():91    """An example application that supports aliases."""929394@cli.command()95def push():96    """Pushes changes."""97    click.echo('Push')9899100@cli.command()101def pull():102    """Pulls changes."""103    click.echo('Pull')104105106@cli.command()107def clone():108    """Clones a repository."""109    click.echo('Clone')110111112@cli.command()113def commit():114    """Commits pending changes."""115    click.echo('Commit')116117118@cli.command()119@pass_config120def status(config):121    """Shows the status."""122    click.echo('Status for %s' % config.path)123124125@cli.command()126@pass_config127@click.argument("alias_", metavar='ALIAS', type=click.STRING)128@click.argument("cmd", type=click.STRING)129@click.option('--config_file', type=click.Path(exists=True, dir_okay=False),130              default="aliases.ini")131def alias(config, alias_, cmd, config_file):132    """Adds an alias to the specified configuration file."""133    config.add_alias(alias_, cmd)134    config.write_config(config_file)135    click.echo('Added %s as alias for %s' % (alias_, cmd))