import click
import functools
class RuntimeConfig:
"""Runtime configuration class. Set `config_file` and `profile`."""
def __init__(self, config_file: str = None, profile: str = None):
self.config_file = config_file or "config.conf"
self.profile = profile or "default"
pass_rconfig = click.make_pass_decorator(RuntimeConfig, ensure=True)
def common_options(f):
options = [
click.option( "--config", "-c", "config_file", default=None),
click.option("--profile", "-p", type=str, default=None),
]
return functools.reduce(lambda x, opt: opt(x), options, f)
@click.group()
@common_options
@click.pass_context
def cli(ctx, config_file, profile):
ctx.obj = RuntimeConfig(config_file, profile)
@cli.group("cmd1")
def cmd1():
pass
@cmd1.command("cmd2")
@common_options
@pass_rconfig
def cmd2(ctx, config_file, profile):
print("--config from context:", ctx.config_file)
print("--profile from context:", ctx.profile)
print("--config:", config_file)
print("--profile:", profile)
if __name__ == "__main__":
cli()