Python click.Group() Examples

The following are 30 code examples of click.Group(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module click , or try the search function .
Example #1
Source File: register_commands_hook.py    From flask-unchained with MIT License 6 votes vote down vote up
def get_bundle_command_groups(self, bundle: Bundle) -> Dict[str, click.Group]:
        command_groups = {}
        module_found = False
        for b in bundle._iter_class_hierarchy():
            for module in self.import_bundle_modules(b):
                module_found = True
                command_groups.update(
                    self._collect_from_package(module, self.is_click_group)
                )

        groups = {}
        for name in getattr(bundle, 'command_group_names', [bundle.name]):
            try:
                groups[name] = command_groups[name]
            except KeyError as e:
                if module_found and not bundle.is_single_module:
                    warn(f'WARNING: Found a commands module for the {bundle.name} '
                         f'bundle, but there was no command group named {e.args[0]}'
                         f' in it. Either create one, or customize the bundle\'s '
                         f'`command_group_names` class attribute.')
                continue
        return groups 
Example #2
Source File: odin.py    From ODIN with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_command(self,ctx,cmd_name):
        """
        Allows commands to be called by their first unique character
            :param ctx: Context information from click
            :param cmd_name: Calling command name
            :return:
        """
        command = click.Group.get_command(self,ctx,cmd_name)
        if command is not None:
            return command
        matches = [x for x in self.list_commands(ctx)
                   if x.startswith(cmd_name)]
        if not matches:
            return None
        elif len(matches) == 1:
            return click.Group.get_command(self,ctx,matches[0])
        ctx.fail("Too many matches: %s" % ", ".join(sorted(matches)))


# That's right, we support -h and --help! Not using -h for an argument like 'host'! ;D 
Example #3
Source File: cli.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def list_commands(self, ctx):
        self._load_plugin_commands()

        # The commands available is the list of both the application (if
        # available) plus the builtin commands.
        rv = set(click.Group.list_commands(self, ctx))
        info = ctx.ensure_object(ScriptInfo)
        try:
            rv.update(info.load_app().cli.list_commands(ctx))
        except Exception:
            # Here we intentionally swallow all exceptions as we don't
            # want the help page to break if the app does not exist.
            # If someone attempts to use the command we try to create
            # the app again and this will give us the error.
            pass
        return sorted(rv) 
Example #4
Source File: grapher.py    From ODIN with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_command(self,ctx,cmd_name):
        """
        Allows commands to be called by their first unique character
            :param ctx: Context information from click
            :param cmd_name: Calling command name
            :return:
        """
        command = click.Group.get_command(self,ctx,cmd_name)
        if command is not None:
            return command
        matches = [x for x in self.list_commands(ctx)
                   if x.startswith(cmd_name)]
        if not matches:
            return None
        elif len(matches) == 1:
            return click.Group.get_command(self,ctx,matches[0])
        ctx.fail("Too many matches: %s" % ", ".join(sorted(matches)))


# That's right, we support -h and --help! Not using -h for an argument like 'host'! ;D 
Example #5
Source File: cli.py    From recruit with Apache License 2.0 6 votes vote down vote up
def list_commands(self, ctx):
        self._load_plugin_commands()

        # The commands available is the list of both the application (if
        # available) plus the builtin commands.
        rv = set(click.Group.list_commands(self, ctx))
        info = ctx.ensure_object(ScriptInfo)
        try:
            rv.update(info.load_app().cli.list_commands(ctx))
        except Exception:
            # Here we intentionally swallow all exceptions as we don't
            # want the help page to break if the app does not exist.
            # If someone attempts to use the command we try to create
            # the app again and this will give us the error.
            # However, we will not do so silently because that would confuse
            # users.
            traceback.print_exc()
        return sorted(rv) 
Example #6
Source File: cli.py    From jbox with MIT License 6 votes vote down vote up
def list_commands(self, ctx):
        self._load_plugin_commands()

        # The commands available is the list of both the application (if
        # available) plus the builtin commands.
        rv = set(click.Group.list_commands(self, ctx))
        info = ctx.ensure_object(ScriptInfo)
        try:
            rv.update(info.load_app().cli.list_commands(ctx))
        except Exception:
            # Here we intentionally swallow all exceptions as we don't
            # want the help page to break if the app does not exist.
            # If someone attempts to use the command we try to create
            # the app again and this will give us the error.
            pass
        return sorted(rv) 
Example #7
Source File: cli.py    From tmt with MIT License 6 votes vote down vote up
def get_command(self, context, cmd_name):
        """ Allow command shortening """
        # Backward-compatible 'test convert' (just temporary for now FIXME)
        cmd_name = cmd_name.replace('convert', 'import')
        # Support both story & stories
        cmd_name = cmd_name.replace('story', 'stories')
        found = click.Group.get_command(self, context, cmd_name)
        if found is not None:
            return found
        matches = [command for command in self.list_commands(context)
                   if command.startswith(cmd_name)]
        if not matches:
            return None
        elif len(matches) == 1:
            return click.Group.get_command(self, context, matches[0])
        context.fail('Did you mean {}?'.format(
            listed(sorted(matches), join='or')))

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#  Common Options
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
Example #8
Source File: leanproject.py    From mathlib-tools with Apache License 2.0 6 votes vote down vote up
def command(self, *args, **kwargs):
        """Behaves the same as `click.Group.command()` except if passed
        a list of names, all after the first will be aliases for the first.
        """
        def decorator(f):
            if args and isinstance(args[0], list):
                _args = [args[0][0]] + list(args[1:])
                for alias in args[0][1:]:
                    cmd = super(CustomMultiCommand, self).command(
                        alias, *args[1:], **kwargs)(f)
                    cmd.short_help = "Alias for '{}'".format(_args[0])
            else:
                _args = args
            cmd = super(CustomMultiCommand, self).command(
                *_args, **kwargs)(f)
            return cmd

        return decorator 
Example #9
Source File: GoReport.py    From Goreport with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_command(self, ctx, cmd_name):
        """
        Allows commands to be called by their first unique character
        :param ctx: Context information from click
        :param cmd_name: Calling command name
        :return:
        """
        rv = click.Group.get_command(self, ctx, cmd_name)
        if rv is not None:
            return rv
        matches = [x for x in self.list_commands(ctx) if x.startswith(cmd_name)]
        if not matches:
            return None
        elif len(matches) == 1:
            return click.Group.get_command(self, ctx, matches[0])
        ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))


# Create the help option for CLICK 
Example #10
Source File: cli.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def list_commands(self, ctx):
        self._load_plugin_commands()

        # The commands available is the list of both the application (if
        # available) plus the builtin commands.
        rv = set(click.Group.list_commands(self, ctx))
        info = ctx.ensure_object(ScriptInfo)
        try:
            rv.update(info.load_app().cli.list_commands(ctx))
        except Exception:
            # Here we intentionally swallow all exceptions as we don't
            # want the help page to break if the app does not exist.
            # If someone attempts to use the command we try to create
            # the app again and this will give us the error.
            # However, we will not do so silently because that would confuse
            # users.
            traceback.print_exc()
        return sorted(rv) 
Example #11
Source File: __main__.py    From passpy with GNU General Public License v3.0 6 votes vote down vote up
def get_command(self, ctx, cmd_name):
        """Allow aliases for commands.
        """
        if cmd_name == 'list':
            cmd_name = 'ls'
        elif cmd_name == 'search':
            cmd_name = 'find'
        elif cmd_name == 'gen':
            cmd_name = 'generate'
        elif cmd_name == 'add':
            cmd_name = 'insert'
        elif cmd_name in ['remove', 'delete']:
            cmd_name = 'rm'
        elif cmd_name == 'rename':
            cmd_name = 'mv'
        elif cmd_name == 'copy':
            cmd_name = 'cp'

        # TODO(benedikt) Figure out how to make 'show' the default
        # command and pass cmd_name as the first argument.
        rv = click.Group.get_command(self, ctx, cmd_name)
        if rv is not None:
            return rv 
Example #12
Source File: cli.py    From scylla with Apache License 2.0 6 votes vote down vote up
def list_commands(self, ctx):
        self._load_plugin_commands()

        # The commands available is the list of both the application (if
        # available) plus the builtin commands.
        rv = set(click.Group.list_commands(self, ctx))
        info = ctx.ensure_object(ScriptInfo)
        try:
            rv.update(info.load_app().cli.list_commands(ctx))
        except Exception:
            # Here we intentionally swallow all exceptions as we don't
            # want the help page to break if the app does not exist.
            # If someone attempts to use the command we try to create
            # the app again and this will give us the error.
            # However, we will not do so silently because that would confuse
            # users.
            traceback.print_exc()
        return sorted(rv) 
Example #13
Source File: ext.py    From sphinx-click with MIT License 6 votes vote down vote up
def _format_subcommand(command):
    """Format a sub-command of a `click.Command` or `click.Group`."""
    yield '.. object:: {}'.format(command.name)

    # click 7.0 stopped setting short_help by default
    if CLICK_VERSION < (7, 0):
        short_help = command.short_help
    else:
        short_help = command.get_short_help_str()

    if short_help:
        yield ''
        for line in statemachine.string2lines(short_help,
                                              tab_width=4,
                                              convert_whitespace=True):
            yield _indent(line) 
Example #14
Source File: test_formatter.py    From sphinx-click with MIT License 6 votes vote down vote up
def test_no_parameters(self):
        """Validate a `click.Group` with no parameters.

        This exercises the code paths for a group with *no* arguments, *no*
        options and *no* environment variables.
        """

        @click.group()
        def cli():
            """A sample command group."""
            pass

        ctx = click.Context(cli, info_name='cli')
        output = list(ext._format_command(ctx, show_nested=False))

        self.assertEqual(
            textwrap.dedent("""
        A sample command group.

        .. program:: cli
        .. code-block:: shell

            cli [OPTIONS] COMMAND [ARGS]...
        """).lstrip(), '\n'.join(output)) 
Example #15
Source File: cli.py    From Financial-Portfolio-Flask with MIT License 6 votes vote down vote up
def list_commands(self, ctx):
        self._load_plugin_commands()

        # The commands available is the list of both the application (if
        # available) plus the builtin commands.
        rv = set(click.Group.list_commands(self, ctx))
        info = ctx.ensure_object(ScriptInfo)
        try:
            rv.update(info.load_app().cli.list_commands(ctx))
        except Exception:
            # Here we intentionally swallow all exceptions as we don't
            # want the help page to break if the app does not exist.
            # If someone attempts to use the command we try to create
            # the app again and this will give us the error.
            pass
        return sorted(rv) 
Example #16
Source File: cli.py    From planespotter with MIT License 6 votes vote down vote up
def list_commands(self, ctx):
        self._load_plugin_commands()

        # The commands available is the list of both the application (if
        # available) plus the builtin commands.
        rv = set(click.Group.list_commands(self, ctx))
        info = ctx.ensure_object(ScriptInfo)
        try:
            rv.update(info.load_app().cli.list_commands(ctx))
        except Exception:
            # Here we intentionally swallow all exceptions as we don't
            # want the help page to break if the app does not exist.
            # If someone attempts to use the command we try to create
            # the app again and this will give us the error.
            pass
        return sorted(rv) 
Example #17
Source File: click.py    From flask-unchained with MIT License 6 votes vote down vote up
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) 
Example #18
Source File: register_commands_hook.py    From flask-unchained with MIT License 6 votes vote down vote up
def run_hook(self,
                 app: FlaskUnchained,
                 bundles: List[Bundle],
                 unchained_config: Optional[Dict[str, Any]] = None,
                 ) -> Dict[str, Union[click.Command, click.Group]]:
        """
        Discover CLI command and command groups from bundles and register them
        with the app.
        """
        commands = {}
        for bundle in bundles:
            command_groups = self.get_bundle_command_groups(bundle)
            commands.update(inherit_docstrings(command_groups, commands))
            commands.update(self.get_bundle_commands(bundle, command_groups))

        for name, command in commands.items():
            if name in app.cli.commands:
                warn(f'Command name conflict: "{name}" is taken.')
                continue
            app.cli.add_command(command, name)
        return commands 
Example #19
Source File: register_commands_hook.py    From flask-unchained with MIT License 6 votes vote down vote up
def get_bundle_commands(self,
                            bundle: Bundle,
                            command_groups: Dict[str, click.Group],
                            ) -> Dict[str, click.Command]:
        # when a command belongs to a group, we don't also want to register the command.
        # therefore we collect all the command names belonging to groups, and use that
        # in our is_click_command type-checking fn below
        group_command_names = set(itertools.chain.from_iterable(
            g.commands.keys() for g in command_groups.values()))

        def is_click_command(obj: Any) -> bool:
            return self.is_click_command(obj) and obj.name not in group_command_names

        commands = {}
        for b in bundle._iter_class_hierarchy():
            for module in self.import_bundle_modules(b):
                new = self._collect_from_package(module, is_click_command)
                commands.update(inherit_docstrings(new, commands))
        return commands 
Example #20
Source File: cli.py    From PhonePi_SampleServer with MIT License 6 votes vote down vote up
def list_commands(self, ctx):
        self._load_plugin_commands()

        # The commands available is the list of both the application (if
        # available) plus the builtin commands.
        rv = set(click.Group.list_commands(self, ctx))
        info = ctx.ensure_object(ScriptInfo)
        try:
            rv.update(info.load_app().cli.list_commands(ctx))
        except Exception:
            # Here we intentionally swallow all exceptions as we don't
            # want the help page to break if the app does not exist.
            # If someone attempts to use the command we try to create
            # the app again and this will give us the error.
            pass
        return sorted(rv) 
