Ejemplo n.º 1
0
    def print_error(self):
        from azure.cli.core.azlogging import CommandLoggerContext
        from azure.cli.core.style import print_styled_text
        with CommandLoggerContext(logger):
            # print error message
            logger.error(self.error_msg)

            # print exception trace if there is
            if self.exception_trace:
                logger.exception(self.exception_trace)

        # print recommendations to action
        if self.recommendations:
            for recommendation in self.recommendations:
                print(recommendation, file=sys.stderr)

        if self.aladdin_recommendations:
            print('\nExamples from AI knowledge base:', file=sys.stderr)
            for recommendation, description in self.aladdin_recommendations:
                print_styled_text(recommendation, file=sys.stderr)
                print_styled_text(description, file=sys.stderr)
Ejemplo n.º 2
0
def _issue_config_cleanup_warning(delete_cert, delete_keys, is_arc, cert_file,
                                  relay_info_path, ssh_client_folder):
    if delete_cert:
        # pylint: disable=broad-except
        try:
            expiration = get_certificate_start_and_end_times(
                cert_file, ssh_client_folder)[1]
            expiration = expiration.strftime("%Y-%m-%d %I:%M:%S %p")
            print_styled_text((
                Style.SUCCESS,
                f"Generated SSH certificate {cert_file} is valid until {expiration} in local time."
            ))
        except Exception as e:
            logger.warning(
                "Couldn't determine certificate expiration. Error: %s", str(e))

    if delete_keys or delete_cert or is_arc:
        # Warn users to delete credentials once config file is no longer being used.
        # If user provided keys, only ask them to delete the certificate.
        if is_arc:
            relay_info_filename = os.path.basename(relay_info_path)
            if delete_keys and delete_cert:
                path_to_delete = f"{os.path.dirname(cert_file)} contains"
                items_to_delete = f" (id_rsa, id_rsa.pub, id_rsa.pub-aadcert.pub, {relay_info_filename})"
            elif delete_cert:
                path_to_delete = f"{cert_file} and {relay_info_path} contain"
                items_to_delete = ""
            else:
                path_to_delete = f"{relay_info_path} contains"
                items_to_delete = ""
        else:
            path_to_delete = f"{os.path.dirname(cert_file)} contains"
            items_to_delete = " (id_rsa, id_rsa.pub, id_rsa.pub-aadcert.pub)"
            if not delete_keys:
                path_to_delete = f"{cert_file} contains"
                items_to_delete = ""

        logger.warning(
            "%s sensitive information%s. Please delete it once you no longer "
            "need this config file.", path_to_delete, items_to_delete)
Ejemplo n.º 3
0
    def show_help(self, cli_name, nouns, parser, is_group):
        self.update_loaders_with_help_file_contents(nouns)

        delimiters = ' '.join(nouns)
        help_file = self.command_help_cls(self, delimiters, parser) if not is_group \
            else self.group_help_cls(self, delimiters, parser)
        help_file.load(parser)
        if not nouns:
            help_file.command = ''
        else:
            AzCliHelp.update_examples(help_file)
        self._print_detailed_help(cli_name, help_file)
        from azure.cli.core.util import show_updates_available
        show_updates_available(new_line_after=True)
        show_link = self.cli_ctx.config.getboolean('output',
                                                   'show_survey_link', True)
        from azure.cli.core.commands.constants import (SURVEY_PROMPT_STYLED,
                                                       UX_SURVEY_PROMPT_STYLED)
        from azure.cli.core.style import print_styled_text
        if show_link:
            print_styled_text(SURVEY_PROMPT_STYLED)
            if not nouns:
                print_styled_text(UX_SURVEY_PROMPT_STYLED)
Ejemplo n.º 4
0
def _give_recommend_commands(cmd, idx, rec):
    index_str = "[" + str(idx) + "] "
    command_item = "az " + rec['command']
    no_arguments = 'arguments' not in rec or not rec['arguments'] or \
                   (len(rec['arguments']) == 1 and rec['arguments'][0] == '')
    if no_arguments:
        _feed_arguments_from_sample(rec)

    if 'arguments' in rec and cmd.cli_ctx.config.getboolean('next', 'show_arguments', fallback=False):
        command_item = "{} {}".format(command_item, ' '.join(rec['arguments']))
    print_styled_text([(Style.ACTION, index_str), (Style.PRIMARY, command_item)])

    if 'reason' in rec:
        reason = rec['reason']
    else:
        reason = _get_cmd_help_from_ctx(rec['command'], "")
        if 'usage_condition' in rec and rec['usage_condition']:
            reason = reason + " (" + rec['usage_condition'] + ")"

    if reason:
        space_padding = re.sub('.', ' ', index_str)
        print_styled_text([(Style.SECONDARY, space_padding + get_title_case(reason) + "\n")])
    else:
        print()
