python-click/examples/complex/complex/cli.py

61 lines
1.6 KiB
Python
Raw Normal View History

2014-10-16 20:40:34 +02:00
import os
import sys
2020-07-21 08:23:42 +02:00
import click
2014-10-16 20:40:34 +02:00
2020-07-21 08:23:42 +02:00
CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX")
2014-10-16 20:40:34 +02:00
2021-10-10 03:31:57 +02:00
class Environment:
2014-10-16 20:40:34 +02:00
def __init__(self):
self.verbose = False
self.home = os.getcwd()
def log(self, msg, *args):
"""Logs a message to stderr."""
if args:
msg %= args
click.echo(msg, file=sys.stderr)
def vlog(self, msg, *args):
"""Logs a message to stderr only if verbose is enabled."""
if self.verbose:
self.log(msg, *args)
2020-07-21 08:23:42 +02:00
pass_environment = click.make_pass_decorator(Environment, ensure=True)
cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands"))
2014-10-16 20:40:34 +02:00
class ComplexCLI(click.MultiCommand):
def list_commands(self, ctx):
rv = []
for filename in os.listdir(cmd_folder):
2020-07-21 08:23:42 +02:00
if filename.endswith(".py") and filename.startswith("cmd_"):
2014-10-16 20:40:34 +02:00
rv.append(filename[4:-3])
rv.sort()
return rv
def get_command(self, ctx, name):
try:
2021-10-10 03:31:57 +02:00
mod = __import__(f"complex.commands.cmd_{name}", None, None, ["cli"])
2014-10-16 20:40:34 +02:00
except ImportError:
return
return mod.cli
@click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS)
2020-07-21 08:23:42 +02:00
@click.option(
"--home",
type=click.Path(exists=True, file_okay=False, resolve_path=True),
help="Changes the folder to operate on.",
)
@click.option("-v", "--verbose", is_flag=True, help="Enables verbose mode.")
@pass_environment
2014-10-16 20:40:34 +02:00
def cli(ctx, verbose, home):
"""A complex command line interface."""
ctx.verbose = verbose
if home is not None:
ctx.home = home