当前位置: 首页>>代码示例>>Python>>正文


Python util.CLIError方法代码示例

本文整理汇总了Python中knack.util.CLIError方法的典型用法代码示例。如果您正苦于以下问题:Python util.CLIError方法的具体用法?Python util.CLIError怎么用?Python util.CLIError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在knack.util的用法示例。


在下文中一共展示了util.CLIError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: retrieve_file_from_url

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def retrieve_file_from_url(url):
    """
    Retrieve a file from an URL

    Args:
        url: The URL to retrieve the file from.

    Returns:
        The absolute path of the downloaded file.
    """
    try:
        alias_source, _ = urlretrieve(url)
        # Check for HTTPError in Python 2.x
        with open(alias_source, 'r') as f:
            content = f.read()
            if content[:3].isdigit():
                raise CLIError(ALIAS_FILE_URL_ERROR.format(url, content.strip()))
    except Exception as exception:
        if isinstance(exception, CLIError):
            raise

        # Python 3.x
        raise CLIError(ALIAS_FILE_URL_ERROR.format(url, exception))

    return alias_source 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:27,代码来源:util.py

示例2: export_aliases

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def export_aliases(export_path=None, exclusions=None):
    """
    Export all registered aliases to a given path, as an INI configuration file.

    Args:
        export_path: The path of the alias configuration file to export to.
        exclusions: Space-separated aliases excluded from export.
    """
    if not export_path:
        export_path = os.path.abspath(ALIAS_FILE_NAME)

    alias_table = get_alias_table()
    for exclusion in exclusions or []:
        if exclusion not in alias_table.sections():
            raise CLIError(ALIAS_NOT_FOUND_ERROR.format(exclusion))
        alias_table.remove_section(exclusion)

    _commit_change(alias_table, export_path=export_path, post_commit=False)
    logger.warning(POST_EXPORT_ALIAS_MSG, export_path)  # pylint: disable=superfluous-parens 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:21,代码来源:custom.py

示例3: process_alias_export_namespace

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def process_alias_export_namespace(namespace):
    """
    Validate input arguments when the user invokes 'az alias export'.

    Args:
        namespace: argparse namespace object.
    """
    namespace.export_path = os.path.abspath(namespace.export_path)
    if os.path.isfile(namespace.export_path):
        raise CLIError(FILE_ALREADY_EXISTS_ERROR.format(namespace.export_path))

    export_path_dir = os.path.dirname(namespace.export_path)
    if not os.path.isdir(export_path_dir):
        os.makedirs(export_path_dir)

    if os.path.isdir(namespace.export_path):
        namespace.export_path = os.path.join(namespace.export_path, ALIAS_FILE_NAME) 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:19,代码来源:_validators.py

示例4: _validate_alias_command

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def _validate_alias_command(alias_command):
    """
    Check if the alias command is valid.

    Args:
        alias_command: The command to validate.
    """
    if not alias_command:
        raise CLIError(EMPTY_ALIAS_ERROR)

    split_command = shlex.split(alias_command)
    boundary_index = len(split_command)
    for i, subcommand in enumerate(split_command):
        if not re.match('^[a-z]', subcommand.lower()) or i > COLLISION_CHECK_LEVEL_DEPTH:
            boundary_index = i
            break

    # Extract possible CLI commands and validate
    command_to_validate = ' '.join(split_command[:boundary_index]).lower()
    for command in azext_alias.cached_reserved_commands:
        if re.match(r'([a-z\-]*\s)*{}($|\s)'.format(command_to_validate), command):
            return

    _validate_positional_arguments(shlex.split(alias_command)) 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:26,代码来源:_validators.py

示例5: _validate_pos_args_syntax

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def _validate_pos_args_syntax(alias_name, alias_command):
    """
    Check if the positional argument syntax is valid in alias name and alias command.

    Args:
        alias_name: The name of the alias to validate.
        alias_command: The command to validate.
    """
    pos_args_from_alias = get_placeholders(alias_name)
    # Split by '|' to extract positional argument name from Jinja filter (e.g. {{ arg_name | upper }})
    # Split by '.' to extract positional argument name from function call (e.g. {{ arg_name.split()[0] }})
    pos_args_from_command = [x.split('|')[0].split('.')[0].strip() for x in get_placeholders(alias_command)]

    if set(pos_args_from_alias) != set(pos_args_from_command):
        arg_diff = set(pos_args_from_alias) ^ set(pos_args_from_command)
        raise CLIError(INCONSISTENT_ARG_ERROR.format('' if len(arg_diff) == 1 else 's',
                                                     arg_diff,
                                                     'is' if len(arg_diff) == 1 else 'are')) 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:20,代码来源:_validators.py

