Beispiel #1
0
    def similar_handle(section: str) -> None:
        """
        Try to use/suggest a similar handle if user misspelled it.

        :param section: The handle inputted by the user.
        """
        com_list, action = most_similar_command(section.lower(),
                                                {'general', 'pat', 'all'})
        # use best match
        if len(com_list) == 1 and action == 'use':
            print(
                f'[bold blue]Unknown handle {section}. Will use best match {com_list[0]}.\n'
            )
            ConfigCommand.handle_switcher().get(com_list[0],
                                                lambda: 'Invalid handle!')()
        # suggest best match
        elif len(com_list) == 1 and action == 'suggest':
            print(
                f'[bold blue]Unknown handle {section}. Did you mean {com_list[0]}?'
            )
            sys.exit(1)
            # multiple best matches
        elif len(com_list) > 1:
            nl = '\n'
            print(
                f'[bold red]Unknown handle \'{section}\'.\nMost similar handles are: [green]{nl}{nl.join(sorted(com_list))}'
            )
        else:
            # unknown handle and no best match found
            print(
                '[bold red]Unknown handle. [green]See cookietemple --help [red]for more information on valid handles'
            )
Beispiel #2
0
    def similar_handle(section: str) -> None:
        """
        Try to use/suggest a similar handle if user misspelled it.

        :param section: The handle inputted by the user.
        """
        com_list, action = most_similar_command(section.lower(),
                                                {"general", "pat", "all"})
        # use best match
        if len(com_list) == 1 and action == "use":
            print(
                f"[bold blue]Unknown handle {section}. Will use best match {com_list[0]}.\n"
            )
            ConfigCommand.handle_switcher().get(com_list[0],
                                                lambda: "Invalid handle!")()
        # suggest best match
        elif len(com_list) == 1 and action == "suggest":
            print(
                f"[bold blue]Unknown handle {section}. Did you mean {com_list[0]}?"
            )
            sys.exit(1)
            # multiple best matches
        elif len(com_list) > 1:
            nl = "\n"
            print(
                f"[bold red]Unknown handle '{section}'.\nMost similar handles are: [green]{nl}{nl.join(sorted(com_list))}"
            )
        else:
            # unknown handle and no best match found
            print(
                "[bold red]Unknown handle. [green]See cookietemple --help [red]for more information on valid handles"
            )
Beispiel #3
0
    def get_command(self, ctx, cmd_name):
        """
        Override the get_command of Click.
        If an unknown command is given, try to determine a similar command.
        If no similar command could´ve been found, exit with an error message.
        Else use the most similar command while printing a status message for the user.

        :param ctx: The given Click context for the group
        :param cmd_name: The command invoked with Click
        """
        rv = click.Group.get_command(self, ctx, cmd_name)
        if rv is not None:
            return rv
        sim_commands, action = most_similar_command(cmd_name, MAIN_COMMANDS)

        matches = [cmd for cmd in self.list_commands(ctx) if cmd in sim_commands]

        # no similar commands could be found
        if not matches:
            ctx.fail(click.style("Unknown command and no similar command was found!", fg="red"))
        elif len(matches) == 1 and action == "use":
            print(f"[bold red]Unknown command! Will use best match [green]{matches[0]}")
            return click.Group.get_command(self, ctx, matches[0])
        elif len(matches) == 1 and action == "suggest":
            ctx.fail(
                click.style("Unknown command! Did you mean ", fg="red") + click.style(f"{matches[0]}?", fg="green")
            )

        # a few similar commands were found, print a info message
        ctx.fail(
            click.style("Unknown command. Most similar commands were", fg="red")
            + click.style(f'{", ".join(sorted(matches))}', fg="red")
        )
def test_most_similar_command_pub(get_commands_with_similar_command_pub,
                                  get_all_valid_handles_as_set) -> None:
    """
    Test the most similar command for web (without any subdomain)
    """
    for com in get_commands_with_similar_command_pub:
        test_tuple = most_similar_command(com.lower(),
                                          get_all_valid_handles_as_set)
        assert test_tuple[0] == ['pub'] and test_tuple[1] == 'use'
