Last active
May 17, 2018 23:54
-
-
Save boredstiff/2c194629ee5afa3f734d0de546249e4c to your computer and use it in GitHub Desktop.
Click reusing options and chaining commands
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
"""This allows you to reuse options between commands and call one command to call two other commands. | |
So when 'create' is called, 'create_package' and 'create_repo' will be called and 'create_package' and 'create_repo' | |
can be called individually. | |
""" | |
import click | |
PACKAGE_NAME_KEY = __name__ + '.package_name' | |
REPO_NAME_KEY = __name__ + '.repo_name' | |
@click.group(chain=True, invoke_without_command=False) | |
def cli(): | |
pass | |
def set_package_name(context, params, value): | |
if value: | |
print('value coming in: {}'.format(value)) | |
context.meta[PACKAGE_NAME_KEY] = value | |
def set_repo_name(context, params, value): | |
if value: | |
print('repo value coming in: {}'.format(value)) | |
context.meta[REPO_NAME_KEY] = value | |
package_options = [ | |
click.option( | |
'--package-name', '-p', | |
required=False, | |
prompt='Please enter a package name', | |
callback=set_package_name) | |
] | |
repo_options = [ | |
click.option( | |
'--repo-name', '-r', | |
required=False, | |
prompt='Please enter a repo name', | |
callback=set_repo_name) | |
] | |
def add_options(options): | |
def _add_options(func): | |
for option in reversed(options): | |
func = option(func) | |
return func | |
return _add_options | |
@cli.command() | |
@add_options(package_options) | |
@click.pass_context | |
def create_package(ctx, *args, **kwargs): | |
print('running package') | |
print('Package name inside of create package: {}'.format(ctx.meta[PACKAGE_NAME_KEY])) | |
@cli.command() | |
@add_options(repo_options) | |
@click.pass_context | |
def create_repo(ctx, *args, **kwargs): | |
print('running repo') | |
print('Repo name inside of create repo: {}'.format(ctx.meta[REPO_NAME_KEY])) | |
@cli.command() | |
@add_options(package_options) | |
@add_options(repo_options) | |
@click.pass_context | |
def create(ctx, *args, **kwargs): | |
ctx.invoke(create_package, *args, **kwargs) | |
ctx.invoke(create_repo) | |
if __name__ == '__main__': | |
cli() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment