Skip to content

Change order of commands #544

@isezen

Description

@isezen

Hello,

Is there any workaround that commands not to be sorted by default? I want them to be in order as I wish. I tried this stackoverflow solution. It works for click library but not for click-extra. I feel that they are sorted at somewhere else in click-extra code, but I couldn't find. My trial is as below:

import cloup as _cloup
import click_extra as _ce
from click_extra import *  # pylint: disable=W0401,W0614 # noqa:F401,F403


def _extra_params():
    return [
        _ce.colorize.HelpOption(),
    ]


class OrderedExtraGroup(_ce.commands.ExtraGroup):  # pylint: disable=R0901
    """Ordered ExtraGroup Class."""

    def __init__(self, *args, **kwargs):
        """Initialize."""
        self.help_priorities = {}
        super().__init__(*args, **kwargs)

    def get_help(self, ctx):
        """Get Help."""
        self.list_commands = self.list_commands_for_help
        return super().get_help(ctx)

    def list_commands_for_help(self, ctx):
        """Reorder the list of commands when listing the help."""
        commands = super().list_commands(ctx)
        return list(c[1] for c in sorted(
            (self.help_priorities.get(command, 1), command)
            for command in commands))

    def command(self, *args, **kwargs):
        """
        Ordered Command.

        Behave the same as `click.Group.command()` except capture a
        priority for listing command names in help.
        """
        help_priority = kwargs.pop('help_priority', 1)
        help_priorities = self.help_priorities

        def decorator(f):
            cmd = super(OrderedExtraGroup, self).command(*args, **kwargs)(f)
            help_priorities[cmd.name] = help_priority
            return cmd

        return decorator


group = _ce.decorators.decorator_factory(
    dec=_cloup.group,
    cls=OrderedExtraGroup,
    params=_extra_params,
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    ✨ enhancementNew feature or improvement to an existing one📚 documentationUpdate to non-code (readme, docstrings, typos, …)🙏 help wantedI can't do this alone and need contributors

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions