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 fileTake it
The walk stopped after 200 commits: lines older than 430c50a point at it.
Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a
lines 1–16why, 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 = {}16Merge pull request #1331 from chusband/GH-1042David Lordbefore adoption68c9328
lines 17–19why, one step back17 def add_alias(self, alias, cmd):18 self.aliases.update({alias: cmd})19Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a
lines 20–27why, one step back20 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 pass27Merge pull request #1331 from chusband/GH-1042David Lordbefore adoption68c9328
lines 28–34why, one step back28 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)Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a
line 35why, one step back35Merge pull request #1331 from chusband/GH-1042David Lordbefore adoption68c9328
line 36why, one step back36Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a
lines 37–122why, one step back37pass_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)Merge pull request #1331 from chusband/GH-1042David Lordbefore adoption68c9328
lines 123–135why, one step back123124125@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))