def cli_group(func): name = func.__name__.replace("_", "-") func = click.group()(func) cli.add_command(func, name=name) return func
def create_client_group(f, name=None): """Constructs a Client Group command. Given a reference to the Client class function, e.g. the @property Client.accounts or instance function Client.AccountsClient.networks(account_id), this constructs a click.Group. It passes the parent context and parent obj (e.g. the parent Client class instance), then sets a new ctx.obj that is the invocation of this command. We simply pass along any of *args and **kwargs down into the function. The `update_wrapper` is responsible for copying all the actual functions @option/@argument properties to the new function. Finally calling `group()(new_func)` creates the Group object and correctly parses all the parameters off the function. :param f: the class object to introspect :type f: `pureport_client.commands.CommandBase` :param name: the name of the group :type: name: str :returns: an instance of click Group :rtype: `click.core.Group` """ actual_f = f.fget if isinstance(f, property) else f @pass_obj @pass_context def new_func(ctx, obj, *args, **kwargs): ctx.obj = actual_f(obj, *args, **kwargs) new_func = update_wrapper(new_func, actual_f) return group(name)(new_func)
def decorator(f: FC) -> FC: if fake_tool: f = click.group( invoke_without_command=True, context_settings=dict( help_option_names=fake_tool.help_options), )(f) f = click.version_option( fake_tool.version, *fake_tool.version_options, message=fake_tool.version_banner, )(f) for arg, attrs in fake_tool.arguments.items(): if attrs is None: attrs = {} f = click.argument(arg, **attrs)(f) for param_decls, param_attrs in fake_tool.options.items(): if isinstance(param_decls, str): param_decls = (param_decls, ) if param_attrs is None: param_attrs = dict(is_flag=True) elif isinstance(param_attrs, list): param_attrs = dict(type=click.Choice(param_attrs)) elif isinstance(param_attrs, type): param_attrs = dict(type=param_attrs) f = click.option(*param_decls, **param_attrs)(f) return f
def click_group_ex(): """Return extended version of click.group().""" # Color coding used to group command types, documented only here as we may # decide to change them later. # green : (default) as sequence step # blue : molecule own command, not dependent on scenario # yellow : special commands, like full test sequence, or login return click.group( cls=HelpColorsGroup, # Workaround to disable click help line truncation to ~80 chars # https://github.com/pallets/click/issues/486 context_settings=dict(max_content_width=9999, color=should_do_markup()), help_headers_color="yellow", help_options_color="green", help_options_custom_colors={ "drivers": "blue", "init": "blue", "list": "blue", "matrix": "blue", "login": "******", "reset": "blue", "test": "bright_yellow", }, result_callback=result_callback, )
def _create_top_group(self, doc): def target(): pass target.__doc__ = doc target.__name__ = self._prog_name # attribute inspected by quick module context_settings = {} if self._config.help_option_names is not None: context_settings[ 'help_option_names'] = self._config.help_option_names blacklist = [] repl_cmd_name = 'repl' gui_cmd_name = 'gui' if self._config.enable_repl: blacklist.append(repl_cmd_name) if self._config.enable_gui: blacklist.append(gui_cmd_name) if self._config.enable_repl: target = self._register_repl(target, repl_cmd_name, blacklist) if self._config.enable_gui: target = self._register_gui(target, gui_cmd_name, blacklist) group = click.group(cls=self._get_group_class(), context_settings=context_settings)(target) if self._config.version_option is not None: group = click.version_option(**self._config.version_option)(group) return group
def cli_group(func): name = utils.parameter_name(func.__name__) func = click.group()(func) cli.add_command(func, name=name) return func
def group(name=None): """ Use the custom group that handle the Locale for python3 """ return click.group(name=name, context_settings=CLICK_CONTEXT_SETTINGS, cls=AgentGroup)
def group(name): """Allow to create a group with a default click context and a cls for click's `didyoueamn` without having to repeat it for every group. """ return click.group(name=name, context_settings=CLICK_CONTEXT_SETTINGS, cls=AliasedGroup)
def wrapped_f(*args): fn = f for option in reversed(global_options_list): fn = option(f) fn = click.group(context_settings={'help_option_names': ['-h', '--help']}, invoke_without_command=self.invoke_without_command)(fn) return fn
def group(name): """Allow to create a group with a default click context and a cls for click's `didyoueamn` without having to repeat it for every group. """ return click.group( name=name, context_settings=CLICK_CONTEXT_SETTINGS, cls=AliasedGroup)
def create_cli(cls, arguments, options=()): """ Simple cli for creating analyses. """ tantalus_api = dbclients.tantalus.TantalusApi() def create_single_analysis(jira_id, version, update=False, **args): cls.create_from_args(tantalus_api, jira_id, version, args, update=update) for arg_name in reversed(['jira_id', 'version'] + arguments): create_single_analysis = click.argument(arg_name)( create_single_analysis) for opt_name, default in reversed(options): create_single_analysis = click.option( '--' + opt_name, default=default)(create_single_analysis) def create_multiple_analyses(version, info_table, update=False): info = pd.read_csv(info_table) for idx, row in info.iterrows(): jira_id = row['jira_id'] args = {} for arg_name in arguments: args[arg_name] = row[arg_name] for opt_name, default in options: args[opt_name] = row.get(opt_name, default) try: cls.create_from_args(tantalus_api, jira_id, version, args, update=update) except KeyboardInterrupt: raise except: logging.exception(f'create analysis failed for {jira_id}') def analysis(): pass analysis = click.group()(analysis) create_single_analysis = analysis.command()(create_single_analysis) create_multiple_analyses = click.argument('info_table')( create_multiple_analyses) create_multiple_analyses = click.argument('version')( create_multiple_analyses) create_multiple_analyses = analysis.command()(create_multiple_analyses) analysis()
def ykman_group( connections=[SmartCardConnection, OtpConnection, FidoConnection], *args, **kwargs): if not isinstance(connections, list): connections = [connections] # Single type return click.group(cls=_YkmanGroup, *args, connections=connections, **kwargs)
def _create_group(self, name, doc): def target(): pass target.__doc__ = doc short_help = doc_to_short_help(doc) name_fixed = name.replace('_', '-').rstrip('-') return click.group(cls=self._get_group_class(), name=name_fixed, short_help=short_help)(target)
def inner(wrapped): wrapped = flask.cli.pass_script_info(wrapped) wrapped = click.option('--quiet', 'log_level', flag_value='quiet', help='Hide info level log messages')(wrapped) wrapped = click.option('--info', 'log_level', flag_value='info', default=True, help='Show info level log messages (default)')(wrapped) wrapped = click.option('--debug', 'log_level', flag_value='debug', help='Show debug level log messages')(wrapped) return click.group(cls=FlacGroup, create_app=lambda _: flac_app_cls.create(init_app=False))(wrapped)
def register_command( command: _MainCommandType[_ConfigType] ) -> click.core.Group: """Register main commands for the CLI program.""" config_type = _get_configuration_type(command) wrapper = _create_cli_option_wrapper(command, config_type) wrapper = click.group(chain=True)(wrapper) return wrapper
def main(): cli = types.FunctionType(dummy.func_code, {}) cli = click.group()(cli) proc_model(cli, package_name = "proton", hostenv = "OS_PROTON_HOST", portenv = "OS_PROTON_PORT", hostdefault = "127.0.0.1", portdefault = 2705) cli()
def main(): cli = types.FunctionType(dummy.func_code, {}) cli = click.group()(cli) proc_model(cli, package_name="proton", hostenv="OS_PROTON_HOST", portenv="OS_PROTON_PORT", hostdefault="127.0.0.1", portdefault=2705) cli()
def wrapper(f): dirpath = dirname(filepath) cli = click.group(**kwargs)(f) for fname in os.listdir(dirpath): modname, ext = splitext(fname) if modname.isidentifier() and not modname.startswith('_') and \ (ext == '' and exists(join(dirpath, fname, '__init__.py')) or ext == '.py'): submod = import_module('.' + modname, package) cli.add_command(submod.cli, modname.replace('_', '-')) return cli
def get_app_groups(): '''Get all app groups, put them in main group "frappe" since bench is designed to only handle that''' commands = dict() for app in get_apps(): app_commands = get_app_commands(app) if app_commands: commands.update(app_commands) ret = dict(frappe=click.group(name='frappe', commands=commands)(app_group)) return ret
def main(): cli = types.FunctionType(dummy.func_code, {}) cli = click.group()(cli) model_list = get_model_list() model = get_api_model(sys.argv, model_list) proc_model(cli, package_name="gluon", model_dir="models", api_model=model, hostenv="OS_PROTON_HOST", portenv="OS_PROTON_PORT", hostdefault=CONF.api.host, portdefault=CONF.api.port) cli()
def _load_cli_plugin_group(parent, group_name, group_help, dirpath_root): """ Load all CLI plugins in the specified directory. This function will iterate over all subdirectories in dirpath_root, loading all cli_plugin.py modules that are encountered. --- type: function args: parent: Click command group within which the plugins will live. group_name: The name used to invoke this group in the CLI. group_help: Help text for plugins. dirpath_root: Directory path containing the plugins. returns: None ... """ def no_op(): """ No-op callback function for generated CLI groups. """ pass group = click.group(name=group_name, help=group_help)(no_op) parent.add_command(group) # pylint: disable=E1101 filepath_plugin = os.path.join(dirpath_root, 'cli_plugin.py') if os.path.isfile(filepath_plugin): for subgroup in _gen_plugin_subgroups(dirpath_root): group.add_command(subgroup) # pylint: disable=E1101 for dirname in os.listdir(dirpath_root): for subgroup in _gen_plugin_subgroups(dirpath_root, dirname): group.add_command(subgroup) # pylint: disable=E1101
def decorator(f): kwargs.setdefault('cls', Group) grp = click.group(**kwargs)(f) if plugins is not None: for entry_point in plugins: try: grp.add_command(entry_point.load()) except Exception: # Catch this so a busted plugin doesn't take down the CLI. # Handled by registering a dummy command that does nothing # other than explain the error. grp.add_command(BrokenCommand(entry_point.name)) return grp
def group(name=None, cls=None, **attrs): """ A group allows a command to have subcommands attached. This is the most common way to implement nesting in Click. :param name: the name of the group (optional) :param commands: a dictionary of commands. :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 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. """ return click.group(name=name, cls=cls or Group, **attrs)
def create_click_cli(confi_entries: Dict[str, ConfiEntry], callback: Callable): cli = callback for key, entry in confi_entries.items(): option_kwargs = entry.get_cli_option_kwargs() # make the key fit cmd-style (i.e. kebab-case) adjusted_key = entry.key.lower().replace("_", "-") keys = [f"--{adjusted_key}", entry.key] # add flag if given (i.e '-t' option) if entry.flags is not None: keys.extend(entry.flags) # use lower case as the key, and as is (no prefix, and no case altering) as the name # see https://click.palletsprojects.com/en/7.x/options/#name-your-options cli = click.option(*keys, **option_kwargs)(cli) # pass context cli = click.pass_context(cli) # wrap in group cli = click.group(invoke_without_command=True)(cli) return cli
def camera(func=None, **attrs): """Helper click group command decorator""" if func is None: return functools.partial(camera, **attrs) @functools.wraps(func) def decorator(ctx, *args, **kwargs): ctx.obj['interface'] = func(*args, **kwargs) group = click.group(**attrs)(click.pass_context(decorator)) from .info import info from .acquire import acquire group.add_command(info) group.add_command(acquire) return group
def skeleton( name: str, version: str, auto_envvar_prefix: Optional[str] = None, cls: Any = None, commands: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> Any: '''Generates an skeleton group with version options included''' auto_envvar_prefix = auto_envvar_prefix if auto_envvar_prefix is not None else name.upper() if cls is None: cls = AdvancedGroup sensible_context_settings = DEFAULT_CONTEXT_SETTINGS sensible_context_settings['auto_envvar_prefix'] = auto_envvar_prefix obj = DefaultFactoryMunch(Munch) obj.prog_name = name obj.version = version obj.context_settings = sensible_context_settings context_settings = sensible_context_settings context_settings['auto_envvar_prefix'] = auto_envvar_prefix context_settings['obj'] = obj commands = commands if commands is not None else {} commands['completion'] = completion_cli commands['version'] = version_cmd return add_options( version_option( version=version, prog_name=name, version_color='green', prog_name_color='yellow', ), click.group( name=name, context_settings=context_settings, commands=commands, cls=cls, **kwargs, ), )
def __get__(self, obj, owner=None): # The recursion_depth stuff is to work around an oddity where # click.group() uses inspect.getdoc on the callback to get the # help text for the command if none was provided via help= # However, inspect.getdoc winds up calling the equivalent # of getattr(owner, callback.__name__), causing a recursion # back into this descriptior; in this case we just return the # wrapped callback itself self.recursion_depth += 1 if self.recursion_depth > 1: self.recursion_depth -= 1 return self.callback if self.callback is None: return self if owner is None: owner = type(obj) key = '_' + self.callback.__name__ # The Group instance is cached in the class dict group = owner.__dict__.get(key) if group is None: def callback(*args, **kwargs): return self.callback(owner, *args, **kwargs) update_wrapper(callback, self.callback) group = click.group(*self.args, cls=_ClassGroup, owner=owner, **self.kwargs)(callback) # Add commands to the group for command in self.commands: if isinstance(command, classgroup): command = command.__get__(None, owner) group.add_command(command) setattr(owner, key, group) self.recursion_depth -= 1 return group
def click_group_ex(): """Return extended version of click.group().""" # Color coding used to group command types, documented only here as we may # decide to change them later. # green : (default) as sequence step # blue : molecule own command, not dependent on scenario # yellow : special commands, like full test sequence, or login return click.group( cls=HelpColorsGroup, help_headers_color='yellow', help_options_color='green', help_options_custom_colors={ 'drivers': 'blue', 'init': 'blue', 'list': 'blue', 'matrix': 'blue', 'login': '******', 'test': 'bright_yellow', }, )
def make_click_group(): # print 'invoking make_cli_group' @click.option('--debug/--no-debug', default=False, help='Set to increase verbosity', show_default=True) @click.pass_context def _cli(ctx, debug, **kwargs): projects = collections.OrderedDict() for p_cls in all_services: projects[p_cls.name] = functools.partial(p_cls.project_from_click_context, ctx, **kwargs) ctx.obj['service_factories'] = projects ctx.obj['debug'] = debug all_services = services.list_all() decorated_cli = _cli for p_cls in all_services: for option in p_cls.make_click_options(): decorated_cli = option(decorated_cli) return click.group()(decorated_cli)
def click_group_ex(): """Return extended version of click.group().""" # Color coding used to group command types, documented only here as we may # decide to change them later. # green : (default) as sequence step # blue : molecule own command, not dependent on scenario # yellow : special commands, like full test sequence, or login return click.group( cls=HelpColorsGroup, help_headers_color="yellow", help_options_color="green", help_options_custom_colors={ "drivers": "blue", "init": "blue", "list": "blue", "matrix": "blue", "login": "******", "reset": "blue", "test": "bright_yellow", }, )
def root(config: Optional[Dict] = None, config_file: Optional[str] = None, basedir=None, **kwargs): """This decorator is used to create the kitipy RootCommand group. It loads the given config_file if provided or uses the given config parameter. The config_file parameter takes precedence over config. If no config is provided, it defaults to an empty config dict. This is generally what you want to call to declare the root of your task tree and use all of the kitipy features. Args: config (Optional[Dict]): Config used by kitipy. config_file (Optional[str]): File containing kitipy config. basedir (Optional[str]): The basedir where kitipy commands should be executed. If not provided, the current working directory will be used. **kwargs: Any other argument supported by click.group() decorator. Returns: Callable: The decorator to apply to the task function. """ if config_file is not None: config = load_config_file(config_file) if basedir is None: basedir = os.getcwd() if config_file is None and config is None: config = {} return click.group('root', cls=RootCommand, config=config, basedir=basedir, **kwargs)
def inner_decorator(f): f = click.group(*args, cls=GlobusCommandGroup, **kwargs)(f) f = common_options(f) return f
def group(name=None, **attrs): return click.group(name, **{'cls': GroupableOptionCommandGroup, **attrs})
def globus_main_func(f): f = click.group("globus", cls=TopLevelGroup)(f) f = common_options(f) f = shell_complete_option(f) f = print_completer_option(f) return f
def get_app_group(app): app_commands = get_app_commands(app) if app_commands: return click.group(name=app, commands=app_commands)(app_group)
def build_group(name, *commands): group = click.group(name)(_nop) for cmd in commands: group.add_command(cmd) return group