def decorator(f): return click.pass_context( opt_pwd( click.pass_context( opt_user(f) ) ) )
def fossor_cli_flags(f): '''Add default Fossor CLI flags''' # Flags will appear in reverse order of how they are listed here: f = add_dynamic_args(f) # Must be applied after all other click options since this requires click's context object to be passed # Add normal flags csv_list = CsvList() f = click.option('--black-list', 'blacklist', type=csv_list, help='Do not run these plugins.')(f) f = click.option('--white-list', 'whitelist', type=csv_list, help='Only run these plugins.')(f) f = click.option('--truncate/--no-truncate', 'truncate', show_default=True, default=True, is_flag=True)(f) f = click.option('-v', '--verbose', is_flag=True)(f) f = click.option('-d', '--debug', is_flag=True, callback=setup_logging)(f) f = click.option('-t', '--time-out', 'timeout', show_default=True, default=600, help='Default timeout for plugins.')(f) f = click.option('--end-time', callback=set_end_time, help='Plugins may optionally implement and use this. Defaults to now.')(f) f = click.option('--start-time', callback=set_start_time, help='Plugins may optionally implement and use this.')(f) f = click.option('--log-since', callback=set_log_since_time, help='LogCheck Plugins would use this.')(f) f = click.option('-r', '--report', type=click.STRING, show_default=True, default='StdOut', help='Report Plugin to run.')(f) f = click.option('--hours', type=click.INT, default=24, show_default=True, callback=set_relative_start_time, help='Sets start-time to X hours ago. Plugins may optionally implement and use this.')(f) f = click.option('--plugin-dir', default=default_plugin_dir, show_default=True, help=f'Import all plugins from this directory.')(f) f = click.option('-p', '--pid', type=click.INT, help='Pid to investigate.')(f) # Required for parsing dynamics arguments f = click.pass_context(f) f = click.command(context_settings=dict(ignore_unknown_options=True, allow_extra_args=True, help_option_names=['-h', '--help']))(f) return f
def build_stages(command): def run(ctx, **cli_params): out = [] for stage in command.stages: mapped_stage_params = { remap.old.lstrip("-"): cli_params[remap.new.lstrip("-")] for remap in stage.remap_params } mapped_stage_params.update(stage.params) inject_namespace = { k: v for k, v in cli_params.items() if k in command.inject_values } cmd = cli.get_command(ctx, stage.command) out.extend( ctx.invoke(cmd, **mapped_stage_params, inject_values=inject_namespace)) return out params = command.arguments + command.options return cli_tools.DocumentedCommand( name=command.name, params=params, callback=click.pass_context(run), short_help=command.short_help, help=command.help, section=getattr(command, "section", None), hidden=command.hidden, )
def define_command(descriptor): callback = descriptor['callback'] command = click.command(name=descriptor['name'], help=descriptor['help'], cls=DeprecatedOptionsCommand)( click.pass_context(callback)) if 'arguments' in descriptor: for key, value in descriptor['arguments'].items(): command = click.argument(key, **value)(command) if 'options' in descriptor: for key, value in descriptor['options'].items(): if type(key) == tuple: click_option = click.option(*key, **value) else: click_option = click.option(key, **value) command = click_option(command) command = click.help_option(hidden=True)(command) verbose_option = click.option('--verbose', is_flag=True, expose_value=False, callback=set_verbose_mode, help='Debug mode') command = verbose_option(command) for group in descriptor['groups']: command_copy = copy.deepcopy(command) if '%s' in descriptor['help']: command_copy.help = descriptor['help'] % group.name group.add_command(command_copy)
def __init__(self, device_class, name=None, invoke_without_command=False, no_args_is_help=None, subcommand_metavar=None, chain=False, result_callback=None, result_callback_pass_device=True, **attrs): self.commands = getattr(device_class, "_device_group_commands", None) if self.commands is None: raise RuntimeError( "Class {} doesn't use DeviceGroupMeta meta class." " It can't be used with DeviceGroup.") self.device_class = device_class self.device_pass = click.make_pass_decorator(device_class) attrs.setdefault("params", self.DEFAULT_PARAMS) attrs.setdefault("callback", click.pass_context(self.group_callback)) if result_callback_pass_device and callable(result_callback): result_callback = self.device_pass(result_callback) super().__init__(name or device_class.__name__.lower(), invoke_without_command, no_args_is_help, subcommand_metavar, chain, result_callback, **attrs)
def add_delete_click_command(cls, command_group): """ Build a fully specified click command for deleting objects, and add it to the click command group `command_group`. Return the function object. :param command_group function: the click command group function to use to register our click command :rtype: function """ def delete_object(ctx, *args, **kwargs): click.secho(ctx.obj['adapter'].delete(kwargs['identifier'])) object_name = cls.endpoint_class.object_class.__name__ delete_object.__doc__ = f""" Delete an existing {cls.endpoint_class.object_class.__name__} object from Brigid. IDENTIFIER is one of {object_name}.id or {cls.endpoint_class.id_resolver_filter_format()}. Usage: brigid {command_group.name} delete IDENTIFIER """ function = print_render_exception(delete_object) function = click.pass_context(function) function = click.argument('identifier')(function) function = command_group.command( 'delete', short_help=f'Delete a {object_name} object from Brigid' )(function) return function
def add_retrieve_click_command(cls, command_group): """ Build a fully specified click command for retrieving single objects, and add it to the click command group `command_group`. Return the function object. :param command_group function: the click command group function to use to register our click command :rtype: function """ def retrieve_object(ctx, *args, **kwargs): click.secho(ctx.obj['adapter'].retrieve(kwargs['identifier'], kwargs['display'])) object_name = cls.endpoint_class.object_class.__name__ retrieve_object.__doc__ = f""" Get an existing {object_name} object from Brigid. IDENTIFIER is one of {object_name}.id or {cls.endpoint_class.id_resolver_filter_format()}. Usage: brigid {command_group.name} retrieve IDENTIFIER [--display=DISPLAY] """ function = print_render_exception(retrieve_object) function = click.pass_context(function) function = click.option('--display', **cls.retrieve_display_option_kwargs())(function) function = click.argument('identifier')(function) function = command_group.command( 'retrieve', short_help=f'Get a single {object_name} object from Brigid' )(function) return function
def add_create_click_command(cls, command_group): """ Build a fully specified click command for creating objects, and add it to the click command group `command_group`. Return the function object. :param command_group function: the click command group function to use to register our click command :rtype: function """ def create_object(ctx, *args, **kwargs): with open(kwargs['filename'], "r") as fd: file_data = fd.read() # Note as of PyYAML 5, the yaml parser will parse both JSON and YAML obj_data = yaml.safe_load(file_data) click.secho(ctx.obj['adapter'].create(**obj_data)) object_name = cls.endpoint_class.object_class.__name__ create_object.__doc__ = f""" Create a new {object_name} object in Brigid from a file. FILENAME can be either a JSON or YAML file, and should at least contain all the required attributes for {object_name} objects. Usage: brigid {command_group.name} create FILENAME """ # Wrap our function with the approriate decorators function = print_render_exception(create_object) function = click.pass_context(function) function = click.argument('filename', type=click.Path(exists=True)) function = command_group.command( 'create', short_help=f'Create a {object_name} object in Brigid' )(function) return function
def __init__(self, *args, **kwargs): # type: (*any, **any) -> None # Allow modules to be invoked without any other options behind them for backwards compatibility super(HealthcheckAddonGroup, self).__init__(chain=True, # Chain allows for multiple commands to specified invoke_without_command=True, callback=click.pass_context(self.run_methods_in_module), *args, **kwargs)
def build_stages(alias): def run(ctx, **cli_params): out = [] for stage in alias.stages: mapped_stage_params = { remap.old.lstrip("-"): cli_params[remap.new.lstrip("-")] for remap in stage.remap_params } mapped_stage_params.update(stage.options) inject_namespace = { k: v for k, v in cli_params.items() if k in alias.inject_values } cmd = cli.get_command(ctx, stage.command) out.extend( ctx.invoke(cmd, **mapped_stage_params, inject_values=inject_namespace)) return out params = alias.arguments + alias.options if alias.section: SECTIONS.setdefault(alias.section, []).append(alias.name) return click.Command( name=alias.name, params=params, callback=click.pass_context(run), short_help=alias.short_help, help=alias.help, )
def pass_context(f): @wraps(f) def _func(ctx, *args, **kwargs): profile = ctx.obj['profile'] if profile: pr = cProfile.Profile() pr.enable() try: ret = f(frappe._dict(ctx.obj), *args, **kwargs) except frappe.exceptions.SiteNotSpecifiedError as e: click.secho(str(e), fg='yellow') sys.exit(1) except frappe.exceptions.IncorrectSitePath: site = ctx.obj.get("sites", "")[0] click.secho(f'Site {site} does not exist!', fg='yellow') sys.exit(1) if profile: pr.disable() s = StringIO() ps = pstats.Stats(pr, stream=s)\ .sort_stats('cumtime', 'tottime', 'ncalls') ps.print_stats() # print the top-100 for line in s.getvalue().splitlines()[:100]: print(line) return ret return click.pass_context(_func)
def _create_callback(wf): def f(ctx, **kwargs): # execute workflow executor = SubprocessExecutor() input_artifacts = { ia_name: kwargs[ia_name] for ia_name in wf.signature.input_artifacts } input_parameters = { ip_name: kwargs[ip_name] for ip_name in wf.signature.input_parameters } output_artifacts = { oa_name: kwargs[oa_name] for oa_name in wf.signature.output_artifacts } future_ = executor(wf, input_artifacts, input_parameters, output_artifacts) # block (i.e., wait) until result is ready completed_process = future_.result() if completed_process.returncode != 0: click.echo(completed_process.stdout) click.echo(completed_process.stderr, err=True) ctx.exit(completed_process.returncode) return click.pass_context(f)
def test_case(func): @functools.wraps(func) def _catch_exceptions(*args, **kwargs): try: ctx, proxy = args[0], args[1] if proxy.verbose >= 1: print('%s...' % func.__name__) sys.stdout.flush() func(*args, **kwargs) if proxy.verbose >= 1: print('%s...OK' % func.__name__) else: print('.', end='') except AssertionError as e: test_failures.append(func.__name__) if proxy.verbose >= 1: import traceback print('ERROR') traceback.print_exc() else: print('E', end='') sys.stdout.flush() _catch_exceptions = click.pass_context(_catch_exceptions) _catch_exceptions = pass_proxy(_catch_exceptions) return _catch_exceptions
def _build_visualizer_callback(visualizer): # TODO there is a lot of code duplicated between # _build_visualizer_callback and _build_method_callback - revisit # this after the refactoring that is happening as part of # https://github.com/qiime2/qiime2/issues/39 def f(ctx, **kwargs): # TODO remove hardcoding of extension pending # https://github.com/qiime2/qiime2/issues/59 output_extension = '.qzv' inputs = { ia_name: qiime.sdk.Artifact.load(kwargs[ia_name]) for ia_name in visualizer.signature.inputs} parameters = {} for ip_name, ip_type in visualizer.signature.parameters.items(): parameters[ip_name] = _build_parameter(ip_name, ip_type, kwargs) outputs = collections.OrderedDict() for oa_name in visualizer.signature.outputs: oa_value = kwargs[oa_name] file_extension = os.path.splitext(oa_value)[1] if file_extension != output_extension: oa_value = ''.join([oa_value, output_extension]) outputs[oa_name] = oa_value args = inputs args.update(parameters) output_visualizations = visualizer(**args) if type(output_visualizations) is not tuple: output_visualizations = (output_visualizations,) for output_visualization, output_filepath in zip(output_visualizations, outputs.values()): output_visualization.save(output_filepath) return click.pass_context(f)
def cid_command(func): def wrapper(ctx, **kwargs): # Complete kwargs with other parameters if len(ctx.args) % 2 != 0: print( f"Unknown extra argument, or an option without value {ctx.args}" ) exit(-1) for i in range(0, len(ctx.args), 2): kwargs[ctx.args[i][2:].replace('-', '_')] = ctx.args[i + 1] set_parameters(kwargs, all_yes=ctx.obj.all_yes) res = func(ctx, **kwargs) params = get_parameters() logger.info('Next time you can use following command:') logger.info(' cid-cmd ' + ctx.info_name + ''.join([ f" --{k.replace('_','-')}" for k, v in ctx.params.items() if isinstance(v, bool) and v ]) + ''.join([ f" --{k.replace('_','-')} '{v}'" for k, v in ctx.params.items() if not isinstance(v, bool) and v is not None ]) + ''.join([ f" --{k} '{v}' " for k, v in params.items() if not isinstance(v, bool) and v is not None ])) return res wrapper.__doc__ = func.__doc__ wrapper.__name__ = func.__name__ return main.command(context_settings=dict( ignore_unknown_options=True, allow_extra_args=True, ))(click.pass_context(wrapper))
def _build_method_callback(method): def f(ctx, **kwargs): # TODO remove hardcoding of extension pending # https://github.com/qiime2/qiime2/issues/59 output_extension = '.qza' inputs = { ia_name: qiime.sdk.Artifact.load(kwargs[ia_name]) for ia_name in method.signature.inputs} parameters = {} for ip_name, ip_type in method.signature.parameters.items(): parameters[ip_name] = _build_parameter(ip_name, ip_type, kwargs) outputs = collections.OrderedDict() for oa_name in method.signature.outputs: oa_value = kwargs[oa_name] file_extension = os.path.splitext(oa_value)[1] if file_extension != output_extension: oa_value = ''.join([oa_value, output_extension]) outputs[oa_name] = oa_value args = inputs args.update(parameters) output_artifacts = method(**args) if type(output_artifacts) is not tuple: output_artifacts = (output_artifacts,) for output_artifact, output_filepath in zip(output_artifacts, outputs.values()): output_artifact.save(output_filepath) return click.pass_context(f)
def exp_apply_cmd(inner): @functools.wraps(inner) def wrapper(ctx, *args, **kwargs): for exp in filter_experiments(experiments, ctx.obj["filter"]): inner(exp, *args, **kwargs) return expcomb.command()(click.pass_context(wrapper))
def mk_compare_resampled(inner): @functools.wraps(inner) def wrapper(ctx, *args, **kwargs): docs, outf = inner(*args, **kwargs) compare_resampled_inner(docs, outf) return bootstrap.command("compare-resampled")(click.pass_context(wrapper))
def pass_context(func): """ Make click context ARIA specific. This exists purely for aesthetic reasons, otherwise some decorators are called ``@click.something`` instead of ``@aria.something``. """ return click.pass_context(func)
def register_commands(click): @click.group('user') def user_group(): """User commands.""" pass user_group.command('list')(list_users) user_group.command('create')(argument('id', metavar='<ID | URL>')( pass_context(create_user))) user_group.command('delete')(argument('id64', type=int, metavar='STEAMID64')( pass_context(delete_user))) user_group.command('seed')(seed_users)
def pass_context(func): """Make click context Cloudify specific This exists purely for aesthetic reasons, otherwise Some decorators are called `@click.something` instead of `@cfy.something` """ return click.pass_context(func)
def command_decorator(func: typing.Callable) -> click.core.Command: pass_state = click.make_pass_decorator(Config, ensure=True) verbose = click.option( *("-v", "--verbose"), count=True, help="Increase verbosity.", callback=Config.set_verbosity, # type: ignore ) return click.command()(verbose(pass_state(click.pass_context(func))))
def mk_test(inner): @functools.wraps(inner) def wrapper(ctx, *args, **kwargs): path_info = inner(*args, **kwargs) for exp_group in experiments: exp_group.run_all(path_info, ctx.obj["filter"]) return expcomb.command()(click.pass_context(wrapper))
def pass_context(f): if iscoroutinefunction(f): @wraps(f) async def wrapper(*args, **kwargs): return await f(get_current_context(), *args, **kwargs) return wrapper return click.pass_context(f)
def decorator(f): f = click.pass_context(f) def coro_wrapper(*args, **kwargs): def coroutine(sink): return f(sink, *args, **kwargs) return coroutine return chair_cli.command(name)(update_wrapper(coro_wrapper, f))
def mk_resample(inner): @functools.wraps(inner) def wrapper(ctx, *args, **kwargs): bootstrapper, outf, gold, guess, result, schedule, extra_pk = inner( *args, **kwargs ) resample_cmd_inner(bootstrapper, outf, gold, guess, result, schedule, extra_pk) return bootstrap.command("resample")(click.pass_context(wrapper))
def get_command(self, ctx, name): if name in self.sub_commands: sub_command = self.sub_commands[name] sub_command_config_options = self._command_config_options.get( sub_command, []) options = prepare_config_options( self.config, name, get_applicable_options(sub_command_config_options, self._application_context), self._ignore_hidden, self._disable_required) sub_sub_commands = [ cmd for cmd in self._all_commands if cmd.parent == sub_command ] if sub_sub_commands: return ClickCommandWithConfigOptions( self.config, command=sub_command, all_commands=self._all_commands, command_config_options=self._command_config_options, application_context=self._application_context, ignore_hidden=self._ignore_hidden, disable_required=self._disable_required, name=name, params=options, callback=click.pass_context(self.register_command)) else: return click.Command( name, params=options, help=sub_command.description, hidden=not self._ignore_hidden and sub_command.hidden, callback=click.pass_context(self.register_command), context_settings={ 'allow_extra_args': sub_command.allow_unknown_options, 'ignore_unknown_options': sub_command.allow_unknown_options })
def get_cli(self): """ Get Click command for each individual stdio command """ commands = [] for command in COMMANDS: commands.append( to_cli_command(command, click.pass_context( wrap_command(command)(self)))) return click.Group(commands=commands)
def _set_commands(click_group: click.core.Group): """ Set commands to click group based on the options in .fetchmerc file """ config_path = _get_config_path() config = ConfigParser.from_files(config_path) option_names = config.options('fetchme') for i in option_names: func = _get_command_func(i, config) click_group.command(name=i)(click.pass_context(func))
def setClickObject(self): context = { 'allow_extra_args': True, 'allow_interspersed_args': True, } callback = click.pass_context(self.run) commandObj = click.command( name = self.getName(), help = self.data.get('description'), context_settings = context )(callback) return commandObj
def pass_folder_locations(func): """ Decorates the function by passing previous context as first arg and standard folder locations as kwargs """ for details in osa.defaults.folder_defaults.values(): pathvars = merge_dicts(osa.defaults.default_path_vars, details['pathparams']) func = click.option(details['paramtxt'], type=click.Path(**pathvars), help=details['helptxt'], default=details['folder'], show_default=True)(func) func = click.pass_context(func) return func
def make_click_command( pkg_name, base_func, options=[], args=[], pass_context=False, default_prompt=False, set_defaults=False, group=None, arg_delimiter=default_arg_delimeter, alt_default_sources=[], ): """Make a click command with given options.""" if group is None: group = click if pass_context: base_func = click.pass_context(base_func) previous_options = set() for option in options: name = option[name_key] alt_names = option.get(alts_key) kwargs = option[kwargs_key] if set_defaults: kwargs[default_key] = load_default(pkg_name, name, alt_default_sources) kwargs_vals = [(help_key, create_help_msg(name, kwargs.get(default_key)))] if default_prompt: kwargs_vals.append( (prompt_key, " ".join(name.split(arg_delimiter)).title())) for kv in kwargs_vals: key, val = kv if key not in kwargs: kwargs[key] = val base_func = click.option( *create_option(name, previous_options, alts=alt_names), **kwargs)(base_func) for arg in args: name = arg[name_key] kwargs = arg[kwargs_key] base_func = click.argument(name, **kwargs)(base_func) return group.command()(base_func)
def group_apply_cmd(inner): @functools.wraps(inner) def wrapper(ctx, *args, **kwargs): inner( ( BoundExpGroup(exp_group, ctx.obj["filter"]) for exp_group in experiments ), *args, **kwargs ) return expcomb.command()(click.pass_context(wrapper))
def _add_values(): for val_name, val_conf in six.iteritems( cometblue.device.CometBlue.SUPPORTED_VALUES): if 'decode' in val_conf: def get_fn_with_name(get_fn_name, print_fn_name): def real_get_fn(ctx): with cometblue.device.CometBlue( ctx.obj.device_address, adapter=ctx.obj.adapter, pin=ctx.obj.pin) as device: value = getattr(device, get_fn_name)() print_fn = getattr(ctx.obj.formatter, print_fn_name) print_fn(value) return real_get_fn get_fn = get_fn_with_name('get_' + val_name, 'print_' + val_name) get_fn = click.pass_context(get_fn) help_text = 'Get %s' % val_conf['description'] if val_conf.get('read_requires_pin', False): help_text += ' (requires PIN)' get_fn = click.command( val_name, help=help_text)(get_fn) _device_get.add_command(get_fn) if 'encode' in val_conf: def set_fn_with_name(set_fn_name): def real_set_fn(ctx, value): with cometblue.device.CometBlue( ctx.obj.device_address, adapter=ctx.obj.adapter, pin=ctx.obj.pin) as device: getattr(device, set_fn_name)(value) return real_set_fn set_fn = getattr(_SetterFunctions, val_name)( set_fn_with_name('set_' + val_name)) set_fn = click.command( val_name, help='Set %s ' '(requires PIN)' % val_conf['description'])(set_fn) _device_set.add_command(set_fn)
def pass_context(f): @wraps(f) def _func(ctx, *args, **kwargs): profile = ctx.obj["profile"] if profile: pr = cProfile.Profile() pr.enable() ret = f(frappe._dict(ctx.obj), *args, **kwargs) if profile: pr.disable() s = StringIO.StringIO() ps = pstats.Stats(pr, stream=s).sort_stats("cumtime", "tottime", "ncalls") ps.print_stats() print s.getvalue() return ret return click.pass_context(_func)
def common_option(f): f = click.option('-n', default=1, help='Number of requests to perform')(f) f = click.option('-c', help='Number of multiple requests to make', default=1)(f) f = click.option('-v', default=0, help='How much troubleshooting info to print')(f) f = click.option('-D', help='', default='cn=Manager,dc=example,dc=com')(f) f = click.option('-w', help='')(f) f = click.argument('URL')(f) f = click.pass_context(f) return f
def pass_context(f): @wraps(f) def _func(ctx, *args, **kwargs): profile = ctx.obj['profile'] if profile: pr = cProfile.Profile() pr.enable() ret = f(frappe._dict(ctx.obj), *args, **kwargs) if profile: pr.disable() s = StringIO() ps = pstats.Stats(pr, stream=s)\ .sort_stats('cumtime', 'tottime', 'ncalls') ps.print_stats() # print the top-100 for line in s.getvalue().splitlines()[:100]: print(line) return ret return click.pass_context(_func)
group_desc = "" # Store our doc string _click_group_func.__doc__ = group_desc # Apply our Decorators; the below is equivalent to # @cli.group(name=sf) # @click.pass_context # def _click_group_func(ctx): # pass # # We intententionally use the decorators this way so # that we an apply our group_desc (if specified) from # the plugin modules we detect and load. _click_group_func = \ click.pass_context(_click_group_func) _click_group_func = \ cli.group(name=sf)(_click_group_func) # Set the flag and fall through command = False if fn_prefix: # Get our fn_suffix fn_suffix = fn[len(fn_prefix)+1:] # Store our function _click_func = getattr(obj, fn) _click_group_func.add_command(_click_func) # Flip the store flag
def register_repl(group, name="repl"): """Register :func:`repl()` as sub-command *name* of *group*.""" group.command(name=name)(click.pass_context(repl))
@click.option('-r', '--roll', default=None, type=int, help='% roll') @click.pass_context def cli(ctx, basic, roll): ctx.obj['basic'] = basic ctx.obj['roll'] = roll for name in ('item', 'sword', 'armor', 'weapon', 'potion', 'scroll', 'ring', 'wsr'): def inner(name=name): def func(ctx, count): basic = ctx.obj['basic'] for x in range(count): click.echo(globals()['_%s' % name](ctx.obj['roll'], basic)) func.__name__ = name return func func = inner() func = click.pass_context(func) func = click.argument('count', default=1, type=int)(func) cli.command()(func) @cli.command() @click.argument('code') def type(code): '''Roll up treasure type A-Z''' def doit(bits, data): if not data: return what, chance, result = data if d100() <= chance: bits.append('%s %s' % (roll_quantity(result), what))
for opt in res.identity_attributes: f = click.option('--%s' % opt, default=ATTR_UNSPECIFIED)(f) return f def plain_output(f): return click.option('--plain', '-p', default=False, is_flag=True)(f) def force(f): return click.option('--force', '-f', default=False, is_flag=True)(f) def cascade(f): return click.option('--cascade', '-C', default=False, is_flag=True)(f) # runtime create commands name = convert(res.__name__) f = click.pass_context(create(res)) f = plain_output(f) f = specify_all_attrs(f) manager.command(name=name + '-create')(f) # runtime delete commands f = click.pass_context(delete(res)) f = plain_output(f) f = force(f) f = cascade(f) f = specify_id_attrs(f) manager.command(name=name + '-delete')(f) # runtime update commands f = click.pass_context(update(res)) f = plain_output(f)
import sys import shutil import click import jinja2 from utils import slugify, jinjago @click.command() @click.argument('template-dir', default='./template', required=False) @click.argument('output-dir', default='./output', required=False) @click.option('--project-name', prompt='Project name', default='Project name', help='Human readable project name, used for titles and docs.') @click.option('--project-slug', prompt='Project slug', default=click.pass_context(lambda ctx: slugify(ctx.params['project_name'])), help='Project slug, used in paths, filenames, etc.') @click.option('--project-version', prompt='Project version', default='1.0.0') @click.option('--project-description', prompt='Project description', default='') @click.option('--force-delete', is_flag=True, default=False, help='Force delete the output directory') def scaffold(template_dir, output_dir, project_name, project_slug, project_version, project_description, force_delete): """ \b TEMPLATE_DIR Template directory [default: ./template]
from wurstc.net import WurstSession def _validate_url(ctx, param, value): try: url = urlparse(value) assert url.scheme, "No scheme (http/https)" assert url.netloc, "No netloc" return value except Exception as exc: raise click.BadParameter("%s is not a valid URL: %s" % (value, exc)) @click.command() @click.pass_context @click.option('--site', default=click.pass_context(get_site_from_context), prompt=True, callback=_validate_url) @click.option('username', '-u', '--user', default=getpass.getuser, prompt=True) @click.password_option('-p', '--password') def login(ctx, site, username, password): """ Exchange explicit user credentials for a token for a Wurst installation. """ if not site.endswith("/"): site += "/" if ctx.meta["wurst.cli"].yes or click.confirm("Post your credentials to %s?" % site): resp = WurstSession(site).post("api/v1/tokens/", data={ "username": username, "password": password }) token = resp.token assert token