adding initial boilerplates
This commit is contained in:
15
python/cli-click/multipleSubCommands-use.py
Normal file
15
python/cli-click/multipleSubCommands-use.py
Normal file
@@ -0,0 +1,15 @@
|
||||
import click
|
||||
from complex.cli import pass_environment
|
||||
|
||||
|
||||
@click.command('init', short_help='Initializes a repo.')
|
||||
@click.argument('path', required=False, type=click.Path(resolve_path=True))
|
||||
@pass_environment
|
||||
def cli(ctx, path):
|
||||
"""Initializes a repository."""
|
||||
print(f'{ctx=}')
|
||||
print(f'{dir(ctx)=}')
|
||||
if path is None:
|
||||
path = ctx.home
|
||||
ctx.log('Initialized the repository in %s',
|
||||
click.format_filename(path))
|
||||
64
python/cli-click/multipleSubCommands.py
Normal file
64
python/cli-click/multipleSubCommands.py
Normal file
@@ -0,0 +1,64 @@
|
||||
import os
|
||||
import sys
|
||||
import click
|
||||
|
||||
CONTEXT_SETTINGS = dict(auto_envvar_prefix='COMPLEX')
|
||||
|
||||
|
||||
class Environment(object):
|
||||
|
||||
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)
|
||||
|
||||
|
||||
pass_environment = click.make_pass_decorator(Environment, ensure=True)
|
||||
cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__),
|
||||
'commands'))
|
||||
|
||||
|
||||
class ComplexCLI(click.MultiCommand):
|
||||
|
||||
def list_commands(self, ctx):
|
||||
rv = []
|
||||
for filename in os.listdir(cmd_folder):
|
||||
if filename.endswith('.py') and \
|
||||
filename.startswith('cmd_'):
|
||||
rv.append(filename[4:-3])
|
||||
rv.sort()
|
||||
return rv
|
||||
|
||||
def get_command(self, ctx, name):
|
||||
try:
|
||||
if sys.version_info[0] == 2:
|
||||
name = name.encode('ascii', 'replace')
|
||||
mod = __import__('complex.commands.cmd_' + name,
|
||||
None, None, ['cli'])
|
||||
except ImportError:
|
||||
return
|
||||
return mod.cli
|
||||
|
||||
|
||||
@click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS)
|
||||
@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
|
||||
def cli(ctx, verbose, home):
|
||||
"""A complex command line interface."""
|
||||
ctx.verbose = verbose
|
||||
if home is not None:
|
||||
ctx.home = home
|
||||
87
python/cli-click/settingsOptionsClass.py
Normal file
87
python/cli-click/settingsOptionsClass.py
Normal file
@@ -0,0 +1,87 @@
|
||||
import click
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
def build_settings_option_class(settings_instance):
|
||||
def set_default(default_name):
|
||||
class Cls(click.Option):
|
||||
def __init__(self, *args, **kwargs):
|
||||
kwargs['default'] = getattr(settings_instance, default_name)
|
||||
super(Cls, self).__init__(*args, **kwargs)
|
||||
|
||||
def handle_parse_result(self, ctx, opts, args):
|
||||
obj = ctx.find_object(type(settings_instance))
|
||||
if obj is None:
|
||||
ctx.obj = settings_instance
|
||||
|
||||
return super(Cls, self).handle_parse_result(ctx, opts, args)
|
||||
|
||||
return Cls
|
||||
|
||||
return set_default
|
||||
|
||||
|
||||
class Settings(object):
|
||||
def __init__(self):
|
||||
self.instance_disk_size = 100
|
||||
self.instance_disk_type = 'pd-ssd'
|
||||
|
||||
|
||||
# import pudb; pudb.set_trace()
|
||||
settings = Settings()
|
||||
settings_option_cls = build_settings_option_class(settings)
|
||||
pass_settings = click.make_pass_decorator(Settings)
|
||||
|
||||
|
||||
@click.command()
|
||||
@click.help_option('-h', '--help')
|
||||
@click.option(
|
||||
'-s',
|
||||
'--disk-size',
|
||||
cls=settings_option_cls('instance_disk_size'),
|
||||
help="Disk size",
|
||||
show_default=True,
|
||||
type=int,
|
||||
)
|
||||
@click.option(
|
||||
'-t',
|
||||
'--disk-type',
|
||||
cls=settings_option_cls('instance_disk_type'),
|
||||
help="Disk type",
|
||||
show_default=True,
|
||||
type=click.Choice(['pd-standard', 'pd-ssd']),
|
||||
)
|
||||
@pass_settings
|
||||
def create(settings_test, disk_size, disk_type):
|
||||
print(f'{settings_test.instance_disk_type=}')
|
||||
print(f'{dir(settings_test)=}')
|
||||
print(disk_size)
|
||||
print(disk_type)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
commands = (
|
||||
'-t pd-standard -s 200',
|
||||
'-t pd-standard',
|
||||
'-s 200',
|
||||
'',
|
||||
'--help',
|
||||
)
|
||||
|
||||
time.sleep(1)
|
||||
print('Click Version: {}'.format(click.__version__))
|
||||
print('Python Version: {}'.format(sys.version))
|
||||
for cmd in commands:
|
||||
try:
|
||||
time.sleep(0.1)
|
||||
print('-----------')
|
||||
print('> ' + cmd)
|
||||
time.sleep(0.1)
|
||||
create(cmd.split())
|
||||
|
||||
except BaseException as exc:
|
||||
if str(exc) != '0' and not isinstance(
|
||||
exc, (click.ClickException, SystemExit)
|
||||
):
|
||||
raise
|
||||
Reference in New Issue
Block a user