code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def resolve_project_url_from_index(extension_name):
"""
Gets the project url of the matching extension from the index
"""
candidates = get_index_extensions().get(extension_name, [])
if not candidates:
raise NoExtensionCandidatesError("No extension found with name '{}'".format(extension_name))
try:
return candidates[0]['metadata']['extensions']['python.details']['project_urls']['Home']
except KeyError as ex:
logger.debug(ex)
raise CLIError('Could not find project information for extension {}.'.format(extension_name)) | Gets the project url of the matching extension from the index | resolve_project_url_from_index | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/_resolve.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/_resolve.py | MIT |
def _get_all_extensions(cmd_chain, ext_set=None):
"""Find all the extension names in cmd_chain (dict of extension command subtree).
An example of cmd_chain may look like (a command sub tree of the 'aks' command group):
{
"create": "aks-preview",
"update": "aks-preview",
"app": {
"up": "deploy-to-azure"
},
"use-dev-spaces": "dev-spaces"
}
Then the resulting ext_set is {'aks-preview', 'deploy-to-azure', 'dev-spaces'}
"""
ext_set = set() if ext_set is None else ext_set
for key in cmd_chain:
if isinstance(cmd_chain[key], str):
ext_set.add(cmd_chain[key])
else:
_get_all_extensions(cmd_chain[key], ext_set)
return ext_set | Find all the extension names in cmd_chain (dict of extension command subtree).
An example of cmd_chain may look like (a command sub tree of the 'aks' command group):
{
"create": "aks-preview",
"update": "aks-preview",
"app": {
"up": "deploy-to-azure"
},
"use-dev-spaces": "dev-spaces"
}
Then the resulting ext_set is {'aks-preview', 'deploy-to-azure', 'dev-spaces'} | _get_all_extensions | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/dynamic_install.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/dynamic_install.py | MIT |
def _search_in_extension_commands(cli_ctx, command_str, allow_prefix_match=False):
"""Search the command in an extension commands dict which mimics a prefix tree.
If the value of the dict item is a string, then the key represents the end of a complete command
and the value is the name of the extension that the command belongs to.
An example of the dict read from extensionCommandTree.json:
{
"aks": {
"create": "aks-preview",
"update": "aks-preview",
"app": {
"up": "deploy-to-azure"
},
"use-dev-spaces": "dev-spaces"
},
...
}
"""
if not command_str:
return None
cmd_chain = _get_extension_command_tree(cli_ctx)
if not cmd_chain:
return None
for part in command_str.split():
try:
if isinstance(cmd_chain[part], str):
return cmd_chain[part]
cmd_chain = cmd_chain[part]
except KeyError:
return None
# command_str is prefix of one or more complete commands.
if not allow_prefix_match:
return None
all_exts = _get_all_extensions(cmd_chain)
return list(all_exts) if all_exts else None | Search the command in an extension commands dict which mimics a prefix tree.
If the value of the dict item is a string, then the key represents the end of a complete command
and the value is the name of the extension that the command belongs to.
An example of the dict read from extensionCommandTree.json:
{
"aks": {
"create": "aks-preview",
"update": "aks-preview",
"app": {
"up": "deploy-to-azure"
},
"use-dev-spaces": "dev-spaces"
},
...
} | _search_in_extension_commands | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/dynamic_install.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/dynamic_install.py | MIT |
def _check_value_in_extensions(cli_ctx, parser, args, no_prompt): # pylint: disable=too-many-statements, too-many-locals
"""Check if the command args can be found in extension commands.
Exit command if the error is caused by an extension not installed.
Otherwise return.
"""
# Check if the command is from an extension
from azure.cli.core.util import roughly_parse_command
from azure.cli.core.azclierror import NoTTYError
exit_code = 2
command_str = roughly_parse_command(args[1:])
allow_prefix_match = args[-1] == '-h' or args[-1] == '--help'
ext_name = _search_in_extension_commands(cli_ctx, command_str, allow_prefix_match=allow_prefix_match)
# ext_name is a list if the input command matches the prefix of one or more extension commands,
# for instance: `az blueprint` when running `az blueprint -h`
# ext_name is a str if the input command matches a complete command of an extension,
# for instance: `az blueprint create`
if isinstance(ext_name, list):
if len(ext_name) > 1:
from knack.prompting import prompt_choice_list, NoTTYException
prompt_msg = "The command requires the latest version of one of the following " \
"extensions. You need to pick one to install:"
try:
choice_idx = prompt_choice_list(prompt_msg, ext_name)
ext_name = ext_name[choice_idx]
no_prompt = True
except NoTTYException:
tty_err_msg = "{}{}\nUnable to prompt for selection as no tty available. Please update or " \
"install the extension with 'az extension add --upgrade -n <extension-name>'." \
.format(prompt_msg, ext_name)
az_error = NoTTYError(tty_err_msg)
az_error.print_error()
az_error.send_telemetry()
parser.exit(exit_code)
else:
ext_name = ext_name[0]
if not ext_name:
return
# If a valid command has parser error, it may be caused by CLI running on a profile that is
# not 'latest' and the command is not supported in that profile. If this command exists in an extension,
# CLI will try to download the extension and rerun the command. But the parser will fail again and try to
# install the extension and rerun the command infinitely. So we need to check if the latest version of the
# extension is already installed and return if yes as the error is not caused by extension not installed.
from azure.cli.core.extension import get_extension, ExtensionNotInstalledException
from azure.cli.core.extension._resolve import resolve_from_index, NoExtensionCandidatesError
extension_allow_preview = _get_extension_allow_preview_install_config(cli_ctx)
try:
ext = get_extension(ext_name)
except ExtensionNotInstalledException:
pass
else:
try:
resolve_from_index(ext_name, cur_version=ext.version, cli_ctx=cli_ctx,
allow_preview=extension_allow_preview)
except NoExtensionCandidatesError:
return
telemetry.set_command_details(command_str,
parameters=AzCliCommandInvoker._extract_parameter_names(args), # pylint: disable=protected-access
extension_name=ext_name)
run_after_extension_installed = _get_extension_run_after_dynamic_install_config(cli_ctx)
prompt_info = ""
if no_prompt:
logger.warning('The command requires the extension %s. It will be installed first.', ext_name)
install_ext = True
else: # yes_prompt
from knack.prompting import prompt_y_n, NoTTYException
prompt_msg = 'The command requires the extension {}. Do you want to install it now?'.format(ext_name)
if run_after_extension_installed:
prompt_msg = '{} The command will continue to run after the extension is installed.' \
.format(prompt_msg)
NO_PROMPT_CONFIG_MSG = "Run 'az config set extension.use_dynamic_install=" \
"yes_without_prompt' to allow installing extensions without prompt."
try:
install_ext = prompt_y_n(prompt_msg, default='y')
if install_ext:
prompt_info = " with prompt"
logger.warning(NO_PROMPT_CONFIG_MSG)
except NoTTYException:
tty_err_msg = "The command requires the extension {}. " \
"Unable to prompt for extension install confirmation as no tty " \
"available. {}".format(ext_name, NO_PROMPT_CONFIG_MSG)
az_error = NoTTYError(tty_err_msg)
az_error.print_error()
az_error.send_telemetry()
parser.exit(exit_code)
print_error = True
if install_ext:
from azure.cli.core.extension.operations import add_extension
add_extension(cli_ctx=cli_ctx, extension_name=ext_name, upgrade=True, allow_preview=extension_allow_preview)
if run_after_extension_installed:
import subprocess
import platform
exit_code = subprocess.call(args, shell=platform.system() == 'Windows')
# In this case, error msg is for telemetry recording purpose only.
# From UX perspective, the command will rerun in subprocess. Whether it succeeds or fails,
# mesages will be shown from the subprocess and this process should not print more message to
# interrupt that.
print_error = False
error_msg = ("Extension {} dynamically installed{} and commands will be "
"rerun automatically.").format(ext_name, prompt_info)
else:
error_msg = 'Extension {} installed{}. Please rerun your command.' \
.format(ext_name, prompt_info)
else:
error_msg = "The command requires the latest version of extension {ext_name}. " \
"To install, run 'az extension add --upgrade -n {ext_name}'.".format(
ext_name=ext_name)
az_error = CommandNotFoundError(error_msg)
if print_error:
az_error.print_error()
az_error.send_telemetry()
parser.exit(exit_code) | Check if the command args can be found in extension commands.
Exit command if the error is caused by an extension not installed.
Otherwise return. | _check_value_in_extensions | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/dynamic_install.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/dynamic_install.py | MIT |
def version(self):
"""
Lazy load version.
Returns the version as a string or None if not available.
"""
try:
self._version = self._version or self.get_version()
except Exception: # pylint: disable=broad-except
logger.debug("Unable to get extension version: %s", traceback.format_exc())
return self._version | Lazy load version.
Returns the version as a string or None if not available. | version | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/__init__.py | MIT |
def metadata(self):
"""
Lazy load metadata.
Returns the metadata as a dictionary or None if not available.
"""
try:
self._metadata = self._metadata or self.get_metadata()
except Exception: # pylint: disable=broad-except
logger.debug("Unable to get extension metadata: %s", traceback.format_exc())
return self._metadata | Lazy load metadata.
Returns the metadata as a dictionary or None if not available. | metadata | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/__init__.py | MIT |
def preview(self):
"""
Lazy load preview status.
Returns the preview status of the extension.
"""
try:
if not isinstance(self._preview, bool):
self._preview = is_preview_from_extension_meta(self.metadata)
except Exception: # pylint: disable=broad-except
logger.debug("Unable to get extension preview status: %s", traceback.format_exc())
return self._preview | Lazy load preview status.
Returns the preview status of the extension. | preview | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/__init__.py | MIT |
def experimental(self):
"""
In extension semantic versioning, experimental = preview, experimental deprecated
"""
return False | In extension semantic versioning, experimental = preview, experimental deprecated | experimental | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/__init__.py | MIT |
def get_all():
"""
Returns all wheel-based extensions.
"""
from glob import glob
exts = []
if os.path.isdir(EXTENSIONS_DIR):
for ext_name in os.listdir(EXTENSIONS_DIR):
ext_path = os.path.join(EXTENSIONS_DIR, ext_name)
pattern = os.path.join(ext_path, '*.*-info') # include *.egg-info and *.dist-info
if os.path.isdir(ext_path) and glob(pattern):
exts.append(WheelExtension(ext_name, ext_path))
if os.path.isdir(EXTENSIONS_SYS_DIR):
for ext_name in os.listdir(EXTENSIONS_SYS_DIR):
ext_path = os.path.join(EXTENSIONS_SYS_DIR, ext_name)
pattern = os.path.join(ext_path, '*.*-info') # include *.egg-info and *.dist-info
if os.path.isdir(ext_path) and glob(pattern):
ext = WheelExtension(ext_name, ext_path)
if ext not in exts:
exts.append(ext)
# https://docs.python.org/3/library/os.html#os.listdir, listdir is in arbitrary order.
# Sort the extensions by name to support overwrite extension feature: https://github.com/Azure/azure-cli/issues/25782.
exts.sort(key=lambda ext: ext.name)
return exts | Returns all wheel-based extensions. | get_all | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/__init__.py | MIT |
def get_all():
"""
Returns all dev extensions.
"""
from glob import glob
exts = []
def _collect(path, depth=0, max_depth=3):
if not os.path.isdir(path) or depth == max_depth or os.path.split(path)[-1].startswith('.'):
return
pattern = os.path.join(path, '*.egg-info')
match = glob(pattern)
if match:
ext_path = os.path.dirname(match[0])
ext_name = os.path.split(ext_path)[-1]
exts.append(DevExtension(ext_name, ext_path))
else:
for item in os.listdir(path):
_collect(os.path.join(path, item), depth + 1, max_depth)
for source in DEV_EXTENSION_SOURCES:
_collect(source)
# https://docs.python.org/3/library/os.html#os.listdir, listdir is in arbitrary order.
# Sort the extensions by name to support overwrite extension feature: https://github.com/Azure/azure-cli/issues/25782.
exts.sort(key=lambda ext: ext.name)
return exts | Returns all dev extensions. | get_all | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/__init__.py | MIT |
def get_extension_names(ext_type=None):
"""
Helper method to only get extension names.
Returns the extension names of extensions installed in the extensions directory.
"""
return [ext.name for ext in get_extensions(ext_type=ext_type)] | Helper method to only get extension names.
Returns the extension names of extensions installed in the extensions directory. | get_extension_names | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/__init__.py | MIT |
def is_preview_from_semantic_version(version):
"""
pre = [a, b] -> preview
>>> print(parse("1.2.3").pre)
None
>>> parse("1.2.3a1").pre
('a', 1)
>>> parse("1.2.3b1").pre
('b', 1)
"""
from packaging.version import parse
parsed_version = parse(version)
return bool(parsed_version.pre and parsed_version.pre[0] in ["a", "b"]) | pre = [a, b] -> preview
>>> print(parse("1.2.3").pre)
None
>>> parse("1.2.3a1").pre
('a', 1)
>>> parse("1.2.3b1").pre
('b', 1) | is_preview_from_semantic_version | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/__init__.py | MIT |
def test_reading_wheel_type_0_30_0_extension_metadata(self):
"""
Test wheel==0.30.0 containing metadata.json and we can handle it properly.
For scenario like 'az extenion add'.
"""
# this wheel contains metadata.json and METADATA
wheel_0_30_0_packed = get_test_data_file('wheel_0_30_0_packed_extension-0.1.0-py3-none-any.whl')
zf = zipfile.ZipFile(wheel_0_30_0_packed)
zf.extractall(self.ext_dir)
ext_name, ext_version = 'hello', '0.1.0'
whl_extension = WheelExtension(ext_name, self.ext_dir)
metadata = whl_extension.get_metadata() # able to read metadata from wheel==0.30.0 built extension
# wheel type extension generates .dist-info
dist_info = ext_name + '-' + ext_version + '.dist-info'
# assert Python metadata
self.assertEqual(metadata['name'], ext_name)
self.assertEqual(metadata['version'], ext_version)
self.assertEqual(metadata['author'], 'Microsoft Corporation')
self.assertIn('metadata.json', os.listdir(os.path.join(self.ext_dir, dist_info)))
# assert Azure CLI extended metadata
self.assertTrue(metadata['azext.isPreview'])
self.assertTrue(metadata['azext.isExperimental'])
self.assertEqual(metadata['azext.minCliCoreVersion'], '2.0.67') | Test wheel==0.30.0 containing metadata.json and we can handle it properly.
For scenario like 'az extenion add'. | test_reading_wheel_type_0_30_0_extension_metadata | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/tests/latest/test_wheel_type_extension.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/tests/latest/test_wheel_type_extension.py | MIT |
def test_reading_wheel_type_0_31_0_extension_metadata(self):
"""
Test wheel>=0.31.0 not containing metadata.json but we can still handle it properly.
For scenario like 'az extenion add'.
"""
# this wheel contains METADATA only
wheel_0_31_0_packed = get_test_data_file('wheel_0_31_0_packed_extension-0.1.0-py3-none-any.whl')
zf = zipfile.ZipFile(wheel_0_31_0_packed)
zf.extractall(self.ext_dir)
ext_name, ext_version = 'hello', '0.1.0'
whl_extension = WheelExtension(ext_name, self.ext_dir)
metadata = whl_extension.get_metadata() # able to read metadata from wheel==0.30.0 built extension
# wheel type extension generates .dist-info
dist_info = ext_name + '-' + ext_version + '.dist-info'
# assert Python metadata
self.assertEqual(metadata['name'], ext_name)
self.assertEqual(metadata['version'], ext_version)
self.assertEqual(metadata['author'], 'Microsoft Corporation')
self.assertNotIn('metadata.json', os.listdir(os.path.join(self.ext_dir, dist_info)))
# assert Azure CLI extended metadata
self.assertTrue(metadata['azext.isPreview'])
self.assertTrue(metadata['azext.isExperimental'])
self.assertEqual(metadata['azext.minCliCoreVersion'], '2.0.67') | Test wheel>=0.31.0 not containing metadata.json but we can still handle it properly.
For scenario like 'az extenion add'. | test_reading_wheel_type_0_31_0_extension_metadata | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/tests/latest/test_wheel_type_extension.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/tests/latest/test_wheel_type_extension.py | MIT |
def test_reading_wheel_type_extension_from_develop_mode(self):
"""
Test wheel type extension but installing from source code.
For scenario that user are developing extension via 'pip install -e' directlly
and load it from _CUSTOM_EXT_DIR or GLOBAL_CONFIG_DIR
"""
source_code_packaged = get_test_data_file('hello-0.1.0.tar.gz')
with tarfile.open(source_code_packaged, 'r:gz') as tar:
tar.extractall(self.ext_dir)
ext_name, ext_version = 'hello', '0.1.0'
ext_extension = WheelExtension(ext_name, os.path.join(self.ext_dir, ext_name + '-' + ext_version))
metadata = ext_extension.get_metadata() # able to read metadata from source code even in wheel type extension
# assert Python metadata
self.assertEqual(metadata['name'], ext_name)
self.assertEqual(metadata['version'], ext_version)
self.assertEqual(metadata['author'], 'Microsoft Corporation')
self.assertNotIn('metadata.json', os.listdir(os.path.join(self.ext_dir, ext_name + '-' + ext_version)))
# assert Azure CLI extended metadata
self.assertTrue(metadata['azext.isPreview'])
self.assertTrue(metadata['azext.isExperimental'])
self.assertEqual(metadata['azext.minCliCoreVersion'], '2.0.67') | Test wheel type extension but installing from source code.
For scenario that user are developing extension via 'pip install -e' directlly
and load it from _CUSTOM_EXT_DIR or GLOBAL_CONFIG_DIR | test_reading_wheel_type_extension_from_develop_mode | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/tests/latest/test_wheel_type_extension.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/tests/latest/test_wheel_type_extension.py | MIT |
def test_add_list_show_remove_extension_extra_index_url(self):
"""
Tests extension addition while specifying --extra-index-url parameter.
:return:
"""
extra_index_urls = ['https://testpypi.python.org/simple', 'https://pypi.python.org/simple']
add_extension(cmd=self.cmd, source=MY_EXT_SOURCE, pip_extra_index_urls=extra_index_urls)
actual = list_extensions()
self.assertEqual(len(actual), 1)
ext = show_extension(MY_EXT_NAME)
self.assertEqual(ext[OUT_KEY_NAME], MY_EXT_NAME)
remove_extension(MY_EXT_NAME)
num_exts = len(list_extensions())
self.assertEqual(num_exts, 0) | Tests extension addition while specifying --extra-index-url parameter.
:return: | test_add_list_show_remove_extension_extra_index_url | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/tests/latest/test_extension_commands.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/tests/latest/test_extension_commands.py | MIT |
def test_update_extension_extra_index_url(self):
"""
Tests extension update while specifying --extra-index-url parameter.
:return:
"""
extra_index_urls = ['https://testpypi.python.org/simple', 'https://pypi.python.org/simple']
add_extension(cmd=self.cmd, source=MY_EXT_SOURCE, pip_extra_index_urls=extra_index_urls)
ext = show_extension(MY_EXT_NAME)
self.assertEqual(ext[OUT_KEY_VERSION], '0.0.3+dev')
newer_extension = _get_test_data_file('myfirstcliextension-0.0.4+dev-py2.py3-none-any.whl')
computed_extension_sha256 = _compute_file_hash(newer_extension)
with mock.patch('azure.cli.core.extension.operations.resolve_from_index', return_value=(newer_extension, computed_extension_sha256)):
update_extension(self.cmd, MY_EXT_NAME, pip_extra_index_urls=extra_index_urls)
ext = show_extension(MY_EXT_NAME)
self.assertEqual(ext[OUT_KEY_VERSION], '0.0.4+dev') | Tests extension update while specifying --extra-index-url parameter.
:return: | test_update_extension_extra_index_url | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/tests/latest/test_extension_commands.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/tests/latest/test_extension_commands.py | MIT |
def test_reading_wheel_type_extension_from_develop_mode(self):
"""
Test develop type extension.
For scenario that user are developing extension via azdev
"""
source_code_packaged = get_test_data_file('hello-0.1.0.tar.gz')
with tarfile.open(source_code_packaged, 'r:gz') as tar:
tar.extractall(self.ext_dir)
ext_name, ext_version = 'hello', '0.1.0'
ext_extension = DevExtension(ext_name, os.path.join(self.ext_dir, ext_name + '-' + ext_version))
metadata = ext_extension.get_metadata() # able to read metadata from source code
# assert Python metadata
self.assertEqual(metadata['name'], ext_name)
self.assertEqual(metadata['version'], ext_version)
self.assertEqual(metadata['author'], 'Microsoft Corporation')
self.assertNotIn('metadata.json', os.listdir(os.path.join(self.ext_dir, ext_name + '-' + ext_version)))
# assert Azure CLI extended metadata
self.assertTrue(metadata['azext.isPreview'])
self.assertTrue(metadata['azext.isExperimental'])
self.assertEqual(metadata['azext.minCliCoreVersion'], '2.0.67') | Test develop type extension.
For scenario that user are developing extension via azdev | test_reading_wheel_type_extension_from_develop_mode | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/tests/latest/test_dev_type_extension.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/tests/latest/test_dev_type_extension.py | MIT |
def get_arguments_schema(cls):
""" Make sure _args_schema is build once.
"""
if not hasattr(cls, "_arguments_schema") or cls._arguments_schema is None:
cls._arguments_schema = cls._build_arguments_schema()
return cls._arguments_schema | Make sure _args_schema is build once. | get_arguments_schema | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def _build_arguments_schema(cls, *args, **kwargs):
""" Build the schema of command's argument, this function should be inherited by sub classes.
"""
schema = AAZArgumentsSchema(*args, **kwargs)
if cls.AZ_SUPPORT_NO_WAIT:
schema.no_wait = AAZBoolArg(
options=['--no-wait'],
help='Do not wait for the long-running operation to finish.'
)
if cls.AZ_SUPPORT_GENERIC_UPDATE:
schema.generic_update_add = AAZGenericUpdateAddArg()
schema.generic_update_set = AAZGenericUpdateSetArg()
schema.generic_update_remove = AAZGenericUpdateRemoveArg()
schema.generic_update_force_string = AAZGenericUpdateForceStringArg()
if cls.AZ_SUPPORT_PAGINATION:
schema.pagination_token = AAZPaginationTokenArg()
schema.pagination_limit = AAZPaginationLimitArg()
return schema | Build the schema of command's argument, this function should be inherited by sub classes. | _build_arguments_schema | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def __init__(self, loader=None, cli_ctx=None, callbacks=None, **kwargs):
"""
:param loader: it is required for command registered in the command table
:param cli_ctx: if a command instance is not registered in the command table, only cli_ctx is required.
:param callbacks: a dict of customized callback functions registered by @register_callback.
common used callbacks:
'pre_operations': This callback runs before all the operations
pre_operations(ctx) -> void
'post_operations': This callback runs after all the operations
post_operations(ctx) -> void
'pre_instance_update': This callback runs before all the instance update operations
pre_instance_update(instance, ctx) -> void
'post_instance_update': This callback runs after all the instance update operations and before PUT
post_instance_update(instance, ctx) -> void
"""
assert loader or cli_ctx, "loader or cli_ctx is required"
self.loader = loader
super().__init__(
cli_ctx=cli_ctx or loader.cli_ctx,
name=self.AZ_NAME,
confirmation=self.AZ_CONFIRMATION,
arguments_loader=self._cli_arguments_loader,
handler=True,
# knack use cmd.handler to check whether it is group or command,
# however this property will not be used in AAZCommand. So use True value for it.
# https://github.com/microsoft/knack/blob/e496c9590792572e680cb3ec959db175d9ba85dd/knack/parser.py#L227-L233
**kwargs
)
self.command_kwargs = {}
if self.AZ_PREVIEW_INFO:
self.preview_info = self.AZ_PREVIEW_INFO(cli_ctx=self.cli_ctx)
if self.AZ_EXPERIMENTAL_INFO:
self.experimental_info = self.AZ_EXPERIMENTAL_INFO(cli_ctx=self.cli_ctx)
if self.AZ_DEPRECATE_INFO:
self.deprecate_info = self.AZ_DEPRECATE_INFO(cli_ctx=self.cli_ctx)
self.help = self.AZ_HELP
self.ctx = None
self.callbacks = callbacks or {}
# help property will be assigned as help_file for command parser:
# https://github.com/Azure/azure-cli/blob/d69eedd89bd097306b8579476ef8026b9f2ad63d/src/azure-cli-core/azure/cli/core/parser.py#L104
# help_file will be loaded as file_data in knack:
# https://github.com/microsoft/knack/blob/e496c9590792572e680cb3ec959db175d9ba85dd/knack/help.py#L206-L208
# additional properties
self.supports_no_wait = self.AZ_SUPPORT_NO_WAIT
self.no_wait_param = None
self.exception_handler = None | :param loader: it is required for command registered in the command table
:param cli_ctx: if a command instance is not registered in the command table, only cli_ctx is required.
:param callbacks: a dict of customized callback functions registered by @register_callback.
common used callbacks:
'pre_operations': This callback runs before all the operations
pre_operations(ctx) -> void
'post_operations': This callback runs after all the operations
post_operations(ctx) -> void
'pre_instance_update': This callback runs before all the instance update operations
pre_instance_update(instance, ctx) -> void
'post_instance_update': This callback runs after all the instance update operations and before PUT
post_instance_update(instance, ctx) -> void | __init__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def _cli_arguments_loader(self):
"""load arguments"""
schema = self.get_arguments_schema()
args = {}
for name, field in schema._fields.items():
# generate command arguments from argument schema.
try:
args[name] = field.to_cmd_arg(name, cli_ctx=self.cli_ctx)
except AAZUnregisteredArg:
continue
return list(args.items()) | load arguments | _cli_arguments_loader | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def update_argument(self, param_name, argtype):
""" This function is called by core to add global arguments
"""
schema = self.get_arguments_schema()
if hasattr(schema, param_name):
# not support to overwrite arguments defined in schema, use arg.type as overrides
argtype = copy.deepcopy(self.arguments[param_name].type)
super().update_argument(param_name, argtype) | This function is called by core to add global arguments | update_argument | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def processor(schema, result):
"""A processor used in AAZBaseValue to serialized data"""
if result == AAZUndefined or result is None:
return result
if isinstance(schema, AAZObjectType):
# handle client flatten in result
disc_schema = schema.get_discriminator(result)
new_result = {}
for k, v in result.items():
# get schema of k
try:
k_schema = schema[k]
except AAZUnknownFieldError as err:
if not disc_schema:
raise err
# get k_schema from discriminator definition
k_schema = disc_schema[k]
if secret_hidden and k_schema._flags.get('secret', False):
# hidden secret properties in output
continue
if client_flatten and k_schema._flags.get('client_flatten', False):
# flatten k when there are client_flatten flag in its schema
assert isinstance(k_schema, AAZObjectType) and isinstance(v, dict)
for sub_k, sub_v in v.items():
if sub_k in new_result:
raise KeyError(f"Conflict key when apply client flatten: {sub_k} in {result}")
new_result[sub_k] = sub_v
else:
if k in new_result:
raise KeyError(f"Conflict key when apply client flatten: {k} in {result}")
new_result[k] = v
result = new_result
return result | A processor used in AAZBaseValue to serialized data | deserialize_output.processor | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def deserialize_output(value, client_flatten=True, secret_hidden=True):
""" Deserialize output of a command.
"""
if not isinstance(value, AAZBaseValue):
return value
def processor(schema, result):
"""A processor used in AAZBaseValue to serialized data"""
if result == AAZUndefined or result is None:
return result
if isinstance(schema, AAZObjectType):
# handle client flatten in result
disc_schema = schema.get_discriminator(result)
new_result = {}
for k, v in result.items():
# get schema of k
try:
k_schema = schema[k]
except AAZUnknownFieldError as err:
if not disc_schema:
raise err
# get k_schema from discriminator definition
k_schema = disc_schema[k]
if secret_hidden and k_schema._flags.get('secret', False):
# hidden secret properties in output
continue
if client_flatten and k_schema._flags.get('client_flatten', False):
# flatten k when there are client_flatten flag in its schema
assert isinstance(k_schema, AAZObjectType) and isinstance(v, dict)
for sub_k, sub_v in v.items():
if sub_k in new_result:
raise KeyError(f"Conflict key when apply client flatten: {sub_k} in {result}")
new_result[sub_k] = sub_v
else:
if k in new_result:
raise KeyError(f"Conflict key when apply client flatten: {k} in {result}")
new_result[k] = v
result = new_result
return result
return value.to_serialized_data(processor=processor) | Deserialize output of a command. | deserialize_output | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def build_lro_poller(self, executor, extract_result):
""" Build AAZLROPoller instance to support long running operation
"""
polling_generator = executor()
if self.ctx.lro_no_wait:
# run until yield the first polling
_ = next(polling_generator)
return None
return AAZLROPoller(polling_generator=polling_generator, result_callback=extract_result) | Build AAZLROPoller instance to support long running operation | build_lro_poller | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def build_paging(self, executor, extract_result):
""" Build AAZPaged instance to support paging
"""
def executor_wrapper(next_link):
self.ctx.next_link = next_link
executor()
if self.AZ_SUPPORT_PAGINATION:
args = self.ctx.args
token = args.pagination_token.to_serialized_data()
limit = args.pagination_limit.to_serialized_data()
return AAZPaged(
executor=executor_wrapper, extract_result=extract_result, cli_ctx=self.cli_ctx,
token=token, limit=limit
)
return AAZPaged(executor=executor_wrapper, extract_result=extract_result, cli_ctx=self.cli_ctx) | Build AAZPaged instance to support paging | build_paging | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def register_command_group(
name, is_preview=False, is_experimental=False, hide=False, redirect=None, expiration=None):
"""This decorator is used to register an AAZCommandGroup as a cli command group.
A registered AAZCommandGroup will be added into module's command group table.
"""
if is_preview and is_experimental:
raise CLIInternalError(
PREVIEW_EXPERIMENTAL_CONFLICT_ERROR.format(name)
)
deprecated_info = {}
if hide:
deprecated_info['hide'] = hide
if redirect:
deprecated_info['redirect'] = f'az {redirect}'
if expiration:
deprecated_info['expiration'] = expiration
def decorator(cls):
assert issubclass(cls, AAZCommandGroup)
cls.AZ_NAME = name
short_summary, long_summary, _ = _parse_cls_doc(cls)
cls.AZ_HELP = {
"type": "group",
"short-summary": short_summary,
"long-summary": long_summary
}
# the only way to load command group help in knack is by _load_from_file
# TODO: change knack to load AZ_HELP directly
import yaml
from knack.help_files import helps
helps[name] = yaml.safe_dump(cls.AZ_HELP)
if is_preview:
cls.AZ_PREVIEW_INFO = partial(PreviewItem, target=f'az {name}', object_type='command group')
if is_experimental:
cls.AZ_EXPERIMENTAL_INFO = partial(ExperimentalItem, target=f'az {name}', object_type='command group')
if deprecated_info:
cls.AZ_DEPRECATE_INFO = partial(Deprecated, target=f'az {name}', object_type='command group',
**deprecated_info)
return cls
return decorator | This decorator is used to register an AAZCommandGroup as a cli command group.
A registered AAZCommandGroup will be added into module's command group table. | register_command_group | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def register_command(
name, is_preview=False, is_experimental=False, confirmation=None, hide=False, redirect=None, expiration=None):
"""This decorator is used to register an AAZCommand as a cli command.
A registered AAZCommand will be added into module's command table.
"""
if is_preview and is_experimental:
raise CLIInternalError(
PREVIEW_EXPERIMENTAL_CONFLICT_ERROR.format(name)
)
deprecated_info = {}
if hide:
deprecated_info['hide'] = hide
if redirect:
deprecated_info['redirect'] = f'az {redirect}'
if expiration:
deprecated_info['expiration'] = expiration
def decorator(cls):
assert issubclass(cls, AAZCommand)
cls.AZ_NAME = name
short_summary, long_summary, examples = _parse_cls_doc(cls)
cls.AZ_HELP = {
"type": "command",
"short-summary": short_summary,
"long-summary": long_summary,
"examples": examples
}
if confirmation:
cls.AZ_CONFIRMATION = confirmation
if is_preview:
cls.AZ_PREVIEW_INFO = partial(PreviewItem, target=f'az {name}', object_type='command')
if is_experimental:
cls.AZ_EXPERIMENTAL_INFO = partial(ExperimentalItem, target=f'az {name}', object_type='command')
if deprecated_info:
cls.AZ_DEPRECATE_INFO = partial(Deprecated, target=f'az {name}', object_type='command', **deprecated_info)
return cls
return decorator | This decorator is used to register an AAZCommand as a cli command.
A registered AAZCommand will be added into module's command table. | register_command | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def load_aaz_command_table(loader, aaz_pkg_name, args):
""" This function is used in AzCommandsLoader.load_command_table.
It will load commands in module's aaz package.
"""
profile_pkg = _get_profile_pkg(aaz_pkg_name, loader.cli_ctx.cloud)
command_table = {}
command_group_table = {}
if args is None:
arg_str = ''
fully_load = True
else:
arg_str = ' '.join(args).lower() # Sometimes args may contain capital letters.
fully_load = os.environ.get(AAZ_PACKAGE_FULL_LOAD_ENV_NAME, 'False').lower() == 'true' # disable cut logic
if profile_pkg is not None:
_load_aaz_pkg(loader, profile_pkg, command_table, command_group_table, arg_str, fully_load)
for group_name, command_group in command_group_table.items():
loader.command_group_table[group_name] = command_group
for command_name, command in command_table.items():
loader.command_table[command_name] = command
return command_table, command_group_table | This function is used in AzCommandsLoader.load_command_table.
It will load commands in module's aaz package. | load_aaz_command_table | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def _get_profile_pkg(aaz_module_name, cloud):
""" load the profile package of aaz module according to the cloud profile.
"""
profile_module_name = get_aaz_profile_module_name(cloud.profile)
try:
return importlib.import_module(f'{aaz_module_name}.{profile_module_name}')
except ModuleNotFoundError:
return None | load the profile package of aaz module according to the cloud profile. | _get_profile_pkg | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def _load_aaz_pkg(loader, pkg, parent_command_table, command_group_table, arg_str, fully_load):
""" Load aaz commands and aaz command groups under a package folder.
"""
cut = False # if cut, its sub commands and sub pkgs will not be added
command_table = {} # the command available for this pkg and its sub pkgs
for value in pkg.__dict__.values():
if not fully_load and cut and command_table:
# when cut and command_table is not empty, stop loading more commands.
# the command_table should not be empty.
# Because if it's empty, the command group will be ignored in help if parent command group.
break
if isinstance(value, type):
if issubclass(value, AAZCommandGroup):
if value.AZ_NAME:
# AAZCommandGroup already be registered by register_command_command
if not arg_str.startswith(f'{value.AZ_NAME.lower()} '):
# when args not contain command group prefix, then cut more loading.
cut = True
# add command group into command group table
command_group_table[value.AZ_NAME] = value(
cli_ctx=loader.cli_ctx) # add command group even it's cut
elif issubclass(value, AAZCommand):
if value.AZ_NAME:
# AAZCommand already be registered by register_command
command_table[value.AZ_NAME] = value(loader=loader)
# continue load sub pkgs
pkg_path = os.path.dirname(pkg.__file__)
for sub_path in os.listdir(pkg_path):
if not fully_load and cut and command_table:
# when cut and command_table is not empty, stop loading more sub pkgs.
break
if sub_path.startswith('_') or not os.path.isdir(os.path.join(pkg_path, sub_path)):
continue
try:
sub_pkg = importlib.import_module(f'.{sub_path}', pkg.__name__)
except ModuleNotFoundError:
logger.debug('Failed to load package folder in aaz: %s.', os.path.join(pkg_path, sub_path))
continue
if not sub_pkg.__file__:
logger.debug('Ignore invalid package folder in aaz: %s.', os.path.join(pkg_path, sub_path))
continue
# recursively load sub package
_load_aaz_pkg(loader, sub_pkg, command_table, command_group_table, arg_str, fully_load)
parent_command_table.update(command_table) # update the parent pkg's command table. | Load aaz commands and aaz command groups under a package folder. | _load_aaz_pkg | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def _parse_cls_doc(cls):
""" Parse the help from the doc string of aaz classes. Examples are only defined in aaz command classes.
"""
doc = cls.__doc__
short_summary = None
long_summary = None
lines = []
if doc:
for line in doc.splitlines():
line = line.strip()
if line:
lines.append(line)
examples = []
if lines:
short_summary = lines[0]
assert not short_summary.startswith(':')
idx = 1
while idx < len(lines):
line = lines[idx]
if line.startswith(_DOC_EXAMPLE_FLAG):
break
idx += 1
long_summary = '\n'.join(lines[1:idx]) or None
while idx < len(lines):
line = lines[idx]
if line.startswith(_DOC_EXAMPLE_FLAG):
example = {
"name": line[len(_DOC_EXAMPLE_FLAG):].strip()
}
e_idx = idx + 1
while e_idx < len(lines) and not lines[e_idx].startswith(_DOC_EXAMPLE_FLAG):
e_idx += 1
example["text"] = '\n'.join(lines[idx + 1: e_idx]) or None
if example["text"]:
examples.append(example)
idx = e_idx - 1
idx += 1
return short_summary, long_summary, examples | Parse the help from the doc string of aaz classes. Examples are only defined in aaz command classes. | _parse_cls_doc | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_command.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_command.py | MIT |
def to_serialized_data(self, processor=None, **kwargs):
""" serialize value into python build-in type """
raise NotImplementedError() | serialize value into python build-in type | to_serialized_data | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_base.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_base.py | MIT |
def process_data(self, data, **kwargs):
"""Process data, make sure the return data followed the Type definition."""
raise NotImplementedError() | Process data, make sure the return data followed the Type definition. | process_data | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_base.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_base.py | MIT |
def build(cls, schema):
"""build a value patch from value type"""
if schema._PatchDataCls:
return cls(data=schema._PatchDataCls())
return cls(data=AAZUndefined) | build a value patch from value type | build | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_base.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_base.py | MIT |
def assign_aaz_list_arg(target: AAZList, source: AAZList, element_transformer=None):
""" an convenience function to transform from a source AAZListArg to a target AAZListArg
Example:
args.target = assign_aaz_list_arg(args.target, args.source, lambda idx, e: {'idx': idx, "prop": e})
"""
assert isinstance(target, AAZBaseValue)
assert isinstance(source, AAZBaseValue)
target_schema = target._schema
source_schema = source._schema
assert isinstance(target_schema, AAZListArg)
assert isinstance(source_schema, AAZListArg)
assert target_schema._nullable == source_schema._nullable, "Inconsist nullable property between target and " \
"source args"
assert target_schema.Element._nullable == source_schema.Element._nullable, "Inconsist nullable property between " \
"target element and source arg element"
if not has_value(source):
return target
if source == None: # noqa: E711, pylint: disable=singleton-comparison
return None
if not source._is_patch:
# return the whole array
data = []
for idx, element in enumerate(source):
if not has_value(element):
continue
if element == None: # noqa: E711, pylint: disable=singleton-comparison
data.append(None)
elif element_transformer:
data.append(element_transformer(idx, element))
else:
data.append(element)
return data
# assign by patch way
for idx, element in enumerate(source):
if not has_value(element):
continue
if element == None: # noqa: E711, pylint: disable=singleton-comparison
target[idx] = None
elif element_transformer:
target[idx] = element_transformer(idx, element)
else:
target[idx] = element
return target | an convenience function to transform from a source AAZListArg to a target AAZListArg
Example:
args.target = assign_aaz_list_arg(args.target, args.source, lambda idx, e: {'idx': idx, "prop": e}) | assign_aaz_list_arg | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/utils.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/utils.py | MIT |
def assign_aaz_dict_arg(target: AAZDict, source: AAZDict, element_transformer=None):
""" an convenience function to transform from a source AAZDictArg to a target AAZDictArg
Example:
args.target = assign_aaz_dict_arg(args.target, args.source, lambda key, e: {'name': key, "prop": e})
"""
assert isinstance(target, AAZBaseValue)
assert isinstance(source, AAZBaseValue)
target_schema = target._schema
source_schema = source._schema
assert isinstance(target_schema, AAZDictArg)
assert isinstance(source_schema, AAZDictArg)
assert target_schema._nullable == source_schema._nullable, "Inconsist nullable property between target and " \
"source args"
assert target_schema.Element._nullable == source_schema.Element._nullable, "Inconsist nullable property between " \
"target element and source arg element"
if not has_value(source):
return target
if source == None: # noqa: E711, pylint: disable=singleton-comparison
return None
if not source._is_patch:
# return the whole array
data = {}
for key, element in source.items():
if not has_value(element):
continue
if element == None: # noqa: E711, pylint: disable=singleton-comparison
data[key] = None
elif element_transformer:
data[key] = element_transformer(key, element)
else:
data[key] = element
return data
# assign by patch way
for key, element in source.items():
if not has_value(element):
continue
if element == None: # noqa: E711, pylint: disable=singleton-comparison
target[key] = None
elif element_transformer:
target[key] = element_transformer(key, element)
else:
target[key] = element
return target | an convenience function to transform from a source AAZDictArg to a target AAZDictArg
Example:
args.target = assign_aaz_dict_arg(args.target, args.source, lambda key, e: {'name': key, "prop": e}) | assign_aaz_dict_arg | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/utils.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/utils.py | MIT |
def _get_attr_schema_and_name(self, key):
""" get attribute schema and it's name based in key """
disc_schema = self._schema.get_discriminator(self._data)
if not hasattr(self._schema, key) and disc_schema is not None:
attr_schema = disc_schema[key] # will raise error if key not exist
schema = disc_schema
else:
attr_schema = self._schema[key] # will raise error if key not exist
schema = self._schema
name = schema.get_attr_name(key)
assert name is not None
return attr_schema, name | get attribute schema and it's name based in key | _get_attr_schema_and_name | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_field_value.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_field_value.py | MIT |
def __init__(self, case=None, braces_removed=True, hyphens_filled=True):
"""
:param case: 'upper' to format data into upper case, 'lower' to format data into lower case
"""
self.case = case
self.braces_removed = braces_removed
self.hyphens_filled = hyphens_filled | :param case: 'upper' to format data into upper case, 'lower' to format data into lower case | __init__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_arg_fmt.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_arg_fmt.py | MIT |
def __init__(self, template=None, cross_tenants=True):
"""
:param template: template property is used to verify a resource Id or construct resource Id.
:param cross_tenants: if cross_tenants is True, the resource id will apply to cross-tenants scenarios.
"""
self._template = None
if template:
self._template = self._Template(template)
self._cross_tenants = cross_tenants | :param template: template property is used to verify a resource Id or construct resource Id.
:param cross_tenants: if cross_tenants is True, the resource id will apply to cross-tenants scenarios. | __init__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_arg_fmt.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_arg_fmt.py | MIT |
def get_prop(self, key):
"""The sub property argument by key. The return value will be an Argument Browser as well."""
if key is None or key == '.':
return self
if key.startswith('..'):
if self._parent is None:
raise ValueError(f"Invalid Key: '{key}' : parent is None")
return self._parent.get(key[1:])
if key.startswith('.'):
names = key[1:].split('.', maxsplit=1)
prop_name = names[0]
if self._arg_data is None or prop_name not in self._arg_data:
return None
sub_value = self._arg_value[prop_name]
sub_data = self._arg_data[prop_name]
sub_browser = AAZArgBrowser(sub_value, sub_data, parent=self)
if len(names) == 1:
return sub_browser
assert len(names) == 2
return sub_browser.get_prop(f'.{names[1]}')
raise NotImplementedError() | The sub property argument by key. The return value will be an Argument Browser as well. | get_prop | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_arg_browser.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_arg_browser.py | MIT |
def get_elements(self):
"""Iter over sub elements of list or dict."""
if self._arg_data is None:
# stop iteration
return
if isinstance(self._arg_data, list):
for idx, d in enumerate(self._arg_data):
# not support to access parent from element args
yield idx, AAZArgBrowser(self._arg_value[idx], d, parent=None)
elif isinstance(self._arg_data, dict):
for k, d in self._arg_data.items():
# not support to access parent from element args
yield k, AAZArgBrowser(self._arg_value[k], d, parent=None)
else:
raise NotImplementedError() | Iter over sub elements of list or dict. | get_elements | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_arg_browser.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_arg_browser.py | MIT |
def get_anytype_elements(self):
"""Iter over sub elements of list or dict."""
return self.get_elements() | Iter over sub elements of list or dict. | get_anytype_elements | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_arg_browser.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_arg_browser.py | MIT |
def split_partial_value(cls, v):
""" split 'Partial Value' format """
assert isinstance(v, str)
match = cls.partial_value_key_pattern.fullmatch(v)
if not match:
key = None
else:
key = match[1]
v = match[len(match.regs) - 1]
key_parts = cls.parse_partial_value_key(key)
return key, key_parts, v | split 'Partial Value' format | split_partial_value | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_utils.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_utils.py | MIT |
def to_choices(self):
"""Generate choices property of CLICommandArgument"""
choices = list(self.items)
if not self._case_sensitive:
choices = CaseInsensitiveList(choices)
return choices | Generate choices property of CLICommandArgument | to_choices | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_arg.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_arg.py | MIT |
def __init__(self, options=None, required=False, help=None, arg_group=None, is_preview=False, is_experimental=False,
id_part=None, default=AAZUndefined, blank=AAZUndefined, nullable=False, fmt=None, registered=True,
configured_default=None, completer=None):
"""
:param options: argument optional names.
:param required: argument is required or not.
:param help: help can be either string (for short-summary) or a dict with `name`, `short-summary`,
`long-summary` and `populator-commands` properties
:param arg_group: argument group.
:param is_preview: is preview.
:param is_experimental: is experimental.
:param id_part: whether needs id part support in azure.cli.core
:param default: when the argument flag is not appeared, the default value will be used.
:param blank: when the argument flag is used without value data, the blank value will be used.
:param nullable: argument can accept `None` as value
:param fmt: argument format
:param registered: control whether register argument into command display
:param configured_default: the key to retrieve the default value from cli configuration
:param completer: tab completion if completion is active
"""
super().__init__(options=options, nullable=nullable)
self._help = {} # the key in self._help can be 'name', 'short-summary', 'long-summary', 'populator-commands'
if self._options:
self._help['name'] = ' '.join(self._options)
if isinstance(help, str):
self._help['short-summary'] = help
elif isinstance(help, dict):
self._help.update(help)
self._required = required
self._arg_group = arg_group
self._is_preview = is_preview
self._is_experimental = is_experimental
self._id_part = id_part
self._default = default
self._blank = blank
self._fmt = fmt
self._registered = registered
self._configured_default = configured_default
self._completer = completer | :param options: argument optional names.
:param required: argument is required or not.
:param help: help can be either string (for short-summary) or a dict with `name`, `short-summary`,
`long-summary` and `populator-commands` properties
:param arg_group: argument group.
:param is_preview: is preview.
:param is_experimental: is experimental.
:param id_part: whether needs id part support in azure.cli.core
:param default: when the argument flag is not appeared, the default value will be used.
:param blank: when the argument flag is used without value data, the blank value will be used.
:param nullable: argument can accept `None` as value
:param fmt: argument format
:param registered: control whether register argument into command display
:param configured_default: the key to retrieve the default value from cli configuration
:param completer: tab completion if completion is active | __init__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_arg.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_arg.py | MIT |
def to_cmd_arg(self, name, **kwargs):
""" convert AAZArg to CLICommandArgument """
if not self._registered:
# argument will not registered in command display
raise AAZUnregisteredArg()
options_list = [*self._options] if self._options else None
arg = CLICommandArgument(
dest=name,
options_list=options_list,
# if default is not None, arg is not required.
required=self._required if self._default == AAZUndefined else False,
help=self._help.get('short-summary', None),
id_part=self._id_part,
default=copy.deepcopy(self._default),
)
if self._arg_group:
arg.arg_group = self._arg_group
if self._blank != AAZUndefined:
arg.nargs = '?'
if isinstance(self._blank, AAZPromptInput):
short_summary = arg.type.settings.get('help', None) or ''
if short_summary:
short_summary += ' '
short_summary += self._blank.help_message
arg.help = short_summary
cli_ctx = kwargs.get('cli_ctx', None)
if cli_ctx is None:
# define mock cli_ctx for PreviewItem and ExperimentalItem
class _CLI_CTX:
enable_color = False
cli_ctx = _CLI_CTX
if options_list is None:
target = f"--{name.replace('_', '-')}"
else:
target = sorted(options_list, key=len)[-1]
if self._is_preview:
def _get_preview_arg_message(self):
subject = "{} '{}'".format(self.object_type.capitalize(), self.target)
return status_tag_messages['preview'].format(subject)
arg.preview_info = PreviewItem(
cli_ctx=cli_ctx,
target=target,
object_type="argument",
message_func=_get_preview_arg_message
)
if self._is_experimental:
def _get_experimental_arg_message(self):
# "Argument xxx"
subject = "{} '{}'".format(self.object_type.capitalize(), self.target)
return status_tag_messages['experimental'].format(subject)
arg.experimental_info = ExperimentalItem(
cli_ctx=cli_ctx,
target=target,
object_type="argument",
message_func=_get_experimental_arg_message
)
if self._configured_default:
arg.configured_default = self._configured_default
if self._completer:
from azure.cli.core.decorators import Completer
assert isinstance(self._completer, Completer)
arg.completer = self._completer
action = self._build_cmd_action() # call sub class's implementation to build CLICommandArgument action
if action:
arg.action = action
return arg | convert AAZArg to CLICommandArgument | to_cmd_arg | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_arg.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_arg.py | MIT |
def _build_cmd_action(self):
"""build argparse Action"""
raise NotImplementedError() | build argparse Action | _build_cmd_action | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_arg.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_arg.py | MIT |
def _type_in_help(self):
"""argument type displayed in help"""
return "Undefined" | argument type displayed in help | _type_in_help | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_arg.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_arg.py | MIT |
def new_content_builder(arg_value, value=None, typ=None, typ_kwargs=None):
""" Create a Content Builder
"""
assert isinstance(arg_value, AAZBaseValue)
arg_data = arg_value.to_serialized_data(keep_undefined_in_list=True)
if value is None:
assert issubclass(typ, AAZBaseType)
schema = typ(**typ_kwargs) if typ_kwargs else typ()
if isinstance(schema, AAZSimpleType):
value = typ._ValueCls(
schema=schema,
data=schema.process_data(arg_data)
)
else:
value = typ._ValueCls(
schema=schema,
data=schema.process_data(None)
)
else:
assert isinstance(value, AAZBaseValue), f"Unknown value type: {type(value)}"
builder = AAZContentBuilder(
values=[value],
args=[AAZArgBrowser(arg_value=arg_value, arg_data=arg_data)]
)
return value, builder | Create a Content Builder | new_content_builder | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_operation.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_operation.py | MIT |
def make_request(self):
""" Make http request based on the properties.
"""
if self.ctx.next_link:
# support making request for next link
_parsed_next_link = urlparse(self.ctx.next_link)
_next_request_params = {
key: [quote(v) for v in value]
for key, value in parse_qs(_parsed_next_link.query).items()
}
request = self.client._request(
"GET", urljoin(self.ctx.next_link, _parsed_next_link.path), _next_request_params,
self.header_parameters, self.content, self.form_content, None)
elif self.method in ("GET",):
request = self.client._request(
self.method, self.url, self.query_parameters, self.header_parameters,
self.content, self.form_content, None)
elif self.method in ("DELETE", "MERGE", "OPTIONS"):
request = self.client._request(
self.method, self.url, self.query_parameters, self.header_parameters,
self.content, self.form_content, None)
elif self.method in ("PUT", "POST", "HEAD", "PATCH",):
request = self.client._request(
self.method, self.url, self.query_parameters, self.header_parameters,
self.content, self.form_content, self.stream_content)
else:
raise ValueError(f"Invalid request method {self.method}")
return request | Make http request based on the properties. | make_request | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_operation.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_operation.py | MIT |
def on_error(self, response):
""" handle errors in response
"""
# raise common http errors
error_type = self.error_map.get(response.status_code)
if error_type:
raise error_type(response=response)
# raise HttpResponseError
error_format = self.ctx.get_error_format(self.error_format)
raise HttpResponseError(response=response, error_format=error_format) | handle errors in response | on_error | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_operation.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_operation.py | MIT |
def new_content_builder(arg_value, value=None, typ=None, typ_kwargs=None):
""" Create a Content Builder
"""
assert isinstance(arg_value, AAZBaseValue)
arg_data = arg_value.to_serialized_data(keep_undefined_in_list=True)
if value is None:
assert issubclass(typ, AAZBaseType)
schema = typ(**typ_kwargs) if typ_kwargs else typ()
if isinstance(schema, AAZSimpleType):
value = typ._ValueCls(
schema=schema,
data=schema.process_data(arg_data)
)
else:
value = typ._ValueCls(
schema=schema,
data=schema.process_data(None)
)
else:
assert isinstance(value, AAZBaseValue), f"Unknown value type: {type(value)}"
builder = AAZContentBuilder(
values=[value],
args=[AAZArgBrowser(arg_value=arg_value, arg_data=arg_data)]
)
return value, builder | Create a Content Builder | new_content_builder | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_operation.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_operation.py | MIT |
def set_const(self, prop_name, prop_value, typ, arg_key=None, typ_kwargs=None):
"""Set const value for a property"""
for value, arg in zip(self._values, self._args):
schema = value._schema
if self._is_discriminated:
assert isinstance(schema, AAZObjectType)
# use discriminator schema
schema = schema.get_discriminator(value)
sub_arg = arg.get_prop(arg_key)
if sub_arg is not None and sub_arg.data != AAZUndefined:
if schema.get_attr_name(prop_name) is None:
schema[prop_name] = typ(**typ_kwargs) if typ_kwargs else typ()
else:
assert isinstance(schema[prop_name], typ)
value[prop_name] = prop_value | Set const value for a property | set_const | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_content_builder.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_content_builder.py | MIT |
def set_prop(self, prop_name, typ, arg_key=None, typ_kwargs=None):
"""Set property value from argument"""
sub_values = []
sub_args = []
for value, arg in zip(self._values, self._args):
schema = value._schema
if self._is_discriminated:
assert isinstance(schema, AAZObjectType)
# use discriminator schema
schema = schema.get_discriminator(value)
sub_arg = arg.get_prop(arg_key)
if sub_arg is not None and sub_arg.data != AAZUndefined:
if schema.get_attr_name(prop_name) is None:
schema[prop_name] = typ(**typ_kwargs) if typ_kwargs else typ()
else:
assert isinstance(schema[prop_name], typ)
if not sub_arg.is_patch and arg_key:
if isinstance(value[prop_name], AAZSimpleValue):
value[prop_name] = sub_arg.data
elif isinstance(value[prop_name], AAZList):
if sub_arg.data is None:
value[prop_name] = None
else:
value[prop_name] = []
elif isinstance(value[prop_name], (AAZBaseDictValue, AAZObject)):
if sub_arg.data is None:
value[prop_name] = None
else:
value[prop_name] = {}
else:
raise NotImplementedError()
if value != None: # noqa: E711, pylint: disable=singleton-comparison
sub_values.append(value[prop_name])
sub_args.append(sub_arg)
if sub_values:
self._sub_prop_builders[prop_name] = AAZContentBuilder(sub_values, sub_args)
return self._sub_prop_builders[prop_name]
return None | Set property value from argument | set_prop | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_content_builder.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_content_builder.py | MIT |
def set_elements(self, typ, arg_key=None, typ_kwargs=None):
"""Set elements of dict or list from argument"""
sub_values = []
sub_args = []
for value, arg in zip(self._values, self._args):
schema = value._schema
if schema._element is None:
schema.Element = typ(**typ_kwargs) if typ_kwargs else typ()
else:
assert isinstance(schema.Element, typ)
if not isinstance(value, (AAZDict, AAZList)):
raise NotImplementedError()
for key, sub_arg in arg.get_elements():
if sub_arg is not None and sub_arg.data != AAZUndefined:
sub_arg = sub_arg.get_prop(arg_key)
if sub_arg is not None and sub_arg.data != AAZUndefined:
if not sub_arg.is_patch and arg_key:
if isinstance(value[key], AAZSimpleValue):
value[key] = sub_arg.data
elif isinstance(value[key], AAZList):
if sub_arg.data is None:
value[key] = None
else:
value[key] = []
elif isinstance(value[key], (AAZBaseDictValue, AAZObject)):
if sub_arg.data is None:
value[key] = None
else:
value[key] = {}
else:
raise NotImplementedError()
sub_values.append(value[key])
sub_args.append(sub_arg)
if sub_values:
self._sub_elements_builder = AAZContentBuilder(sub_values, sub_args)
return self._sub_elements_builder
return None | Set elements of dict or list from argument | set_elements | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_content_builder.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_content_builder.py | MIT |
def set_anytype_elements(self, arg_key=None):
"""Set any type elements of free from dictionary"""
self.set_elements(AAZAnyType, arg_key=arg_key) | Set any type elements of free from dictionary | set_anytype_elements | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_content_builder.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_content_builder.py | MIT |
def discriminate_by(self, prop_name, prop_value):
"""discriminate object by a specify property"""
if self._discriminator_prop_name is None:
self._discriminator_prop_name = prop_name
if self._discriminator_prop_name != prop_name:
raise KeyError(f"Conflict discriminator key: {self._discriminator_prop_name} and {prop_name}")
disc_values = []
disc_args = []
for value, arg in zip(self._values, self._args):
if not isinstance(value, (AAZObject,)):
raise NotImplementedError()
schema = value._schema
schema.discriminate_by(prop_name, prop_value)
if value[prop_name] == prop_value:
disc_values.append(value)
disc_args.append(arg)
if disc_values:
self._discriminator_builders[prop_value] = AAZContentBuilder(disc_values, disc_args, is_discriminated=True)
else:
self._discriminator_builders[prop_value] = None
return self._discriminator_builders[prop_value] | discriminate object by a specify property | discriminate_by | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_content_builder.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_content_builder.py | MIT |
def get(self, key):
"""Get sub builder by key"""
if not key or key == '.':
return self
parts = self._split_key(key)
return self._get(*parts) | Get sub builder by key | get | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_content_builder.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_content_builder.py | MIT |
def _build_base_url(cls, ctx, **kwargs):
"""Provide a complete url. Supports placeholder added"""
# return "https://{KeyVaultName}" + ctx.cli_ctx.cloud.suffixes.keyvault_dns
raise NotImplementedError() | Provide a complete url. Supports placeholder added | _build_base_url | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_client.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_client.py | MIT |
def _build_configuration(cls, ctx, credential, **kwargs):
"""Provide client configuration"""
# return AAZClientConfiguration(
# credential=credential,
# credential_scopes=<credential_scopes>,
# **kwargs
# )
raise NotImplementedError() | Provide client configuration | _build_configuration | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_client.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_client.py | MIT |
def _start(self):
"""Start the long running operation.
On completion, runs any callbacks.
:param callable update_cmd: The API request to check the status of
the operation.
"""
try:
for polling_method in self._polling_generator:
self._polling_method = polling_method
try:
self._polling_method.run()
except AzureError as error:
if not error.continuation_token:
try:
error.continuation_token = self._polling_method.get_continuation_token()
except Exception as err: # pylint: disable=broad-except
_LOGGER.warning("Unable to retrieve continuation token: %s", err)
error.continuation_token = None
raise error
except Exception as error: # pylint: disable=broad-except
self._exception = error
finally:
self._done.set() | Start the long running operation.
On completion, runs any callbacks.
:param callable update_cmd: The API request to check the status of
the operation. | _start | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_poller.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_poller.py | MIT |
def result(self, timeout=None):
"""Return the result of the long running operation, or
the result available after the specified timeout.
:returns: The deserialized resource of the long running operation,
if one is available.
:raises ~azure.core.exceptions.HttpResponseError: Server problem with the query.
"""
self.wait(timeout)
resource = self._polling_method.resource()
if self._result_callback:
return self._result_callback(resource)
return resource | Return the result of the long running operation, or
the result available after the specified timeout.
:returns: The deserialized resource of the long running operation,
if one is available.
:raises ~azure.core.exceptions.HttpResponseError: Server problem with the query. | result | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_poller.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_poller.py | MIT |
def wait(self, timeout=None):
"""Wait on the long running operation for a specified length
of time. You can check if this call as ended with timeout with the
"done()" method.
:param float timeout: Period of time to wait for the long running
operation to complete (in seconds).
:raises ~azure.core.exceptions.HttpResponseError: Server problem with the query.
"""
if self._thread is None:
return
self._thread.join(timeout=timeout)
if self._exception: # derive from BaseException
raise self._exception | Wait on the long running operation for a specified length
of time. You can check if this call as ended with timeout with the
"done()" method.
:param float timeout: Period of time to wait for the long running
operation to complete (in seconds).
:raises ~azure.core.exceptions.HttpResponseError: Server problem with the query. | wait | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_poller.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_poller.py | MIT |
def done(self):
"""Check status of the long running operation.
:returns: 'True' if the process has completed, else 'False'.
:rtype: bool
"""
return self._thread is None or not self._thread.is_alive() | Check status of the long running operation.
:returns: 'True' if the process has completed, else 'False'.
:rtype: bool | done | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_poller.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_poller.py | MIT |
def message_details(self):
"""Return a detailled string of the error.
"""
# () -> str
error_str = "Code: {}".format(self.code)
error_str += "\nMessage: {}".format(self.message)
if self.target:
error_str += "\nTarget: {}".format(self.target)
if self.details:
error_str += "\nException Details:"
for error_obj in self.details:
# Indent for visibility
error_str += "\n".join("\t" + s for s in str(error_obj).splitlines())
if self.innererror:
error_str += "\nInner error: {}".format(
json.dumps(self.innererror, indent=4)
)
return error_str | Return a detailled string of the error. | message_details | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_error_format.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_error_format.py | MIT |
def __str__(self):
"""Cloud error message."""
error_str = "Type: {}".format(self.type)
error_str += "\nInfo: {}".format(json.dumps(self.info, indent=4))
return error_str | Cloud error message. | __str__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_error_format.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_error_format.py | MIT |
def format_data(cls, data):
"""format input data"""
raise NotImplementedError() | format input data | format_data | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_arg_action.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_arg_action.py | MIT |
def _update_headers(self, headers):
"""Updates the Authorization header with the bearer token.
:param dict headers: The HTTP Request headers
"""
headers["Authorization"] = "Bearer {}".format(self._token.token)
if self._aux_tokens:
headers["x-ms-authorization-auxiliary"] = ', '.join(
"Bearer {}".format(token.token) for token in self._aux_tokens) | Updates the Authorization header with the bearer token.
:param dict headers: The HTTP Request headers | _update_headers | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | MIT |
def on_request(self, request):
"""Called before the policy sends a request.
The base implementation authorizes the request with a bearer token.
:param ~azure.core.pipeline.PipelineRequest request: the request
"""
self._enforce_https(request)
if self._need_new_token:
self._token = self._credential.get_token(*self._scopes)
if self._need_new_aux_tokens:
self._aux_tokens = self._credential.get_auxiliary_tokens(*self._scopes)
self._update_headers(request.http_request.headers) | Called before the policy sends a request.
The base implementation authorizes the request with a bearer token.
:param ~azure.core.pipeline.PipelineRequest request: the request | on_request | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | MIT |
def authorize_request(self, request, *scopes, **kwargs):
"""Acquire a token from the credential and authorize the request with it.
Keyword arguments are passed to the credential's get_token method. The token will be cached and used to
authorize future requests.
:param ~azure.core.pipeline.PipelineRequest request: the request
:param str scopes: required scopes of authentication
"""
if self._need_new_token:
self._token = self._credential.get_token(*scopes, **kwargs)
if self._need_new_aux_tokens:
self._aux_tokens = self._credential.get_auxiliary_tokens(*self._scopes)
self._update_headers(request.http_request.headers) | Acquire a token from the credential and authorize the request with it.
Keyword arguments are passed to the credential's get_token method. The token will be cached and used to
authorize future requests.
:param ~azure.core.pipeline.PipelineRequest request: the request
:param str scopes: required scopes of authentication | authorize_request | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | MIT |
def send(self, request):
"""Authorize request with a bearer token and send it to the next policy
:param request: The pipeline request object
:type request: ~azure.core.pipeline.PipelineRequest
"""
self.on_request(request)
try:
response = self.next.send(request)
self.on_response(request, response)
except Exception: # pylint:disable=broad-except
handled = self.on_exception(request)
if not handled:
raise
else:
if response.http_response.status_code == 401:
self._token = None # any cached token is invalid
if "WWW-Authenticate" in response.http_response.headers:
request_authorized = self.on_challenge(request, response)
if request_authorized:
try:
response = self.next.send(request)
self.on_response(request, response)
except Exception: # pylint:disable=broad-except
handled = self.on_exception(request)
if not handled:
raise
return response | Authorize request with a bearer token and send it to the next policy
:param request: The pipeline request object
:type request: ~azure.core.pipeline.PipelineRequest | send | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | MIT |
def on_challenge(self, request, response):
"""Authorize request according to an authentication challenge
This method is called when the resource provider responds 401 with a WWW-Authenticate header.
:param ~azure.core.pipeline.PipelineRequest request: the request which elicited an authentication challenge
:param ~azure.core.pipeline.PipelineResponse response: the resource provider's response
:returns: a bool indicating whether the policy should send the request
"""
# pylint:disable=unused-argument,no-self-use
return False | Authorize request according to an authentication challenge
This method is called when the resource provider responds 401 with a WWW-Authenticate header.
:param ~azure.core.pipeline.PipelineRequest request: the request which elicited an authentication challenge
:param ~azure.core.pipeline.PipelineResponse response: the resource provider's response
:returns: a bool indicating whether the policy should send the request | on_challenge | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | MIT |
def on_response(self, request, response):
"""Executed after the request comes back from the next policy.
:param request: Request to be modified after returning from the policy.
:type request: ~azure.core.pipeline.PipelineRequest
:param response: Pipeline response object
:type response: ~azure.core.pipeline.PipelineResponse
""" | Executed after the request comes back from the next policy.
:param request: Request to be modified after returning from the policy.
:type request: ~azure.core.pipeline.PipelineRequest
:param response: Pipeline response object
:type response: ~azure.core.pipeline.PipelineResponse | on_response | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | MIT |
def on_exception(self, request):
"""Executed when an exception is raised while executing the next policy.
This method is executed inside the exception handler.
:param request: The Pipeline request object
:type request: ~azure.core.pipeline.PipelineRequest
:return: False by default, override with True to stop the exception.
:rtype: bool
"""
# pylint: disable=no-self-use,unused-argument
return False | Executed when an exception is raised while executing the next policy.
This method is executed inside the exception handler.
:param request: The Pipeline request object
:type request: ~azure.core.pipeline.PipelineRequest
:return: False by default, override with True to stop the exception.
:rtype: bool | on_exception | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | MIT |
def _parse_claims_challenge(challenge):
"""Parse the "claims" parameter from an authentication challenge
Example challenge with claims:
Bearer authorization_uri="https://login.windows-ppe.net/", error="invalid_token",
error_description="User session has been revoked",
claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0="
:return: the challenge's "claims" parameter or None, if it doesn't contain that parameter
"""
encoded_claims = None
for parameter in challenge.split(","):
if "claims=" in parameter:
if encoded_claims:
# multiple claims challenges, e.g. for cross-tenant auth, would require special handling
return None
encoded_claims = parameter[parameter.index("=") + 1:].strip(" \"'")
if not encoded_claims:
return None
padding_needed = -len(encoded_claims) % 4
try:
decoded_claims = base64.urlsafe_b64decode(encoded_claims + "=" * padding_needed).decode()
return decoded_claims
except Exception: # pylint:disable=broad-except
return None | Parse the "claims" parameter from an authentication challenge
Example challenge with claims:
Bearer authorization_uri="https://login.windows-ppe.net/", error="invalid_token",
error_description="User session has been revoked",
claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0="
:return: the challenge's "claims" parameter or None, if it doesn't contain that parameter | _parse_claims_challenge | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | MIT |
def on_challenge(self, request, response): # pylint:disable=unused-argument
"""Authorize request according to an ARM authentication challenge
:param ~azure.core.pipeline.PipelineRequest request: the request which elicited an authentication challenge
:param ~azure.core.pipeline.PipelineResponse response: ARM's response
:returns: a bool indicating whether the policy should send the request
"""
challenge = response.http_response.headers.get("WWW-Authenticate")
if challenge:
claims = self._parse_claims_challenge(challenge)
if claims:
self.authorize_request(request, *self._scopes, claims=claims)
return True
return False | Authorize request according to an ARM authentication challenge
:param ~azure.core.pipeline.PipelineRequest request: the request which elicited an authentication challenge
:param ~azure.core.pipeline.PipelineResponse response: ARM's response
:returns: a bool indicating whether the policy should send the request | on_challenge | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/aaz/_http_policy.py | MIT |
def set_help_py(self):
self.helps['test'] = """
type: group
short-summary: Foo Bar Group
long-summary: Foo Bar Baz Group is a fun group
"""
self.helps['test alpha'] = """
type: command
short-summary: Foo Bar Command
long-summary: Foo Bar Baz Command is a fun command
parameters:
- name: --arg1 -a
short-summary: A short summary
populator-commands:
- az foo bar
- az bar baz
- name: ARG4 # Note: positional's are discouraged in the CLI.
short-summary: Positional parameter. Not required
examples:
- name: Alpha Example
text: az test alpha --arg1 a --arg2 b --arg3 c
supported-profiles: 2018-03-01-hybrid, latest
- name: A simple example unsupported on latest
text: az test alpha --arg1 a --arg2 b
unsupported-profiles: 2017-03-09-profile
""" | self.helps['test alpha'] = | set_help_py | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/tests/test_help.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/tests/test_help.py | MIT |
def _helper_get_clouds(_):
""" Helper method for multiprocessing.Pool.map func that uses throwaway arg """
get_clouds(DummyCli()) | Helper method for multiprocessing.Pool.map func that uses throwaway arg | _helper_get_clouds | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/tests/test_cloud.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/tests/test_cloud.py | MIT |
def sample_vm_get(resource_group_name, vm_name, opt_param=None, expand=None, custom_headers=None, raw=False,
**operation_config):
"""
The operation to get a virtual machine.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_name: The name of the virtual machine.
:type vm_name: str
:param opt_param: Used to verify reflection correctly
identifies optional params.
:type opt_param: object
:param expand: The expand expression to apply on the operation.
:type expand: str
:param dict custom_headers: headers that will be added to the request
:param boolean raw: returns the direct response alongside the
deserialized response
:rtype: VirtualMachine
:rtype: msrest.pipeline.ClientRawResponse if raw=True
"""
pass | The operation to get a virtual machine.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param vm_name: The name of the virtual machine.
:type vm_name: str
:param opt_param: Used to verify reflection correctly
identifies optional params.
:type opt_param: object
:param expand: The expand expression to apply on the operation.
:type expand: str
:param dict custom_headers: headers that will be added to the request
:param boolean raw: returns the direct response alongside the
deserialized response
:rtype: VirtualMachine
:rtype: msrest.pipeline.ClientRawResponse if raw=True | sample_vm_get | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/tests/test_command_registration.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/tests/test_command_registration.py | MIT |
def sample_sdk_method_with_weird_docstring(param_a, param_b, param_c): # pylint: disable=unused-argument
"""
An operation with nothing good.
:param dict param_a:
:param param_b: The name
of
nothing.
:param param_c: The name
of
nothing2.
""" | An operation with nothing good.
:param dict param_a:
:param param_b: The name
of
nothing.
:param param_c: The name
of
nothing2. | test_command_build_argument_help_text.sample_sdk_method_with_weird_docstring | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/tests/test_command_registration.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/tests/test_command_registration.py | MIT |
def test_command_build_argument_help_text(self):
def sample_sdk_method_with_weird_docstring(param_a, param_b, param_c): # pylint: disable=unused-argument
"""
An operation with nothing good.
:param dict param_a:
:param param_b: The name
of
nothing.
:param param_c: The name
of
nothing2.
"""
class TestCommandsLoader(AzCommandsLoader):
def load_command_table(self, args):
super().load_command_table(args)
with self.command_group('test command', operations_tmpl='{}#{{}}'.format(__name__)) as g:
g.command('foo', sample_sdk_method_with_weird_docstring.__name__)
return self.command_table
setattr(sys.modules[__name__], sample_sdk_method_with_weird_docstring.__name__,
sample_sdk_method_with_weird_docstring) # pylint: disable=line-too-long
cli = DummyCli(commands_loader_cls=TestCommandsLoader)
command = 'test command foo'
loader = _prepare_test_commands_loader(TestCommandsLoader, cli, command)
command_metadata = loader.command_table[command]
self.assertEqual(len(command_metadata.arguments), 3, 'We expected exactly 3 arguments')
some_expected_arguments = {
'param_a': CLIArgumentType(dest='param_a', required=True, help=''),
'param_b': CLIArgumentType(dest='param_b', required=True, help='The name of nothing.'),
'param_c': CLIArgumentType(dest='param_c', required=True, help='The name of nothing2.')
}
for probe in some_expected_arguments:
existing = next(arg for arg in command_metadata.arguments if arg == probe)
self.assertLessEqual(some_expected_arguments[existing].settings.items(),
command_metadata.arguments[existing].options.items()) | An operation with nothing good.
:param dict param_a:
:param param_b: The name
of
nothing.
:param param_c: The name
of
nothing2. | test_command_build_argument_help_text | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/tests/test_command_registration.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/tests/test_command_registration.py | MIT |
def dummy_handler(arg1, arg2=None, arg3=None, arg4=None):
"""
Short summary here. Long summary here. Still long summary.
:param arg1: arg1's docstring help text
:param arg2: arg2's docstring help text
:param arg3: arg3's docstring help text
:param arg4: arg4's docstring help text
"""
pass | Short summary here. Long summary here. Still long summary.
:param arg1: arg1's docstring help text
:param arg2: arg2's docstring help text
:param arg3: arg3's docstring help text
:param arg4: arg4's docstring help text | dummy_handler | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/tests/test_help_loaders.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/tests/test_help_loaders.py | MIT |
def test_format_styled_text_legacy_powershell(self, is_modern_terminal_mock, get_parent_proc_name_mock):
"""Verify bright/dark blue is replaced with the default color in legacy powershell.exe terminal."""
styled_text = [
(Style.ACTION, "Blue: Commands, parameters, and system inputs")
]
# Try to delete _is_legacy_powershell cache
try:
delattr(format_styled_text, '_is_legacy_powershell')
except AttributeError:
pass
# When theme is 'none', no need to call is_modern_terminal and get_parent_proc_name
formatted = format_styled_text(styled_text, theme='none')
is_modern_terminal_mock.assert_not_called()
get_parent_proc_name_mock.assert_not_called()
assert formatted == """Blue: Commands, parameters, and system inputs"""
excepted = """\x1b[0mBlue: Commands, parameters, and system inputs\x1b[0m"""
formatted = format_styled_text(styled_text, theme='dark')
assert formatted == excepted
formatted = format_styled_text(styled_text, theme='light')
assert formatted == excepted | Verify bright/dark blue is replaced with the default color in legacy powershell.exe terminal. | test_format_styled_text_legacy_powershell | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/tests/test_style.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/tests/test_style.py | MIT |
def test_no_extensions_dir(self):
""" Extensions directory doesn't exist """
shutil.rmtree(self.ext_dir)
actual = get_extensions(ext_type=WheelExtension)
self.assertEqual(len(actual), 0) | Extensions directory doesn't exist | test_no_extensions_dir | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/tests/test_extension.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/tests/test_extension.py | MIT |
def test_no_extensions_in_dir(self):
""" Directory exists but there are no extensions """
actual = get_extensions(ext_type=WheelExtension)
self.assertEqual(len(actual), 0) | Directory exists but there are no extensions | test_no_extensions_in_dir | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/tests/test_extension.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/tests/test_extension.py | MIT |
def __call__(self, parser, namespace, values, option_string=None):
""" Parse a date value and return the ISO8601 string. """
import dateutil.parser
import dateutil.tz
value_string = ' '.join(values)
dt_val = None
try:
# attempt to parse ISO 8601
dt_val = dateutil.parser.parse(value_string)
except ValueError:
pass
# TODO: custom parsing attempts here
if not dt_val:
raise CLIError("Unable to parse: '{}'. Expected format: {}".format(value_string, help_string))
if not dt_val.tzinfo and timezone:
dt_val = dt_val.replace(tzinfo=dateutil.tz.tzlocal())
# Issue warning if any supplied data will be ignored
if not date and any([dt_val.day, dt_val.month, dt_val.year]):
logger.warning('Date info will be ignored in %s.', value_string)
if not time and any([dt_val.hour, dt_val.minute, dt_val.second, dt_val.microsecond]):
logger.warning('Time info will be ignored in %s.', value_string)
if not timezone and dt_val.tzinfo:
logger.warning('Timezone info will be ignored in %s.', value_string)
iso_string = dt_val.isoformat()
setattr(namespace, self.dest, iso_string) | Parse a date value and return the ISO8601 string. | get_datetime_type.__call__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/parameters.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/parameters.py | MIT |
def get_datetime_type(help=None, date=True, time=True, timezone=True):
help_string = help + ' ' if help else ''
accepted_formats = []
if date:
accepted_formats.append('date (yyyy-mm-dd)')
if time:
accepted_formats.append('time (hh:mm:ss.xxxxx)')
if timezone:
accepted_formats.append('timezone (+/-hh:mm)')
help_string = help_string + 'Format: ' + ' '.join(accepted_formats)
# pylint: disable=too-few-public-methods
class DatetimeAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
""" Parse a date value and return the ISO8601 string. """
import dateutil.parser
import dateutil.tz
value_string = ' '.join(values)
dt_val = None
try:
# attempt to parse ISO 8601
dt_val = dateutil.parser.parse(value_string)
except ValueError:
pass
# TODO: custom parsing attempts here
if not dt_val:
raise CLIError("Unable to parse: '{}'. Expected format: {}".format(value_string, help_string))
if not dt_val.tzinfo and timezone:
dt_val = dt_val.replace(tzinfo=dateutil.tz.tzlocal())
# Issue warning if any supplied data will be ignored
if not date and any([dt_val.day, dt_val.month, dt_val.year]):
logger.warning('Date info will be ignored in %s.', value_string)
if not time and any([dt_val.hour, dt_val.minute, dt_val.second, dt_val.microsecond]):
logger.warning('Time info will be ignored in %s.', value_string)
if not timezone and dt_val.tzinfo:
logger.warning('Timezone info will be ignored in %s.', value_string)
iso_string = dt_val.isoformat()
setattr(namespace, self.dest, iso_string)
return CLIArgumentType(action=DatetimeAction, nargs='+', help=help_string) | Parse a date value and return the ISO8601 string. | get_datetime_type | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/parameters.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/parameters.py | MIT |
def get_three_state_flag(positive_label='true', negative_label='false', invert=False, return_label=False):
""" Creates a flag-like argument that can also accept positive/negative values. This allows
consistency between create commands that typically use flags and update commands that require
positive/negative values without introducing breaking changes. Flag-like behavior always
implies the affirmative unless invert=True then invert the logic.
- positive_label: label for the positive value (ex: 'enabled')
- negative_label: label for the negative value (ex: 'disabled')
- invert: invert the boolean logic for the flag
- return_label: if true, return the corresponding label. Otherwise, return a boolean value
"""
choices = [positive_label, negative_label]
# pylint: disable=too-few-public-methods
class ThreeStateAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
values = values or positive_label
is_positive = values.lower() == positive_label.lower()
is_positive = not is_positive if invert else is_positive
set_val = None
if return_label:
set_val = positive_label if is_positive else negative_label
else:
set_val = is_positive
setattr(namespace, self.dest, set_val)
params = {
'choices': CaseInsensitiveList(choices),
'nargs': '?',
'action': ThreeStateAction
}
return CLIArgumentType(**params) | Creates a flag-like argument that can also accept positive/negative values. This allows
consistency between create commands that typically use flags and update commands that require
positive/negative values without introducing breaking changes. Flag-like behavior always
implies the affirmative unless invert=True then invert the logic.
- positive_label: label for the positive value (ex: 'enabled')
- negative_label: label for the negative value (ex: 'disabled')
- invert: invert the boolean logic for the flag
- return_label: if true, return the corresponding label. Otherwise, return a boolean value | get_three_state_flag | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/parameters.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/parameters.py | MIT |
def get_enum_type(data, default=None):
""" Creates the argparse choices and type kwargs for a supplied enum type or list of strings. """
if not data:
return None
# transform enum types, otherwise assume list of string choices
try:
choices = [x.value for x in data]
except AttributeError:
choices = data
# pylint: disable=too-few-public-methods
class DefaultAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
def _get_value(val):
return next((x for x in self.choices if x.lower() == val.lower()), val)
if isinstance(values, list):
values = [_get_value(v) for v in values]
else:
values = _get_value(values)
setattr(args, self.dest, values)
def _type(value):
return next((x for x in choices if x.lower() == value.lower()), value) if value else value
default_value = None
if default:
default_value = next((x for x in choices if x.lower() == default.lower()), None)
if not default_value:
raise CLIError("Command authoring exception: unrecognized default '{}' from choices '{}'"
.format(default, choices))
arg_type = CLIArgumentType(choices=CaseInsensitiveList(choices), action=DefaultAction, default=default_value)
else:
arg_type = CLIArgumentType(choices=CaseInsensitiveList(choices), action=DefaultAction)
return arg_type | Creates the argparse choices and type kwargs for a supplied enum type or list of strings. | get_enum_type | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/parameters.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/parameters.py | MIT |
def _expansion_validator_impl(namespace):
"""
The validator create a argument of a given type from a specific set of arguments from CLI
command.
:param namespace: The argparse namespace represents the CLI arguments.
:return: The argument of specific type.
"""
ns = vars(namespace)
kwargs = {k: ns[k] for k in ns if k in set(expanded_arguments)}
setattr(namespace, assigned_arg, model_type(**kwargs)) | The validator create a argument of a given type from a specific set of arguments from CLI
command.
:param namespace: The argparse namespace represents the CLI arguments.
:return: The argument of specific type. | expand.expand.get_complex_argument_processor._expansion_validator_impl | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/parameters.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/parameters.py | MIT |
def get_complex_argument_processor(expanded_arguments, assigned_arg, model_type):
"""
Return a validator which will aggregate multiple arguments to one complex argument.
"""
def _expansion_validator_impl(namespace):
"""
The validator create a argument of a given type from a specific set of arguments from CLI
command.
:param namespace: The argparse namespace represents the CLI arguments.
:return: The argument of specific type.
"""
ns = vars(namespace)
kwargs = {k: ns[k] for k in ns if k in set(expanded_arguments)}
setattr(namespace, assigned_arg, model_type(**kwargs))
return _expansion_validator_impl | Return a validator which will aggregate multiple arguments to one complex argument. | expand.get_complex_argument_processor | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/parameters.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/parameters.py | MIT |
def expand(self, dest, model_type, group_name=None, patches=None):
# TODO:
# two privates symbols are imported here. they should be made public or this utility class
# should be moved into azure.cli.core
from knack.introspection import extract_args_from_signature, option_descriptions
self._check_stale()
if not self._applicable():
return
if not patches:
patches = {}
# fetch the documentation for model parameters first. for models, which are the classes
# derive from msrest.serialization.Model and used in the SDK API to carry parameters, the
# document of their properties are attached to the classes instead of constructors.
parameter_docs = option_descriptions(model_type)
def get_complex_argument_processor(expanded_arguments, assigned_arg, model_type):
"""
Return a validator which will aggregate multiple arguments to one complex argument.
"""
def _expansion_validator_impl(namespace):
"""
The validator create a argument of a given type from a specific set of arguments from CLI
command.
:param namespace: The argparse namespace represents the CLI arguments.
:return: The argument of specific type.
"""
ns = vars(namespace)
kwargs = {k: ns[k] for k in ns if k in set(expanded_arguments)}
setattr(namespace, assigned_arg, model_type(**kwargs))
return _expansion_validator_impl
expanded_arguments = []
for name, arg in extract_args_from_signature(model_type.__init__, excluded_params=EXCLUDED_PARAMS):
arg = arg.type
if name in parameter_docs:
arg.settings['help'] = parameter_docs[name]
if group_name:
arg.settings['arg_group'] = group_name
if name in patches:
patches[name](arg)
self.extra(name, arg_type=arg)
expanded_arguments.append(name)
dest_option = ['--__{}'.format(dest.upper())]
self.argument(dest,
arg_type=ignore_type,
options_list=dest_option,
validator=get_complex_argument_processor(expanded_arguments, dest, model_type)) | Return a validator which will aggregate multiple arguments to one complex argument. | expand | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/parameters.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/parameters.py | MIT |
def get_mgmt_service_client(cli_ctx, client_or_resource_type, subscription_id=None, api_version=None,
aux_subscriptions=None, aux_tenants=None, credential=None, **kwargs):
"""Create Python SDK mgmt-plane client. In addition to directly creating the client instance, this centralized
client factory adds more features to the client instance:
- multi-API
- server telemetry
- safe logging
- cross-tenant authentication
:param cli_ctx: AzCli instance
:param client_or_resource_type: Python SDK mgmt-plane client type or a member of
azure.cli.core.profiles._shared.ResourceType
:param subscription_id: Override the current login context's subscription
:param api_version: Override the client or resource type's default API version
:param aux_subscriptions: For cross-tenant authentication, such as vnet peering
:param aux_tenants: For cross-tenant authentication, such as vnet peering
:param credential: Custom credential to override the current login context's credential
For more information, see src/azure-cli-core/azure/cli/core/auth/msal_authentication.py
"""
if not subscription_id and 'subscription_id' in cli_ctx.data:
subscription_id = cli_ctx.data['subscription_id']
sdk_profile = None
if isinstance(client_or_resource_type, (ResourceType, CustomResourceType)):
# Get the versioned client
client_type = get_client_class(client_or_resource_type)
api_version = api_version or get_api_version(cli_ctx, client_or_resource_type, as_sdk_profile=True)
if isinstance(api_version, SDKProfile):
sdk_profile = api_version.profile
api_version = None
else:
# Get the non-versioned client
client_type = client_or_resource_type
client, _ = _get_mgmt_service_client(cli_ctx, client_type, subscription_id=subscription_id,
api_version=api_version, sdk_profile=sdk_profile,
aux_subscriptions=aux_subscriptions,
aux_tenants=aux_tenants, credential=credential,
**kwargs)
return client | Create Python SDK mgmt-plane client. In addition to directly creating the client instance, this centralized
client factory adds more features to the client instance:
- multi-API
- server telemetry
- safe logging
- cross-tenant authentication
:param cli_ctx: AzCli instance
:param client_or_resource_type: Python SDK mgmt-plane client type or a member of
azure.cli.core.profiles._shared.ResourceType
:param subscription_id: Override the current login context's subscription
:param api_version: Override the client or resource type's default API version
:param aux_subscriptions: For cross-tenant authentication, such as vnet peering
:param aux_tenants: For cross-tenant authentication, such as vnet peering
:param credential: Custom credential to override the current login context's credential
For more information, see src/azure-cli-core/azure/cli/core/auth/msal_authentication.py | get_mgmt_service_client | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/client_factory.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/client_factory.py | MIT |
def _prepare_client_kwargs_track2(cli_ctx):
"""Prepare kwargs for Track 2 SDK client."""
client_kwargs = {}
# Prepare connection_verify to change SSL verification behavior, used by ConnectionConfiguration
client_kwargs.update(_debug.change_ssl_cert_verification_track2())
# Prepare User-Agent header, used by UserAgentPolicy
client_kwargs['user_agent'] = get_az_user_agent()
try:
command_ext_name = cli_ctx.data['command_extension_name']
if command_ext_name:
client_kwargs['user_agent'] += "CliExtension/{}".format(command_ext_name)
except KeyError:
pass
# Prepare custom headers, used by HeadersPolicy
headers = dict(cli_ctx.data['headers'])
# - Prepare CommandName header
command_name_suffix = ';completer-request' if cli_ctx.data['completer_active'] else ''
headers['CommandName'] = "{}{}".format(cli_ctx.data['command'], command_name_suffix)
# - Prepare ParameterSetName header
if cli_ctx.data.get('safe_params'):
headers['ParameterSetName'] = ' '.join(cli_ctx.data['safe_params'])
client_kwargs['headers'] = headers
# Prepare x-ms-client-request-id header, used by RequestIdPolicy
if 'x-ms-client-request-id' in cli_ctx.data['headers']:
client_kwargs['request_id'] = cli_ctx.data['headers']['x-ms-client-request-id']
from azure.cli.core.sdk.policies import RecordTelemetryUserAgentPolicy
client_kwargs['user_agent_policy'] = RecordTelemetryUserAgentPolicy(**client_kwargs)
# Replace NetworkTraceLoggingPolicy to redact 'Authorization' and 'x-ms-authorization-auxiliary' headers.
# NetworkTraceLoggingPolicy: log raw network trace, with all headers.
from azure.cli.core.sdk.policies import SafeNetworkTraceLoggingPolicy
client_kwargs['logging_policy'] = SafeNetworkTraceLoggingPolicy()
# Disable ARMHttpLoggingPolicy.
# ARMHttpLoggingPolicy: Only log allowed information.
from azure.core.pipeline.policies import SansIOHTTPPolicy
client_kwargs['http_logging_policy'] = SansIOHTTPPolicy()
return client_kwargs | Prepare kwargs for Track 2 SDK client. | _prepare_client_kwargs_track2 | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/client_factory.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/client_factory.py | MIT |
def _prepare_mgmt_client_kwargs_track2(cli_ctx, cred):
"""Prepare kwargs for Track 2 SDK mgmt client."""
client_kwargs = _prepare_client_kwargs_track2(cli_ctx)
# Enable CAE support in mgmt SDK
from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy
# Track 2 SDK maintains `scopes` and passes `scopes` to get_token.
scopes = resource_to_scopes(cli_ctx.cloud.endpoints.active_directory_resource_id)
policy = ARMChallengeAuthenticationPolicy(cred, *scopes)
client_kwargs['credential_scopes'] = scopes
client_kwargs['authentication_policy'] = policy
# Track 2 currently lacks the ability to take external credentials.
# https://github.com/Azure/azure-sdk-for-python/issues/8313
# As a temporary workaround, manually add external tokens to 'x-ms-authorization-auxiliary' header.
# https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant
if hasattr(cred, "get_auxiliary_tokens"):
aux_tokens = cred.get_auxiliary_tokens(*scopes)
if aux_tokens:
# Hard-code scheme to 'Bearer' as _BearerTokenCredentialPolicyBase._update_headers does.
client_kwargs['headers']['x-ms-authorization-auxiliary'] = \
', '.join("Bearer {}".format(token.token) for token in aux_tokens)
return client_kwargs | Prepare kwargs for Track 2 SDK mgmt client. | _prepare_mgmt_client_kwargs_track2 | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/client_factory.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/client_factory.py | MIT |
def validate_tags(ns):
""" Extracts multiple space-separated tags in key[=value] format """
if isinstance(ns.tags, list):
tags_dict = {}
for item in ns.tags:
tags_dict.update(validate_tag(item))
ns.tags = tags_dict | Extracts multiple space-separated tags in key[=value] format | validate_tags | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/validators.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/validators.py | MIT |
def validate_tag(string):
""" Extracts a single tag in key[=value] format """
result = {}
if string:
comps = string.split('=', 1)
result = {comps[0]: comps[1]} if len(comps) > 1 else {string: ''}
return result | Extracts a single tag in key[=value] format | validate_tag | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/validators.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/validators.py | MIT |
def validate_key_value_pairs(string):
""" Validates key-value pairs in the following format: a=b;c=d """
result = None
if string:
kv_list = [x for x in string.split(';') if '=' in x] # key-value pairs
result = dict(x.split('=', 1) for x in kv_list)
return result | Validates key-value pairs in the following format: a=b;c=d | validate_key_value_pairs | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/commands/validators.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/commands/validators.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.