cli.py
This file
Path
examples/complex/complex/cli.py
65 lines · 1.8 KiB · Python
Last changed by
Merge pull request #1328 from blackmagic02881/7.xDavid Lordbefore adoption3932d80
History of this fileTake it
1import os2import sys3import click456CONTEXT_SETTINGS = dict(auto_envvar_prefix='COMPLEX')789class Environment(object):1011 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__),29 'commands'))303132class ComplexCLI(click.MultiCommand):3334 def list_commands(self, ctx):35 rv = []36 for filename in os.listdir(cmd_folder):37 if filename.endswith('.py') and \38 filename.startswith('cmd_'):39 rv.append(filename[4:-3])40 rv.sort()41 return rv4243 def get_command(self, ctx, name):44 try:45 if sys.version_info[0] == 2:46 name = name.encode('ascii', 'replace')47 mod = __import__('complex.commands.cmd_' + name,48 None, None, ['cli'])49 except ImportError:50 return51 return mod.cli525354@click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS)55@click.option('--home', type=click.Path(exists=True, file_okay=False,56 resolve_path=True),57 help='Changes the folder to operate on.')58@click.option('-v', '--verbose', is_flag=True,59 help='Enables verbose mode.')60@pass_environment61def cli(ctx, verbose, home):62 """A complex command line interface."""63 ctx.verbose = verbose64 if home is not None:65 ctx.home = home