示例6: _validate_alias_command_level

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def _validate_alias_command_level(alias, command):
    """
    Make sure that if the alias is a reserved command, the command that the alias points to
    in the command tree does not conflict in levels.

    e.g. 'dns' -> 'network dns' is valid because dns is a level 2 command and network dns starts at level 1.
    However, 'list' -> 'show' is not valid because list and show are both reserved commands at level 2.

    Args:
        alias: The name of the alias.
        command: The command that the alias points to.
    """
    alias_collision_table = AliasManager.build_collision_table([alias])

    # Alias is not a reserved command, so it can point to any command
    if not alias_collision_table:
        return

    command_collision_table = AliasManager.build_collision_table([command])
    alias_collision_levels = alias_collision_table.get(alias.split()[0], [])
    command_collision_levels = command_collision_table.get(command.split()[0], [])

    # Check if there is a command level conflict
    if set(alias_collision_levels) & set(command_collision_levels):
        raise CLIError(COMMAND_LVL_ERROR.format(alias, command)) 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:27,代码来源:_validators.py

示例7: _validate_alias_file_content

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def _validate_alias_file_content(alias_file_path, url=''):
    """
    Make sure the alias name and alias command in the alias file is in valid format.

    Args:
        The alias file path to import aliases from.
    """
    alias_table = get_config_parser()
    try:
        alias_table.read(alias_file_path)
        for alias_name, alias_command in reduce_alias_table(alias_table):
            _validate_alias_name(alias_name)
            _validate_alias_command(alias_command)
            _validate_alias_command_level(alias_name, alias_command)
            _validate_pos_args_syntax(alias_name, alias_command)
    except Exception as exception:  # pylint: disable=broad-except
        error_msg = CONFIG_PARSING_ERROR % AliasManager.process_exception_message(exception)
        error_msg = error_msg.replace(alias_file_path, url or alias_file_path)
        raise CLIError(error_msg) 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:21,代码来源:_validators.py

示例8: check_runtime_errors

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def check_runtime_errors(cmd_derived_from_alias, pos_args_table):
    """
    Validate placeholders and their expressions in cmd_derived_from_alias to make sure
    that there is no runtime error (such as index out of range).

    Args:
        cmd_derived_from_alias: The command derived from the alias
            (include any positional argument placehodlers)
        pos_args_table: The positional argument table.
    """
    for placeholder, value in pos_args_table.items():
        exec('{} = "{}"'.format(placeholder, value))  # pylint: disable=exec-used

    expressions = get_placeholders(cmd_derived_from_alias)
    for expression in expressions:
        try:
            exec(expression)  # pylint: disable=exec-used
        except Exception as exception:  # pylint: disable=broad-except
            error_msg = PLACEHOLDER_EVAL_ERROR.format(expression, exception)
            raise CLIError(error_msg) 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:22,代码来源:argument.py

示例9: get_action

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def get_action(self, values, option_string):  # pylint: disable=no-self-use
        try:
            properties = dict(x.split('=', 1) for x in values)
        except ValueError:
            raise CLIError('usage error: {} [KEY=VALUE ...]'.format(option_string))
        d = {}
        for k in properties:
            kl = k.lower()
            v = properties[k]
            if kl == 'carrier-name':
                d['carrier_name'] = v
            elif kl == 'tracking-number':
                d['tracking_number'] = v
            elif kl == 'drive-count':
                d['drive_count'] = v
            elif kl == 'ship-date':
                d['ship_date'] = v
        return d 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:20,代码来源:action.py

示例10: get_action

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def get_action(self, values, option_string):  # pylint: disable=no-self-use
        try:
            properties = defaultdict(list)
            for (k, v) in (x.split('=', 1) for x in values):
                properties[k].append(v)
            properties = dict(properties)
        except ValueError:
            raise CLIError('usage error: {} [KEY=VALUE ...]'.format(option_string))
        d = {}
        for k in properties:
            kl = k.lower()
            v = properties[k]
            if kl == 'type':
                d['type'] = v[0]
            elif kl == 'id':
                d['id'] = v[0]
            elif kl == 'enabled':
                d['enabled'] = v[0]
        return d 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:21,代码来源:action.py