Ejemplo n.º 5
0
    def show_version(self):
        from azure.cli.core.util import get_az_version_string, show_updates
        from azure.cli.core.commands.constants import SURVEY_PROMPT_STYLED, UX_SURVEY_PROMPT_STYLED
        from azure.cli.core.style import print_styled_text

        ver_string, updates_available_components = get_az_version_string()
        print(ver_string)
        show_updates(updates_available_components)

        show_link = self.config.getboolean('output', 'show_survey_link', True)
        if show_link:
            print_styled_text()
            print_styled_text(SURVEY_PROMPT_STYLED)
            print_styled_text(UX_SURVEY_PROMPT_STYLED)
Ejemplo n.º 6
0
    def test_print_styled_text(self, mock_format_styled_text, mock_print):
        # Just return the original input
        mock_format_styled_text.side_effect = lambda obj: obj

        # Default to stderr
        print_styled_text("test text")
        mock_print.assert_called_with("test text", file=sys.stderr)

        # No args
        print_styled_text()
        mock_print.assert_called_with(file=sys.stderr)

        # Multiple args
        print_styled_text("test text 1", "test text 2")
        mock_print.assert_called_with("test text 1", "test text 2", file=sys.stderr)
Ejemplo n.º 7
0
def demo_style(cmd, theme=None):  # pylint: disable=unused-argument
    from azure.cli.core.style import Style, print_styled_text, format_styled_text
    if theme:
        format_styled_text.theme = theme
    print_styled_text("[How to call print_styled_text]")
    # Print an empty line
    print_styled_text()
    # Various methods to print
    print_styled_text("- Print using a str")
    print_styled_text("- Print using multiple", "strs")
    print_styled_text((Style.PRIMARY, "- Print using a tuple"))
    print_styled_text((Style.PRIMARY, "- Print using multiple"),
                      (Style.IMPORTANT, "tuples"))
    print_styled_text([(Style.PRIMARY, "- Print using a "),
                       (Style.IMPORTANT, "list")])
    print_styled_text([(Style.PRIMARY, "- Print using multiple")],
                      [(Style.IMPORTANT, "lists")])
    print_styled_text()

    print_styled_text("[Available styles]\n")
    placeholder = '████ {:8s}: {}\n'
    styled_text = [
        (Style.PRIMARY, placeholder.format("White", "Primary text color")),
        (Style.SECONDARY, placeholder.format("Grey", "Secondary text color")),
        (Style.IMPORTANT, placeholder.format("Magenta",
                                             "Important text color")),
        (Style.ACTION,
         placeholder.format(
             "Blue",
             "Commands, parameters, and system inputs (White in legacy powershell terminal)"
         )),
        (Style.HYPERLINK, placeholder.format("Cyan", "Hyperlink")),
        (Style.ERROR, placeholder.format("Red", "Error message indicator")),
        (Style.SUCCESS, placeholder.format("Green",
                                           "Success message indicator")),
        (Style.WARNING,
         placeholder.format("Yellow", "Warning message indicator")),
    ]
    print_styled_text(styled_text)

    print_styled_text("[interactive]\n")
    # NOTE! Unicode character ⦾ ⦿ will most likely not be displayed correctly
    styled_text = [
        (Style.ACTION, "?"),
        (Style.PRIMARY, " Select a SKU for your app:\n"),
        (Style.PRIMARY, "⦾ Free            "),
        (Style.SECONDARY,
         "Dev/Test workloads: 1 GB memory, 60 minutes/day compute\n"),
        (Style.PRIMARY, "⦾ Basic           "),
        (Style.SECONDARY,
         "Dev/Test workloads: 1.75 GB memory, monthly charges apply\n"),
        (Style.PRIMARY, "⦾ Standard        "),
        (Style.SECONDARY,
         "Production workloads: 1.75 GB memory, monthly charges apply\n"),
        (Style.ACTION, "⦿ Premium         "),
        (Style.SECONDARY,
         "Production workloads: 3.5 GB memory, monthly charges apply\n"),
    ]
    print_styled_text(styled_text)

    print_styled_text("[progress report]\n")
    # NOTE! Unicode character ✓ will most likely not be displayed correctly
    styled_text = [
        (Style.SUCCESS, '(✓) Done: '),
        (Style.PRIMARY, "Creating a resource group for myfancyapp\n"),
        (Style.SUCCESS, '(✓) Done: '),
        (Style.PRIMARY,
         "Creating an App Service Plan for myfancyappplan on a "),
        (Style.IMPORTANT, "premium instance"),
        (Style.PRIMARY, " that has a "),
        (Style.IMPORTANT, "monthly charge"),
        (Style.PRIMARY, "\n"),
        (Style.SUCCESS, '(✓) Done: '),
        (Style.PRIMARY, "Creating a webapp named myfancyapp\n"),
    ]
    print_styled_text(styled_text)

    print_styled_text("[error handing]\n")
    styled_text = [
        (Style.ERROR, "ERROR: Command not found: az storage create\n"),
        (Style.PRIMARY, "TRY\n"),
        (Style.ACTION, "az storage account create --name"),
        (Style.PRIMARY, " mystorageaccount "),
        (Style.ACTION, "--resource-group"),
        (Style.PRIMARY, " MyResourceGroup\n"),
        (Style.SECONDARY, "Create a storage account. For more detail, see "),
        (Style.HYPERLINK,
         "https://docs.microsoft.com/en-us/azure/storage/common/storage-account-create?"
         "tabs=azure-cli#create-a-storage-account-1"),
        (Style.SECONDARY, "\n"),
    ]
    print_styled_text(styled_text)

    print_styled_text("[post-output hint]\n")
    styled_text = [
        (Style.PRIMARY, "The default subscription is "),
        (Style.IMPORTANT,
         "AzureSDKTest (0b1f6471-1bf0-4dda-aec3-cb9272f09590)"),
        (Style.PRIMARY, ". To switch to another subscription, run "),
        (Style.ACTION, "az account set --subscription"),
        (Style.PRIMARY, " <subscription ID>\n"),
        (Style.WARNING, "WARNING: The subscription has been disabled!\n")
    ]
    print_styled_text(styled_text)

    print_styled_text("[logs]\n")

    # Print logs
    logger.debug("This is a debug log entry.")
    logger.info("This is a info log entry.")
    logger.warning("This is a warning log entry.")
    logger.error("This is a error log entry.")
    logger.critical("This is a critical log entry.")