Example #21
Source File: main.py    From typer with MIT License 6 votes vote down vote up
def get_command(typer_instance: Typer) -> click.Command:
    if typer_instance._add_completion:
        click_install_param, click_show_param = get_install_completion_arguments()
    if (
        typer_instance.registered_callback
        or typer_instance.info.callback
        or typer_instance.registered_groups
        or len(typer_instance.registered_commands) > 1
    ):
        # Create a Group
        click_command = get_group(typer_instance)
        if typer_instance._add_completion:
            click_command.params.append(click_install_param)
            click_command.params.append(click_show_param)
        return click_command
    elif len(typer_instance.registered_commands) == 1:
        # Create a single Command
        click_command = get_command_from_info(typer_instance.registered_commands[0])
        if typer_instance._add_completion:
            click_command.params.append(click_install_param)
            click_command.params.append(click_show_param)
        return click_command
    assert False, "Could not get a command for this Typer instance"  # pragma no cover 
Example #22
Source File: cli.py    From planespotter with MIT License 5 votes vote down vote up
def command(self, *args, **kwargs):
        """This works exactly like the method of the same name on a regular
        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`
        unless it's disabled by passing ``with_appcontext=False``.
        """
        wrap_for_ctx = kwargs.pop('with_appcontext', True)
        def decorator(f):
            if wrap_for_ctx:
                f = with_appcontext(f)
            return click.Group.command(self, *args, **kwargs)(f)
        return decorator 
Example #23
Source File: cli.py    From jaide with GNU General Public License v2.0 5 votes vote down vote up
def get_command(self, ctx, cmd_name):
        """ Allow for partial commands. """
        rv = click.Group.get_command(self, ctx, cmd_name)
        if rv is not None:
            return rv
        matches = [x for x in self.list_commands(ctx)
                   if x.startswith(cmd_name)]
        if not matches:
            return None
        elif len(matches) == 1:
            return click.Group.get_command(self, ctx, matches[0])
        ctx.fail('Command ambiguous, could be: %s' %
                 ', '.join(sorted(matches))) 
Example #24
Source File: core.py    From diffy with Apache License 2.0 5 votes vote down vote up
def plugin_command_factory():
    """Dynamically generate plugin groups for all plugins, and add all basic command to it"""
    for p in plugins.all():
        plugin_name = p.slug
        help = f"Options for '{plugin_name}'"
        group = click.Group(name=plugin_name, help=help)
        for name, description in CORE_COMMANDS.items():
            callback = func_factory(p, name)
            pretty_opt = click.Option(
                ["--pretty/--not-pretty"], help="Output a pretty version of the JSON"
            )
            params = [pretty_opt]
            command = click.Command(
                name,
                callback=callback,
                help=description.format(plugin_name),
                params=params,
            )
            group.add_command(command)

        plugins_group.add_command(group) 
Example #25
Source File: click.py    From flask-unchained with MIT License 5 votes vote down vote up
def group(self, *args, **kwargs):
        """
        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.
        """
        kwargs.setdefault('cls', Group)
        return super().group(*args, **kwargs) 
Example #26
Source File: __init__.py    From realms-wiki with GNU General Public License v2.0 5 votes vote down vote up
def command(self, *args, **kwargs):
        """This works exactly like the method of the same name on a regular
        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`
        unless it's disabled by passing ``with_appcontext=False``.
        """
        wrap_for_ctx = kwargs.pop('with_appcontext', True)

        def decorator(f):
            if wrap_for_ctx:
                f = with_appcontext(f)
            return click.Group.command(self, *args, **kwargs)(f)
        return decorator 
Example #27
Source File: __init__.py    From realms-wiki with GNU General Public License v2.0 5 votes vote down vote up
def group(self, *args, **kwargs):
        """This works exactly like the method of the same name on a regular
        :class:`click.Group` but it defaults the group class to
        :class:`AppGroup`.
        """
        kwargs.setdefault('cls', AppGroup)
        return click.Group.group(self, *args, **kwargs) 
Example #28
Source File: _cli.py    From cider with MIT License 5 votes vote down vote up
def __init__(self, **attrs):
        click.Group.__init__(self, **attrs) 
Example #29
Source File: _cli.py    From cider with MIT License 5 votes vote down vote up
def get_command(self, ctx, command):
        aliases = {
            "delete": "remove-default",
            "ls": "list",
            "write": "set-default"
        }

        command = aliases.get(command, command)
        return click.Group.get_command(self, ctx, command) 
Example #30
Source File: __init__.py    From honeycomb with MIT License 5 votes vote down vote up
def __init__(self, folder, **kwargs):
        """Create a standard group, adding the folder parameter.

        :param folder: Path to folder with command .py files
        """
        click.Group.__init__(self, **kwargs)
        self.folder = os.path.join(cwd, folder)
        self.name = folder