示例11: kusto_database_update

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def kusto_database_update(client,
                          resource_group_name,
                          cluster_name,
                          database_name,
                          read_write_database=None,
                          read_only_following_database=None):
    all_parameters = []
    if read_write_database is not None:
        all_parameters.append(read_write_database)
    if read_only_following_database is not None:
        all_parameters.append(read_only_following_database)
    if len(all_parameters) > 1:
        raise CLIError('at most one of  read_write_database, read_only_following_database is needed for parameters!')
    if len(all_parameters) != 1:
        raise CLIError('parameters is required. but none of read_write_database, read_only_following_database is provid'
                       'ed!')
    parameters = all_parameters[0] if len(all_parameters) == 1 else None
    return client.begin_update(resource_group_name=resource_group_name,
                               cluster_name=cluster_name,
                               database_name=database_name,
                               parameters=parameters) 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:23,代码来源:custom.py

示例12: get_action

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def get_action(self, values, option_string):  # pylint: disable=no-self-use
        try:
            properties = defaultdict(list)
            for (k, v) in (x.split('=', 1) for x in values):
                properties[k].append(v)
            properties = dict(properties)
        except ValueError:
            raise CLIError('usage error: {} [KEY=VALUE ...]'.format(option_string))
        d = {}
        for k in properties:
            kl = k.lower()
            v = properties[k]
            if kl == 'name':
                d['name'] = v[0]
            elif kl == 'capacity':
                d['capacity'] = v[0]
            elif kl == 'tier':
                d['tier'] = v[0]
        return d 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:21,代码来源:action.py

示例13: _validate_resource_group_name

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def _validate_resource_group_name(rg_name):
    rg_pattern = r'[0-9a-zA-Z._\-()]+$'
    # if match is null or ends in period, then raise error
    if not match(rg_pattern, rg_name) or rg_name[-1] == '.':
        raise CLIError('Resource group name only allow alphanumeric characters, periods, underscores, hyphens and parenthesis and cannot end in a period.')

    if len(rg_name) > 90:
        raise CLIError('Resource group name only allow up to 90 characters.')

    # Check for existing dup name
    try:
        list_rg_command = 'az group list --query "[].name" -o json'
        logger.info('Checking for existing resource groups with identical name within subscription...')
        output = _call_az_command(list_rg_command)
    except AzCommandError as azCommandError:
        logger.error(azCommandError)
        raise CLIError('Unexpected error occured while fetching existing resource groups.')
    rg_list = loads(output)

    if rg_name in [rg.lower() for rg in rg_list]:
        raise CLIError('Resource group with name \'{}\' already exists within subscription.'.format(rg_name)) 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:23,代码来源:_validators.py

示例14: validate_vm_username

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def validate_vm_username(username, is_linux):
    """Sourced from src/azure-cli/azure/cli/command_modules/vm/_validators.py _validate_admin_username()"""
    pattern = (r'[\\\/"\[\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\/"\[\]:|<>+=;,?*@]+')
    linux_err = r'VM username cannot contain upper case character A-Z, special characters \/"[]:|<>+=;,?*@#()! or start with $ or -'
    win_err = r'VM username cannot contain special characters \/"[]:|<>+=;,?*@# or ends with .'

    if findall(pattern, username):
        raise CLIError(linux_err if is_linux else win_err)

    if is_linux and findall(r'^[$-]+', username):
        raise CLIError(linux_err)

    if not is_linux and username.endswith('.'):
        raise CLIError(win_err)

    # Sourced from vm module also
    disallowed_user_names = [
        "administrator", "admin", "user", "user1", "test", "user2",
        "test1", "user3", "admin1", "1", "123", "a", "actuser", "adm",
        "admin2", "aspnet", "backup", "console", "guest",
        "owner", "root", "server", "sql", "support", "support_388945a0",
        "sys", "test2", "test3", "user4", "user5"]

    if username.lower() in disallowed_user_names:
        raise CLIError("This username '{}' meets the general requirements, but is specifically disallowed. Please try a different value.".format(username)) 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:27,代码来源:_validators.py

示例15: validate_express_route_peering

# 需要导入模块: from knack import util [as 别名]
# 或者: from knack.util import CLIError [as 别名]
def validate_express_route_peering(cmd, namespace):
    from msrestazure.tools import is_valid_resource_id, resource_id
    circuit = namespace.circuit_name
    peering = namespace.peering

    if not circuit and not peering:
        return

    usage_error = CLIError('usage error: --peering ID | --peering NAME --circuit-name CIRCUIT')
    if not is_valid_resource_id(peering):
        namespace.peering = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Network',
            type='expressRouteCircuits',
            name=circuit,
            child_type_1='peerings',
            child_name_1=peering
        )
    elif circuit:
        raise usage_error 
开发者ID:Azure,项目名称:azure-cli-extensions,代码行数:23,代码来源:_validators.py


注:本文中的knack.util.CLIError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。