Skip to content

utils

Top level helpers

AliasedGroup

Click group allowing using prefix of command instead of the whole command

get_command(self, ctx, cmd_name)

Returns a command of which the given word is a subsequence

Source code in aicrowd/utils/utils.py
def get_command(self, ctx, cmd_name):
    """
    Returns a command of which the given word is a subsequence
    """
    rv = click.Group.get_command(self, ctx, cmd_name)

    if rv is not None:
        return rv

    matches = list(
        filter(
            lambda cmd_orig: is_subsequence(cmd_name, cmd_orig),
            self.list_commands(ctx),
        )
    )

    if not matches:
        return None

    if len(matches) == 1:
        return click.Group.get_command(self, ctx, matches[0])

    ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")
    return None

CommandWithExamples

Click command which extracts and properly displays usage examples

format_examples(self, _ctx, formatter)

Show examples separately, in their own section

Source code in aicrowd/utils/utils.py
def format_examples(self, _ctx, formatter):
    """
    Show examples separately, in their own section
    """
    try:
        examples_index = self.help.index("Examples:")
        formatter.write("\n")
        formatter.write(self.help[examples_index:])
        formatter.write("\n")
    except ValueError:
        # this command didn't provide examples
        pass

format_help(self, ctx, formatter)

Modified --help output to also include examples

Source code in aicrowd/utils/utils.py
def format_help(self, ctx, formatter):
    """
    Modified --help output to also include examples
    """
    self.format_usage(ctx, formatter)
    self.format_help_text(ctx, formatter)
    self.format_examples(ctx, formatter)
    self.format_options(ctx, formatter)
    self.format_epilog(ctx, formatter)

format_help_text(self, ctx, formatter)

Don't print 'Examples' as a part of help

Source code in aicrowd/utils/utils.py
def format_help_text(self, ctx, formatter):
    """
    Don't print 'Examples' as a part of help
    """
    if self.help:
        formatter.write_paragraph()
        with formatter.indentation():
            help_text = self.help.split("Examples:")[0]
            if self.deprecated:
                help_text += DEPRECATED_HELP_NOTICE
            formatter.write_text(help_text)
    elif self.deprecated:
        formatter.write_paragraph()
        with formatter.indentation():
            formatter.write_text(DEPRECATED_HELP_NOTICE)

exception_handler(f)

try/except wrapper for CLI function calls

Source code in aicrowd/utils/utils.py
def exception_handler(f):
    """
    try/except wrapper for CLI function calls
    """

    @wraps(f)
    def _exception_handler(*args, **kwargs):
        try:
            f(*args, **kwargs)
        except CLIException as e:
            if not e.message:  # covers both "" and None
                e.message = (
                    "An unknown error occured. Please set verbosity to check full logs."
                )

            click.echo(str(e))
            sys.exit(e.exit_code)
        except Exception as e:
            click.echo(click.style("An unexpected error occured!", fg="red"))
            print(str(e))
            click.echo(
                "To get more information, you can run this command with -v.\n"
                + "To increase level of verbosity, you can go upto -vvvvv"
            )
            sys.exit(UNKNOWN_ERROR)

    return _exception_handler

is_subsequence(s1, s2)

returns whether s1 is a subsequence of s2 or not

Parameters:

Name Type Description Default
s1 str

probable subsequence of s2

required
s2 str

string

required

Returns:

Type Description
bool

is s1 a subsequence of s2

Source code in aicrowd/utils/utils.py
def is_subsequence(s1: str, s2: str) -> bool:
    """
    returns whether s1 is a subsequence of s2 or not

    Args:
        s1: probable subsequence of s2
        s2: string

    Returns:
        is s1 a subsequence of s2
    """
    i, j = 0, 0
    n1, n2 = len(s1), len(s2)

    while i < n1 and j < n2:
        # if matched, advance in both
        if s1[i] == s2[j]:
            i += 1

        # otherwise, try next char in s2
        j += 1

    # was s1 fully matched?
    return i == n1