Skip to content
Myr

Added a complex aliases example

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 9f778e8 · Browse files · 4 files+144 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+144 added−0 removed

  • other:+144 added−0 removed

4 files+144 added−0 removed

added:examples/aliases/aliases.ini+2 added
1[aliases]2ci=commit
added:examples/aliases/aliases.py+111 added
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 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, 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)
added:examples/aliases/README+16 added
1$ complex_23 complex is an example of building very complex cli4 applications that load subcommands dynamically from5 a plugin folder and other things.67 All the commands are implemented as plugins in the8 `complex.commands` package. If a python module is9 placed named "cmd_foo" it will show up as "foo"10 command and the `cli` object within it will be11 loaded as nested click command.1213Usage:1415 $ pip install --editable .16 $ complex --help
added:examples/aliases/setup.py+15 added
1from setuptools import setup23setup(4 name='click-example-aliases',5 version='1.0',6 py_modules=['aliases'],7 include_package_data=True,8 install_requires=[9 'Click',10 ],11 entry_points='''12 [console_scripts]13 aliases=aliases:cli14 ''',15)