コード例 #1
0
def cli_group(func):
    name = func.__name__.replace("_", "-")
    func = click.group()(func)

    cli.add_command(func, name=name)

    return func
コード例 #2
0
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)
コード例 #3
0
 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
コード例 #4
0
ファイル: base.py プロジェクト: yemo-memeda/molecule
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,
    )
コード例 #5
0
ファイル: builder.py プロジェクト: gergelyk/python-kickoff
    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
コード例 #6
0
ファイル: main.py プロジェクト: swamireddy/ceph-lcm
def cli_group(func):
    name = utils.parameter_name(func.__name__)
    func = click.group()(func)

    cli.add_command(func, name=name)

    return func
コード例 #7
0
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)
コード例 #8
0
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)
コード例 #9
0
 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
コード例 #10
0
ファイル: cfy.py プロジェクト: cloudify-cosmo/cloudify-cli
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)
コード例 #11
0
        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
コード例 #12
0
    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()
コード例 #13
0
ファイル: util.py プロジェクト: maxthomas/yubikey-manager
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)
コード例 #14
0
ファイル: builder.py プロジェクト: gergelyk/python-kickoff
    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)
コード例 #15
0
ファイル: cli.py プロジェクト: rsyring/flac
 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)
コード例 #16
0
ファイル: cli.py プロジェクト: ROpdebee/Voyager
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
コード例 #17
0
ファイル: cli.py プロジェクト: GluonsAndProtons/gluon
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()
コード例 #18
0
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()
コード例 #19
0
 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
コード例 #20
0
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
コード例 #21
0
ファイル: bench_helper.py プロジェクト: ESS-LLP/frappe
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
コード例 #22
0
ファイル: cli.py プロジェクト: openstack/gluon
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()
コード例 #23
0
ファイル: cli.py プロジェクト: lfntac/ipv6
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()
コード例 #24
0
ファイル: cli.py プロジェクト: wtpayne/hiai
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
コード例 #25
0
ファイル: plugins.py プロジェクト: jhyun0919/ML-DL_jhyun
    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
コード例 #26
0
ファイル: plugins.py プロジェクト: vikasgoel2000/lambda-packs
    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
コード例 #27
0
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)
コード例 #28
0
ファイル: cli.py プロジェクト: shimont/opal
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
コード例 #29
0
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
コード例 #30
0
ファイル: core.py プロジェクト: AdrienPensart/click-skeleton
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,
        ),
    )
コード例 #31
0
ファイル: click.py プロジェクト: embray/Renewal
    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
コード例 #32
0
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',
        },
    )
コード例 #33
0
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)
コード例 #34
0
ファイル: base.py プロジェクト: qoreQyaS/molecule
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",
        },
    )
コード例 #35
0
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)
コード例 #36
0
ファイル: custom_group.py プロジェクト: tkuennen/globus-cli
 def inner_decorator(f):
     f = click.group(*args, cls=GlobusCommandGroup, **kwargs)(f)
     f = common_options(f)
     return f
コード例 #37
0
ファイル: custom_group.py プロジェクト: globus/globus-cli
 def inner_decorator(f):
     f = click.group(*args, cls=GlobusCommandGroup, **kwargs)(f)
     f = common_options(f)
     return f
コード例 #38
0
ファイル: cli.py プロジェクト: AlphaX-IBS/raiden
def group(name=None, **attrs):
    return click.group(name, **{'cls': GroupableOptionCommandGroup, **attrs})
コード例 #39
0
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
コード例 #40
0
ファイル: bench_helper.py プロジェクト: MaxMorais/frappe
def get_app_group(app):
	app_commands = get_app_commands(app)
	if app_commands:
		return click.group(name=app, commands=app_commands)(app_group)
コード例 #41
0
ファイル: cli.py プロジェクト: frederikhermans/focus
def build_group(name, *commands):
    group = click.group(name)(_nop)
    for cmd in commands:
        group.add_command(cmd)
    return group