Ejemplo n.º 8
0
def demo_style(cmd):  # pylint: disable=unused-argument
    from azure.cli.core.style import Style, print_styled_text
    print("[available styles]\n")
    styled_text = [
        (Style.PRIMARY, "Bright White: Primary text color\n"),
        (Style.SECONDARY, "White: Secondary text color\n"),
        (Style.IMPORTANT, "Bright Magenta: Important text color\n"),
        (Style.ACTION,
         "Bright Blue: Commands, parameters, and system inputs\n"),
        (Style.HYPERLINK, "Bright Cyan: Hyperlink\n"),
        (Style.ERROR, "Bright Red: Error message indicator\n"),
        (Style.SUCCESS, "Bright Green: Success message indicator\n"),
        (Style.WARNING, "Bright Yellow: Warning message indicator\n"),
    ]
    print_styled_text(styled_text)

    print("[interactive]\n")
    # NOTE! Unicode character ⦾ ⦿ will most likely not be displayed correctly
    styled_text = [
        (Style.ACTION, "?"),
        (Style.PRIMARY, " Select a SKU for your app:\n"),
        (Style.PRIMARY, "⦾ Free            "),
        (Style.SECONDARY,
         "Dev/Test workloads: 1 GB memory, 60 minutes/day compute\n"),
        (Style.PRIMARY, "⦾ Basic           "),
        (Style.SECONDARY,
         "Dev/Test workloads: 1.75 GB memory, monthly charges apply\n"),
        (Style.PRIMARY, "⦾ Standard        "),
        (Style.SECONDARY,
         "Production workloads: 1.75 GB memory, monthly charges apply\n"),
        (Style.ACTION, "⦿ Premium         "),
        (Style.SECONDARY,
         "Production workloads: 3.5 GB memory, monthly charges apply\n"),
    ]
    print_styled_text(styled_text)

    print("[progress report]\n")
    # NOTE! Unicode character ✓ will most likely not be displayed correctly
    styled_text = [
        (Style.SUCCESS, '(✓) Done: '),
        (Style.PRIMARY, "Creating a resource group for myfancyapp\n"),
        (Style.SUCCESS, '(✓) Done: '),
        (Style.PRIMARY,
         "Creating an App Service Plan for myfancyappplan on a "),
        (Style.IMPORTANT, "premium instance"),
        (Style.PRIMARY, " that has a "),
        (Style.IMPORTANT, "monthly charge"),
        (Style.PRIMARY, "\n"),
        (Style.SUCCESS, '(✓) Done: '),
        (Style.PRIMARY, "Creating a webapp named myfancyapp\n"),
    ]
    print_styled_text(styled_text)

    print("[error handing]\n")
    styled_text = [
        (Style.ERROR, "ERROR: Command not found: az storage create\n"),
        (Style.PRIMARY, "TRY\n"),
        (Style.ACTION, "az storage account create --name"),
        (Style.PRIMARY, " mystorageaccount "),
        (Style.ACTION, "--resource-group"),
        (Style.PRIMARY, " MyResourceGroup\n"),
        (Style.SECONDARY, "Create a storage account. For more detail, see "),
        (Style.HYPERLINK,
         "https://docs.microsoft.com/en-us/azure/storage/common/storage-account-create?"
         "tabs=azure-cli#create-a-storage-account-1"),
        (Style.SECONDARY, "\n"),
    ]
    print_styled_text(styled_text)

    print("[post-output hint]\n")
    styled_text = [
        (Style.PRIMARY, "The default subscription is "),
        (Style.IMPORTANT,
         "AzureSDKTest (0b1f6471-1bf0-4dda-aec3-cb9272f09590)"),
        (Style.PRIMARY, ". To switch to another subscription, run "),
        (Style.ACTION, "az account set --subscription"),
        (Style.PRIMARY, " <subscription ID>\n"),
        (Style.WARNING, "WARNING: The subscription has been disabled!")
    ]
    print_styled_text(styled_text)