Skip to content
Myr

cli.py

This file

Path

examples/complex/complex/cli.py

60 lines · 1.6 KiB · Python

Last changed by

Not known.

History of this file

Take it

1import os2import sys34import click567CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX")8910class Environment:11    def __init__(self):12        self.verbose = False13        self.home = os.getcwd()1415    def log(self, msg, *args):16        """Logs a message to stderr."""17        if args:18            msg %= args19        click.echo(msg, file=sys.stderr)2021    def vlog(self, msg, *args):22        """Logs a message to stderr only if verbose is enabled."""23        if self.verbose:24            self.log(msg, *args)252627pass_environment = click.make_pass_decorator(Environment, ensure=True)28cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands"))293031class ComplexCLI(click.MultiCommand):32    def list_commands(self, ctx):33        rv = []34        for filename in os.listdir(cmd_folder):35            if filename.endswith(".py") and filename.startswith("cmd_"):36                rv.append(filename[4:-3])37        rv.sort()38        return rv3940    def get_command(self, ctx, name):41        try:42            mod = __import__(f"complex.commands.cmd_{name}", None, None, ["cli"])43        except ImportError:44            return45        return mod.cli464748@click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS)49@click.option(50    "--home",51    type=click.Path(exists=True, file_okay=False, resolve_path=True),52    help="Changes the folder to operate on.",53)54@click.option("-v", "--verbose", is_flag=True, help="Enables verbose mode.")55@pass_environment56def cli(ctx, verbose, home):57    """A complex command line interface."""58    ctx.verbose = verbose59    if home is not None:60        ctx.home = home