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
Provenance
- Commit
fdb0a8c- Tree
2cd77f1- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
9f778e8
4 files changed+144 added−0 removed
added:examples/aliases/aliases.ini+2 added
1+[aliases]2+ci=commitadded:examples/aliases/aliases.py+111 added
1+import os2+import click3+4+try:5+ import ConfigParser as configparser6+except ImportError:7+ import configparser8+9+10+class Config(object):11+ """The config in this example only holds aliases."""12+13+ def __init__(self):14+ self.path = os.getcwd()15+ self.aliases = {}16+17+ 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+ pass24+25+26+pass_config = click.make_pass_decorator(Config, ensure=True)27+28+29+class AliasedGroup(click.Group):30+ """This subclass of a group supports looking up aliases in a config31+ file and with a bit of magic.32+ """33+34+ 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 rv39+40+ # 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)43+44+ # 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)48+49+ # 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)))60+61+62+def 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 value73+74+75+@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.')79+def cli():80+ """An example application that supports aliases."""81+82+83+@cli.command()84+def push():85+ """Pushes changes."""86+ click.echo('Push')87+88+89+@cli.command()90+def pull():91+ """Pulls changes."""92+ click.echo('Pull')93+94+95+@cli.command()96+def clone():97+ """Clones a repository."""98+ click.echo('Clone')99+100+101+@cli.command()102+def commit():103+ """Commits pending changes."""104+ click.echo('Commit')105+106+107+@cli.command()108+@pass_config109+def status(config):110+ """Shows the status."""111+ click.echo('Status for %s' % config.path)added:examples/aliases/README+16 added
1+$ complex_2+3+ complex is an example of building very complex cli4+ applications that load subcommands dynamically from5+ a plugin folder and other things.6+7+ 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.12+13+Usage:14+15+ $ pip install --editable .16+ $ complex --helpadded:examples/aliases/setup.py+15 added
1+from setuptools import setup2+3+setup(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+)