Beispiel #5
0
 def handle_non_existing_command(self, handle: str, run_f: bool = False) -> None:
     """
     Handle the case, when an unknown handle was entered and try to find a similar handle.
     :param handle: The non existing handle
     :param run_f: Flag that indicates whether to run print to output or not (do not run in case of languages)
     """
     self.available_handles = load_available_handles()
     self.most_sim, self.action = most_similar_command(handle, self.available_handles)
     if run_f:
         self.print_console_output(handle)
def test_most_similar_command_cli(get_commands_with_similar_command_cli,
                                  get_all_valid_handles_as_set) -> None:
    """
    Test our most similar command suggestion (here: cli) if the user enters a domain/subdomain unknown to cookietemple.
    It should suggest a similar command within a certain range of similarity (e.g clo -> cli but not asd -> cli).
    """
    for com in get_commands_with_similar_command_cli:
        test_tuple = most_similar_command(com.lower(),
                                          get_all_valid_handles_as_set)
        assert test_tuple[0] == ['cli'] and test_tuple[1] == 'use'
def test_most_similar_command_pub_with_subdomain_and_language(get_commands_with_similar_command_pub_with_subdomain_and_language, get_all_valid_handles_as_set) \
      -> None:
    """
    This test the most similar command for cli with language specified.
    All is needed in the rare case if there are multiple similar handles.
    """
    for com in get_commands_with_similar_command_pub_with_subdomain_and_language:
        test_tuple = most_similar_command(com.lower(),
                                          get_all_valid_handles_as_set)
        assert all(handle in {'pub-thesis', 'pub-thesis-latex'}
                   for handle in test_tuple[0])
def test_most_similar_command_gui_with_language(
        get_commands_with_similar_command_gui_with_language,
        get_all_valid_handles_as_set) -> None:
    """
    Test the most similar command for cli with language specified.
    All is needed in the rare case if there are multiple similar handles.
    """
    for com in get_commands_with_similar_command_gui_with_language:
        test_tuple = most_similar_command(com.lower(),
                                          get_all_valid_handles_as_set)
        assert all(handle in {'gui-java'} for handle in test_tuple[0])
def test_most_similar_command_web_with_subdomain_and_language(
        get_commands_with_similar_command_web_with_subdomain_and_language,
        get_all_valid_handles_as_set) -> None:
    """
    This test the most similar command for cli with language specified.
    All is needed in the rare case if there are multiple similar handles.
    """
    for com in get_commands_with_similar_command_web_with_subdomain_and_language:
        test_tuple = most_similar_command(com.lower(),
                                          get_all_valid_handles_as_set)
        assert all(handle in {"web-website", "web-website-python"}
                   for handle in test_tuple[0])
Beispiel #10
0
    def handle_domain_or_language_only(self, handle: str,
                                       available_templates: dict) -> None:
        """
        Try to find a similar domain or treat handle as possible language
        :param handle: The handle inputted by the user
        :param available_templates: All available templates load from yml file as dict
        """
        # try to find a similar domain
        self.handle_non_existing_command(handle)
        # we found a similar handle matching a domain, use it (suggest it maybe later)
        if self.most_sim and self.action not in ("suggest", ""):
            self.print_console_output(handle)

        # input may be a language so try this
        templates_flatted: List[str] = []
        self.flatten_nested_dict(available_templates, templates_flatted)
        # load all available languages
        available_languages = TemplateInfo.load_available_languages(
            templates_flatted)
        # if handle exists as language in cookietemple output its available templates and exit with zero status
        if handle in available_languages:
            templates_to_print_ = [
                template for template in templates_flatted
                if handle in template[1]
            ]
            TemplateInfo.output_table(templates_to_print_, handle)

        # the handle does not match any domain/language; is there a similar language?
        else:
            # save domain values for later use
            domain_handle, domain_action = self.most_sim, self.action
            # try to find a similar language for instant use
            self.most_sim, self.action = most_similar_command(
                handle, available_languages)
            # use language if available
            if self.most_sim and self.action not in ("", "suggest"):
                self.print_console_output(handle)
            # try to suggest a similar domain handle
            elif domain_action == "suggest" and domain_handle:
                TemplateInfo.print_suggestion(handle, domain_handle)
            # try to suggest a similar language handle
            elif self.action == "suggest" and self.most_sim:
                TemplateInfo.print_suggestion(handle, self.most_sim)
            # we're done there is no similar handle
            else:
                TemplateInfo.non_existing_handle()
        sys.exit(0)