Last active
October 3, 2016 07:20
-
-
Save dojiong/02912bebf7859c1ed0a1c3762ad19051 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import partial | |
import click | |
def class_group(name=None, parent=click, **group_args): | |
def dec(cls): | |
attrs = dir(cls) | |
group_name = name or getattr(cls, '__cmd__', None) \ | |
or cls.__name__.lower() | |
group = parent.group(group_name, **group_args)(cls) | |
def set_ctx(*argv, **kwargs): | |
click.get_current_context().obj = cls(*argv, **kwargs) | |
group.callback = set_ctx | |
for attr in attrs: | |
if attr.startswith('__'): | |
continue | |
val = getattr(cls, attr) | |
if isinstance(val, click.Command): | |
def t(cb, *args, **kwargs): | |
ctx = click.get_current_context() | |
obj = ctx.find_object(cls) | |
return ctx.invoke(cb, obj, *args[1:], **kwargs) | |
val.callback = partial(t, val.callback) | |
group.add_command(val) | |
return cls | |
return dec | |
@click.group() | |
def cli(): | |
pass | |
@class_group(parent=cli) | |
@click.option('-v', '--verbose', is_flag=True) | |
class Test(object): | |
def __init__(self, verbose): | |
self.verbose = verbose | |
@click.command() | |
def hello(self): | |
if self.verbose: | |
print('[v]hello') | |
else: | |
print('hello') | |
if __name__ == '__main__': | |
cli() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment