def cli(get=None, post=None): def tabulating_decorator(f): def new_func(*args, **kwargs): ctx = click.get_current_context() data = ctx.invoke(f, *args, **kwargs) tabulate(data, **kwargs) return data return update_wrapper(new_func, f) group = click.Group(name='timeseries', short_help="Commands on timeseries readings.") # List # Create options, wrapping the tabulating getter list_params = getattr(get, '__click_params__', []) get.__click_params__ = [] options_get = options()(tabulating_decorator(get)) # then construct the actual list command list_command = click.command('list')(options_get) list_command.params = list_params + list_command.params group.add_command(list_command) # Post # Pull of any parameters from the given poster since we want them # at the head of the other post parameters post_params = getattr(post, '__click_params__', []) post.__click_params__ = [] # Construct the post options wrapping the tabulating poster options_post = post_options()(tabulating_decorator(post)) post_command = click.command('post')(options_post) # and prefix the poster's parameters post_command.params = post_params + post_command.params group.add_command(post_command) return group
def decorator(f): if 'name' in kwargs: cmd = click.command(*args, **kwargs)(f) else: name = f.__name__.replace('_', '-') cmd = click.command(*args, name=name, **kwargs)(f) self.add_command(cmd) return cmd
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 section(name=None, **attrs): """Creates a new :class:`Section` with a function as callback. This works otherwise the same as :func:`command` just that the `cls` parameter is set to :class:`Group`. """ attrs.setdefault("cls", Section) return click.command(name, **attrs)
def main(cls, *args, **kwargs): """ Executes the default action for the model. Convenient for making quick and dirt CLI tools. """ import click kind_map = { 'int': int, 'float': float, 'str': str, } def cli(**kwargs_): kwargs_ = {k: v for k, v in kwargs_.items() if v is not None} kwargs_ = {**kwargs, **kwargs_} m = cls._main(*args, **kwargs_) m.run() print(m) m.plot(show=True) for cmd, help in list(cls.OPTIONS.items())[::-1]: cmd, _, kind = cmd.partition(':') kind = kind_map[kind or 'float'] cmd = cmd.replace('_', '-') cli = click.option(f'--{cmd}', help=help, type=kind)(cli) cli = click.command()(cli) cli()
def create_client_command(f): """Constructs a Client Command. Given a reference to the Client class function, e.g. the Client.AccountClient.list, this constructs a click.Command. It passes the parent Group (see create_client_group) obj (e.g. the Client class instance), then sets invokes the function reference using the parent context `obj` as the `self` argument of the command. The `update_wrapper` is responsible for copying all the actual functions @option/@argument properties to the new function. Finally calling `command()(new_func)` creates the Command object and correctly parses all the parameters off the function. :param f: the class object to introspect :type f: `pureport_client.commands.CommandBase` :returns: an instance of click Command :rtype: `click.core.Command` """ actual_f = f.fget if isinstance(f, property) else f actual_f = create_print_wrapper(f) @pass_obj def new_func(obj, *args, **kwargs): return actual_f(obj, *args, **kwargs) new_func = update_wrapper(new_func, actual_f) return command()(new_func)
def get_command(self, ctx, name): # type: (click.Context, str) -> click.Command """ Retrieves a command to execute :param ctx: Passed context :param name: Name of the command :return: Function pointer to the command or None when no import could happen :rtype: callable """ cmd = self.commands.get(name) if cmd: return cmd # More extensive - build the command and register discovery_data = self._discover_methods() # Will be coming from cache result_handler = ctx.obj.result_handler # type: HCResults current_module_name = ctx.command.name if current_module_name in discovery_data.keys(): if name in discovery_data[current_module_name]: # Function found, inject the result handler function_data = discovery_data[current_module_name][name] # Try to avoid name collision with other modules. Might lead to unexpected results module_name = function_data['module_name'] mod = imp.load_source('healthcheck_{0}'.format(module_name), function_data['location']) cl = getattr(mod, function_data['class'])() method_to_run = getattr(cl, function_data['function']) full_name = '{0}-{1}'.format(module_name, name) wrapped_function = (self.healthcheck_wrapper(result_handler, full_name)(method_to_run)) # Inject our Healthcheck arguments # Wrap around the click decorator to extract the option arguments using the function parameters click_command_wrap = click.command(name=name, help=function_data.get('help'), short_help=function_data.get('short_help')) cmd = click_command_wrap(wrapped_function) self.add_command(cmd) return cmd
def main(cls, *args, **kwargs): """ Executes the default action for the model. Convenient for making quick and dirt CLI tools. """ import click kind_map = {"int": int, "float": float, "str": str} @click.option("--plot", is_flag=True, help="Display plot") @click.option("--debug", is_flag=True, help="Display debug information") def cli(plot=False, debug=False, **kwargs_): kwargs_ = {k: v for k, v in kwargs_.items() if v is not None} kwargs_ = {**kwargs, **kwargs_} m = cls._main(*args, **kwargs_) m.run() print(m) if debug: print("\n\nDEBUG SYMBOLS") for k, v in vars(m).items(): print(k, "=", pformat(v)) if plot: m.plot(show=True) for cmd, help in list(cls.OPTIONS.items())[::-1]: cmd, _, kind = cmd.partition(":") kind = kind_map[kind or "float"] cmd = cmd.replace("_", "-") cli = click.option(f"--{cmd}", help=help, type=kind)(cli) cli = click.command()(cli) cli()
def ykman_command(interfaces, *args, **kwargs): return click.command( cls=_YkmanCommand, *args, interfaces=interfaces, **kwargs, ) # type: ignore
def get_command(self, ctx: click.Context, cmd_name: str) -> tp.Optional[click.Command]: generator_cls = PlotGenerator.GENERATORS[cmd_name] @click.pass_context def command_template(context: click.Context, **kwargs: tp.Any) -> None: # extract common arguments and plot config from context common_options: CommonPlotOptions = context.obj["common_options"] plot_config: PlotConfig = context.obj["plot_config"] artefact_name: str = context.obj["save_artefact"] try: generator_instance = generator_cls(plot_config, **kwargs) if artefact_name: paper_config = get_paper_config() if paper_config.artefacts.get_artefact(artefact_name): LOG.info( f"Updating existing artefact '{artefact_name}'.") else: LOG.info(f"Creating new artefact '{artefact_name}'.") artefact = PlotArtefact.from_generator( artefact_name, generator_instance, common_options) paper_config.add_artefact(artefact) paper_config.store_artefacts() else: generator_instance(common_options) except PlotGeneratorFailed as ex: print(f"Failed to create plot generator {generator_cls.NAME}: " f"{ex.message}") # return command wrapped with options specified in the generator class command_definition = add_cli_options(command_template, *generator_cls.OPTIONS) return click.command(cmd_name)(command_definition)
def shell(name=None, **attrs): """Creates a new :class:`Shell` with a function as callback. This works otherwise the same as :func:`command` just that the `cls` parameter is set to :class:`Shell`. """ attrs.setdefault('cls', Shell) return click.command(name, **attrs)
def build_entrypoint(main: Callable[[Config], Any], options: List[click.option], **context_settings) -> Callable[..., Any]: decorators = [ click.command(context_settings=context_settings), click.argument("configuration-file", default=None, required=False, type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True)) ] decorators.extend(options) def entrypoint(**cli_options): file_options = {} configuration_file = cli_options["configuration_file"] if configuration_file: file_args = _build_file_args(Path(configuration_file)) collector = _decorate(decorators, lambda **options: options) file_options = collector.main(args=file_args, standalone_mode=False, **context_settings) file_options["configuration_file"] = configuration_file config = Config(**ChainMap(file_options, cli_options)) return main(config) decorated_entrypoint = _decorate(decorators, entrypoint) return decorated_entrypoint
def command(*args, **kwargs): command = click.command(*args, context_settings=context_settings, **kwargs) def wrapper(f): return command(log_options(f)) return wrapper
def command(name=None, cls=None, **attrs): """ Commands are the basic building block of command line interfaces in Click. A basic command handles command line parsing and might dispatch more parsing to commands nested below it. :param name: the name of the command to use unless a group overrides it. :param context_settings: an optional dictionary with defaults that are passed to the context object. :param params: the parameters to register with this command. This can be either :class:`Option` or :class:`Argument` objects. :param help: the help string to use for this command. :param epilog: like the help string but it's printed at the end of the help page after everything else. :param short_help: the short help to use for this command. This is shown on the command listing of the parent command. :param add_help_option: by default each command registers a ``--help`` option. This can be disabled by this parameter. :param options_metavar: The options metavar to display in the usage. Defaults to ``[OPTIONS]``. :param args_before_options: Whether or not to display the options metavar before the arguments. Defaults to False. """ return click.command(name=name, cls=cls or Command, **attrs)
def get_command(self, ctx, name): # type: (click.Context, str) -> click.Command """ Retrieves a command to execute :param ctx: Passed context :param name: Name of the command :return: Function pointer to the command or None when no import could happen :rtype: callable """ cmd = self.commands.get(name) if cmd: return cmd # More extensive - build the command and register # @todo Make recursive with other groups discovery_data = self._discover_methods() # Will be coming from cache current_module_name = ctx.command.name if current_module_name in discovery_data.keys(): if name in discovery_data[current_module_name]: function_data = discovery_data[current_module_name][name] mod = imp.load_source(function_data['module_name'], function_data['location']) cl = getattr(mod, function_data['class'])() method_to_run = getattr(cl, function_data['function']) # Wrap around the click decorator to extract the option arguments using the function parameters click_command_wrap = click.command(name=name, help=function_data.get('help'), short_help=function_data.get('short_help')) cmd = click_command_wrap(method_to_run) self.add_command(cmd) return cmd
def get_command(self, ctx, name): """Return the command object for the sub-command for the given parent to run. Collects the sub-commands options and sets up all needed attributes. Then creates a new click command to return to be run. :param ctx: Click context. :type ctx: Namespace :param name: Sub-command name. :type name: str :return: Click command object. :rtype: object """ collection = self.collection_cls() method = getattr(collection, name) new_method = self.convert_to_function(method) params = getattr(method, '__click_params__', []) new_method.__click_params__ = copy(params) attributes = dict() try: # removes methods documented parameters from showing in help attributes['help'] = method.__doc__.split('::')[0].strip() except AttributeError: # methods docstring does not container documented parameters attributes['help'] = method.__doc__ cmd = click.command(name=name, **attributes)(new_method) return cmd
def _build_command(self): wrapped = click.command(name=self.name)(self.invoke) for k in self.kwargs: logging.info(f"Binding click option for: {self.name} -> --{k}") wrapped = click.option(f"--{k}", callback=_deserialize_option)(wrapped) return wrapped
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 define_command(descriptor, wizard): callback = descriptor['callback'] command = click.command(name=descriptor['name'], short_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 not wizard: value.pop('prompt', None) callbacks = [check_empty_values] if 'validators' in value: callbacks = callbacks + value.pop('validators') value['callback'] = partial(multiple_option_callback, callbacks) 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=help_msg.VERBOSE_OPTION) 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 else: command_copy.help = descriptor['help'] group.add_command(command_copy)
def parse_arguments(fn: Any) -> Callable[[Any, str], None]: _, prog_name = fn.__name__.split("_", 1) orig_fn = copy.deepcopy(fn) fn = click.pass_obj(fn) command = click.command()(fn) def wrapped(self: Any, argstr: str) -> None: argv = shlex.split(argstr) logger.debug("%s", argv) try: command.main( args=argv, prog_name=prog_name, standalone_mode=False, obj=self, help_option_names=["-h", "--help"], ) except click.MissingParameter: click.echo(f"usage: {fn.__doc__}") wrapped.__doc__ = fn.__doc__ # type: ignore wrapped.__name__ = fn.__name__ # type: ignore wrapped.__orig_fn__ = orig_fn # type: ignore return wrapped
def click_command(self) -> click.Command: def f(click_action, *args, **kwargs): for action in self.actions: if action.name == click_action: ctx = click.get_current_context() signature = inspect.signature(action.run) params = { k: v for k, v in ctx.params.items() if k in signature.parameters } action.run(**params) # 注册 argument action_argument = click.core.Argument(param_decls=('click_action', )) click.decorators._param_memo(f, action_argument) for option in self.options: click_option = option.click_option() click.decorators._param_memo(f, click_option) context_settings = { 'max_content_width': 500, } command = click.command(name=self.name, context_settings=context_settings)(f) return command
def plot(func): try: import click except ImportError: click = None if click: doc_strings = [f.__doc__ for f in _plot_helper._functions] decorators = [click.command()] chain = itertools.chain(*(s.split("\n") for s in doc_strings)) lines1, lines2 = itertools.tee(chain) next(lines2, None) for line1, line2 in itertools.izip(lines1, lines2): if ':' in line1: opt, t = [s.strip() for s in line1.split(":")] decorators.append( click.option('--' + opt, type=pydoc.locate(t), help=line2.strip())) decorators.append(wraps(func)) else: decorators = [wraps(func)] @_decorate_all(decorators) def plotted_func(**kwargs): fig, ax = plt.subplots() name = func(fig, ax, **kwargs) for helper in _plot_helper._functions: helper(ax, **kwargs) fig.savefig(name) return plotted_func
def _delete_cmd_builder(self, handler_function: Callable) -> click.Command: if hasattr(handler_function, '__file_inputs__'): file_inputs = handler_function.__file_inputs__ else: file_inputs = default_file_inputs_handler() print_result = True if hasattr(handler_function, '__print_result__'): print_result = handler_function.__print_result__ @environment_name_option() @file_inputs.option() @ignore_missing_option() @tnco_client_secret_option() @tnco_pwd_option() @click.pass_context def cmd(ctx: click.Context, environment_name: str, file_content: Any, ignore_missing: bool, pwd: str = None, client_secret: str = None, **kwargs): ctl = self._get_controller() with ctl.tnco_client_safety_net(): tnco_client = ctl.get_tnco_client(environment_name, input_pwd=pwd, input_client_secret=client_secret) result = handler_function(tnco_client, ctx=ctx, file_content=file_content, ignore_missing=ignore_missing, **kwargs) if result is not None and print_result: ctl.io.print(f'Removed: {result}') # Add any extra arguments or options decorated on the handler_function if hasattr(handler_function, '__click_params__'): cmd.__click_params__.extend(handler_function.__click_params__) # Build final command cmd_kwargs = {} if not hasattr(handler_function, '__cmd_kwargs__') else handler_function.__cmd_kwargs__ if 'help' not in cmd_kwargs: help = f'Delete {self.display_name}' help += f'\n\n If "-f, --file" option is set then the target {self.display_name} will be discovered from this file' cmd_kwargs['help'] = help if 'short_help' not in cmd_kwargs: cmd_kwargs['short_help'] = f'Delete {self.display_name}' cmd = click.command(**cmd_kwargs)(cmd) return cmd
def plot(func): try: import click except ImportError: click = None if click: doc_strings = [f.__doc__ for f in _plot_helper._functions] decorators = [click.command()] chain = itertools.chain(*(s.split("\n") for s in doc_strings)) lines1, lines2 = itertools.tee(chain) next(lines2, None) for line1, line2 in itertools.izip(lines1, lines2): if ':' in line1: opt, t = [s.strip() for s in line1.split(":")] decorators.append(click.option('--' + opt, type=pydoc.locate(t), help=line2.strip())) decorators.append(wraps(func)) else: decorators = [wraps(func)] @_decorate_all(decorators) def plotted_func(**kwargs): fig, ax = plt.subplots() name = func(fig, ax, **kwargs) for helper in _plot_helper._functions: helper(ax, **kwargs) fig.savefig(name) return plotted_func
def _get_cmd_builder(self, handler_function: Callable) -> click.Command: if hasattr(handler_function, '__output_formats__'): output_formats = handler_function.__output_formats__ else: output_formats = default_output_format_handler() # Build up a command (but don't decorate it as one yet) @environment_name_option() @output_formats.option() @tnco_client_secret_option() @tnco_pwd_option() @click.pass_context def cmd(ctx: click.Context, environment_name: str, output_format: str, pwd: str = None, client_secret: str = None, **kwargs): ctl = self._get_controller() output_formatter = output_formats.resolve_choice(output_format) with ctl.tnco_client_safety_net(): tnco_client = ctl.get_tnco_client(environment_name, input_pwd=pwd, input_client_secret=client_secret) result = handler_function(tnco_client, ctx=ctx, **kwargs) if isinstance(result, list): ctl.io.print(output_formatter.convert_list(result)) else: ctl.io.print(output_formatter.convert_element(result)) # Add any extra arguments or options decorated on the handler_function if hasattr(handler_function, '__click_params__'): cmd.__click_params__.extend(handler_function.__click_params__) # Build final command cmd_kwargs = {} if not hasattr(handler_function, '__cmd_kwargs__') else handler_function.__cmd_kwargs__ if 'help' not in cmd_kwargs: help = f'Get {self.display_name}' cmd_kwargs['help'] = help if 'short_help' not in cmd_kwargs: cmd_kwargs['short_help'] = f'Get {self.display_name}' cmd = click.command(**cmd_kwargs)(cmd) return cmd
def upload_command(model_type: Type[Union[Optimization, Benchmark]]): result_type = ( OptimizationResult if issubclass(model_type, Optimization) else BenchmarkResult ) def base_function(**_): results_name = ( "optimization" if issubclass(model_type, Optimization) else "benchmark" ) results_path = os.path.join("analysis", f"{results_name}-results.json") results = result_type.parse_file(results_path).upload() with open(results_path, "w") as file: file.write(results.json()) model_string = ( "an optimization" if issubclass(model_type, Optimization) else "a benchmark" ) return generate_click_command( click.command( "upload", help=f"Upload the analysed results of {model_string} to the REST API.", ), [*_upload_options()], base_function, )
def make_command(function, phase): """Turn a function into click Command""" context_settings = dict(obj={"source": phase}) decorator = click.command(context_settings=context_settings) return decorator(function)
def get_command(self, ctx, name): """Get a callable command object.""" if name not in self.daemon_class.list_actions(): return None # The context object is a Daemon object daemon = ctx.obj def subcommand(debug=False): """Call a daemonocle action.""" if daemon.detach and debug: daemon.detach = False daemon.do_action(name) # Override the docstring for the function so that it shows up # correctly in the help output subcommand.__doc__ = daemon.get_action(name).__doc__ if name == 'start': # Add a --debug option for start subcommand = click.option( '--debug', is_flag=True, help='Do NOT detach and run in the background.' )(subcommand) # Make it into a click command subcommand = click.command( name, options_metavar=self.options_metavar)(subcommand) return subcommand
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 test_invalid_json_body_causes_non_zero_exit(monkeypatch): monkeypatch.setattr('cel.commands.run.build', click.command()(lambda: None)) runner = CliRunner() result = runner.invoke(run.run, ['-b', '{']) assert result.exit_code != 0
def generate_script_input_form_cli_interface(script_db_model): """Generates a command-line interface from for sql_alchemy class representing a script. Parameters ---------- script_db_model : sqlalchemy classes sqlalchemy class representing script. Returns ------- command : click.core.Command Instance of command class of click. To invoke input interface use: if __name__ == '__main__': command() """ wtform_instance = generate_script_wtform_class_instance(script_db_model) # TODO: since we have a form object we can create one more # decorator to automatically validate the input to the function # this way we can have the validation also in the command line # interface and not only in the web UI. command = wtform_instance.actions['main'] for input_field in wtform_instance: command = click.argument(input_field.name)(command) command = click.command()(command) return command
def decorator(f): # Need to add options in reverse order than f's args. # CLI hyperparameters that belong to the wrapped function. # See https://click.palletsprojects.com/en/7.x/advanced/#forwarding-unknown-options opts = click.argument("train_args", nargs=-1, type=click.UNPROCESSED)(f) for channel in channels[::-1]: opts = click.option( f"--{channel}", default=os.environ.get("SM_CHANNEL_{channel.upper()}", os.path.join(channel_prefix, channel)), help=f"Where to read input channel {channel}", type=Path, )(opts) opts = click.option( "--output-data-dir", default=os.environ.get("SM_OUTPUT_DATA_DIR", output), help="Where to output additional artifacts", type=Path, )(opts) opts = click.option( "--model-dir", default=os.environ.get("SM_MODEL_DIR", model), help="Where to output model artifacts", type=Path, )(opts) return click.command( context_settings={"ignore_unknown_options": True})(opts)
def wrapper(*args, **kwargs): g = click.command()( click.option( '-c', '--config', help='additional configuration file', multiple=True, is_eager=True, expose_value=False, callback=_update_settings, type=click.Path(exists=True))(f)) return g(*args, **kwargs)
def shell(name=None, **attrs): """Instantiates a new Shell instance, using the MultiCommandShell class as the default. Functions similar to @click.command(). Use this decorator on your top-level command in your Click project """ attrs.setdefault('cls', MultiCommandShell) return click.command(name, isShell=True, **attrs)
def command_wrapper(*cargs): func = cargs[0] command = click.command( kwargs.pop('name', func.__name__.lower()), kwargs.pop('cls', Command), **kwargs )(func) command.__doc__ = func.__doc__ iregister(command) return command
def decorator(f): if 'name' not in kwargs and f.__name__.startswith(group_name): kw = kwargs.copy() kw.setdefault('name', f.__name__[len(group_name):]) else: kw = kwargs cmd = click.command(*args, **kw)(f) self.add_command(cmd) return cmd
def make_command_from_function(function, options, help_text=None): if help_text: function.__doc__ = help_text function = click.command()(function) for name, option in options.items(): function = click.option(name, **option)(function) return function
def command(*args, **kwargs): """Make Click commands Cloudify specific This exists purely for aesthetical reasons, otherwise Some decorators are called `@click.something` instead of `@cfy.something` """ kwargs.setdefault('cls', CommandWithLoggers) return click.command(*args, **kwargs)
def make_command_from_string(code, cmd_context, options, help_text=None): def _command(**kwargs): exec (code, cmd_context, kwargs) if help_text: _command.__doc__ = help_text _command = click.command()(_command) for name, option in options.items(): _command = click.option(name, **option)(_command) return _command
def get_click_client(app: App) -> Callable: @click.group(invoke_without_command=True, help='API Star') @click.option('--version', is_flag=True, help='Display the `apistar` version number.') @click.pass_context def client(ctx: click.Context, version: bool) -> None: if ctx.invoked_subcommand is not None: return if version: from apistar import __version__ click.echo(__version__) else: click.echo(ctx.get_help()) for command in app.commands: command_signature = inspect.signature(command) for param in reversed(list(command_signature.parameters.values())): name = param.name.replace('_', '-') annotation = param.annotation kwargs = {} if hasattr(annotation, 'default'): kwargs['default'] = annotation.default if hasattr(annotation, 'description'): kwargs['help'] = annotation.description if issubclass(annotation, (bool, schema.Boolean)): kwargs['is_flag'] = True kwargs['default'] = False elif hasattr(annotation, 'choices'): kwargs['type'] = click.Choice(annotation.choices) elif hasattr(annotation, 'native_type'): kwargs['type'] = annotation.native_type elif annotation is inspect.Signature.empty: kwargs['type'] = str else: kwargs['type'] = annotation if 'default' in kwargs: name = '--%s' % param.name.replace('_', '-') option = click.option(name, **kwargs) command = option(command) else: kwargs.pop('help', None) argument = click.argument(param.name, **kwargs) command = argument(command) cmd_wrapper = click.command(help=command.__doc__) command = cmd_wrapper(command) client.add_command(command) return client
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 build_command(name, func): args, varargs, keywords, defaults = inspect.getargspec(func) args = args if args else list() defaults = defaults if defaults else list() if varargs is not None or keywords is not None: raise RuntimeError('Cannot build CLI for function with kwargs or ' 'varags.') if len(args) != len(defaults): raise RuntimeError('Cannot build CLI for function with argument ' 'without default values.') for arg, default in reversed(zip(args, defaults)): func = click.option('--'+arg, type=_get_type(default), default=default)(func) return click.command(name)(func)
def decorator(f): namespace = f.__module__.rsplit(".", 1)[1] name = args[0] if args else kwargs.get("name", f.__name__.lower()) # XXX: hack for handling commands without namespaces (root) if namespace == "root" or "root" in kwargs: new_name = "%s" % name kwargs.pop("root", None) else: new_name = "%s %s" % (namespace, name) kwargs["name"] = new_name _args = args[1:] if args else args cmd = click.command(*_args, **kwargs)(f) self.add_command(cmd) return cmd
def decorator(f): namespace = f.__module__.rsplit('.', 1)[1] name = args[0] if args else kwargs.get('name', f.__name__.lower()) # XXX: hack for handling commands without namespaces (root) if namespace == 'global' or 'root' in kwargs: new_name = '%s' % name kwargs.pop('root', None) else: new_name = '%s %s' % (namespace, name) kwargs['name'] = new_name _args = args[1:] if args else args cmd = click.command(*_args, **kwargs)(f) self.add_command(cmd) return cmd
def filterable_command(fn): decorators = [ click.option('--year_gt', type=int), click.option('--year_lt', type=int), click.option('--rating_gt', type=float), click.option('--rating_lt', type=float), click.command() ] command = fn for decorator in decorators: command = decorator(command) return command
def _make_command(cmd_name): cmd_class = getattr(frontend, re.sub(r'_(js|react)$', '', cmd_name)) cmd = click.command(cmd_name)(wrap_distutils_command(cmd_class)) for opt, short_opt, description in cmd_class.user_options: long_opt_name = opt.rstrip('=') var_name = long_opt_name.replace('-', '_') opts = ['--' + long_opt_name] if short_opt: opts.append('-' + short_opt) default = DEFAULT_OPTIONS.get(cmd_name, {}).get(var_name) is_flag = not opt.endswith('=') cmd = click.option(*(opts + [var_name]), is_flag=is_flag, default=default, help=description)(cmd) return cmd
def with_cli_args(func): ''' A decorator helping with using click with standalone_mode turned off. ''' getter_cmd = click.command(context_settings={ 'allow_extra_args': True, 'ignore_unknown_options': True, })(args_getter) getter_cmd.params.extend(func.__click_params__) @wraps(func) def wrapper(*args, **kwargs): kwargs.update( getter_cmd(standalone_mode=False) ) return func(*args, **kwargs) return wrapper
def __call__(self, func): module = sys.modules[func.__module__] # Get the command name as Django expects it self.name = func.__module__.rsplit(".", 1)[-1] # Build the click command decorators = [click.command(name=self.name, cls=self.cls, **self.kwargs)] + self.get_params(self.name) for decorator in reversed(decorators): func = decorator(func) # Django expects the command to be callable (it instantiates the class # pointed at by the `Command` module-level property)... # ...let's make it happy. module.Command = lambda: func return func
def decorator(fn): fn = click.option( '-v', '--verbosity', type=click.Choice([0, 1, 2, 3]), default=1, help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output', )(fn) fn = click.option( '--pythonpath', help='A directory to add to the Python path, e.g. "/home/orunprojects/myproject".', )(fn) fn = click.option( '--database', default=DEFAULT_DB_ALIAS, help='Nominates a database to create. Defaults to the "default" database.', )(fn) return click.command(name=name, cls=cls, **attrs)(fn)
command.finalize_options() command.run() return _wrapper cmd_list = ['init_catalog', 'extract_messages', 'update_catalog'] cmd_list += [cmd + '_js' for cmd in cmd_list] cmd_list.append('compile_catalog') for cmd_name in cmd_list: cmd_class = getattr(frontend, re.sub(r'_js$', '', cmd_name)) cmd = click.command(cmd_name)(wrap_distutils_command(cmd_class)) for opt, short_opt, description in cmd_class.user_options: long_opt_name = opt.rstrip('=') var_name = long_opt_name.replace('-', '_') opts = ['--' + long_opt_name] if short_opt: opts.append('-' + short_opt) default = DEFAULT_OPTIONS.get(cmd_name, {}).get(var_name) is_flag = not opt.endswith('=') cmd = click.option(*(opts + [var_name]), is_flag=is_flag, default=default, help=description)(cmd) cli.add_command(cmd)
def group(name=None, **attrs): attrs.setdefault('cls', UnSortedGroup) return click.command(name, **attrs)
def _sort_by(thing): return not getattr(thing, "_always_sorts_first", False), sort_by(thing) contents = [ path_and_children for path in paths or (project.from_path(FilePath(".")),) for path_and_children in recurse(path=path, ls=ls) ] for line in output(contents, sort_by=_sort_by): stdout.write(line) stdout.write("\n") I_hate_everything = [ click.command(context_settings=dict(help_option_names=["-h", "--help"])), click.version_option(version=__version__, prog_name="l"), click.option( "-1", "--one-per-line", "output", flag_value=core.one_per_line, help="Force output to be one entry per line. " "Note that unlike ls, when recursively listing directories, " "also forces output to not be grouped by subdirectory.", ), click.option( "--many-per-line", "output", flag_value=core.columnized, help="Show human-readable, labelled output.", ), click.option( "--tree", "output",
def command(f): return ApplicativeCommand(click.command()(f))
def config_group(name=None, **attrs): attrs.setdefault('cls', ConfigGroup) return click.command(name, **attrs)
def command(name=None, cls=GroupableOptionCommand, **attrs): return click.command(name, cls, **attrs)