Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions src/alias_msrc_test/azext_alias/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

from argcomplete.completers import FilesCompleter # pylint: disable=import-error

from azure.cli.core import AzCommandsLoader
from azure.cli.core.decorators import Completer
from azure.cli.core.commands.events import (
EVENT_INVOKER_PRE_CMD_TBL_TRUNCATE, EVENT_INVOKER_ON_TAB_COMPLETION, EVENT_INTERACTIVE_PRE_COMPLETER_TEXT_PARSING,
EVENT_INTERACTIVE_POST_SUB_TREE_CREATE)

from azext_alias.util import get_alias_table
from azext_alias._validators import (
process_alias_create_namespace,
process_alias_import_namespace,
process_alias_export_namespace
)
from azext_alias import _help # pylint: disable=unused-import
from azext_alias.hooks import (
alias_event_handler,
enable_aliases_autocomplete,
transform_cur_commands_interactive,
enable_aliases_autocomplete_interactive
)


# We don't have access to load_cmd_tbl_func in custom.py (need the entire command table
# for alias and command validation when the user invokes alias create).
# This cache saves the entire command table globally so custom.py can have access to it.
# Alter this cache through cache_reserved_commands(load_cmd_tbl_func) in util.py
cached_reserved_commands = []


class AliasExtCommandLoader(AzCommandsLoader):

def __init__(self, cli_ctx=None):
from azure.cli.core.commands import CliCommandType
custom_command_type = CliCommandType(operations_tmpl='azext_alias.custom#{}')
super(AliasExtCommandLoader, self).__init__(cli_ctx=cli_ctx,
custom_command_type=custom_command_type)
self.cli_ctx.register_event(EVENT_INVOKER_PRE_CMD_TBL_TRUNCATE, alias_event_handler)
self.cli_ctx.register_event(EVENT_INVOKER_ON_TAB_COMPLETION, enable_aliases_autocomplete)
self.cli_ctx.register_event(EVENT_INTERACTIVE_PRE_COMPLETER_TEXT_PARSING, transform_cur_commands_interactive)
self.cli_ctx.register_event(EVENT_INTERACTIVE_POST_SUB_TREE_CREATE, enable_aliases_autocomplete_interactive)

def load_command_table(self, _):

with self.command_group('alias') as g:
g.custom_command('create', 'create_alias', validator=process_alias_create_namespace)
g.custom_command('export', 'export_aliases', validator=process_alias_export_namespace)
g.custom_command('import', 'import_aliases', validator=process_alias_import_namespace)
g.custom_command('list', 'list_alias')
g.custom_command('remove', 'remove_alias')
g.custom_command('remove-all', 'remove_all_aliases',
confirmation='Are you sure you want to remove all registered aliases?')

return self.command_table

def load_arguments(self, _):
with self.argument_context('alias create') as c:
c.argument('alias_name', options_list=['--name', '-n'], help='The name of the alias.')
c.argument('alias_command', options_list=['--command', '-c'], help='The command that the alias points to.')

with self.argument_context('alias export') as c:
c.argument('export_path', options_list=['--path', '-p'],
help='The path of the alias configuration file to export to', completer=FilesCompleter())
c.argument('exclusions', options_list=['--exclude', '-e'],
help='Space-separated aliases excluded from export', completer=get_alias_completer, nargs='*')

with self.argument_context('alias import') as c:
c.argument('alias_source', options_list=['--source', '-s'],
help='The source of the aliases to import from.', completer=FilesCompleter())

with self.argument_context('alias remove') as c:
c.argument('alias_names', options_list=['--name', '-n'], help='Space-separated aliases',
completer=get_alias_completer, nargs='*')


@Completer
def get_alias_completer(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument
"""
An argument completer for alias name.
"""
return get_alias_table().sections()


COMMAND_LOADER_CLS = AliasExtCommandLoader
37 changes: 37 additions & 0 deletions src/alias_msrc_test/azext_alias/_const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

import os

from azure.cli.core._environment import get_config_dir

GLOBAL_CONFIG_DIR = get_config_dir()
ALIAS_FILE_NAME = 'alias'
ALIAS_HASH_FILE_NAME = 'alias.sha1'
COLLIDED_ALIAS_FILE_NAME = 'collided_alias'
ALIAS_TAB_COMP_TABLE_FILE_NAME = 'alias_tab_completion'
GLOBAL_ALIAS_TAB_COMP_TABLE_PATH = os.path.join(GLOBAL_CONFIG_DIR, ALIAS_TAB_COMP_TABLE_FILE_NAME)
COLLISION_CHECK_LEVEL_DEPTH = 5

INSUFFICIENT_POS_ARG_ERROR = 'alias: "{}" takes exactly {} positional argument{} ({} given)'
CONFIG_PARSING_ERROR = 'alias: Please ensure you have a valid alias configuration file. Error detail: %s'
DEBUG_MSG = 'Alias Manager: Transforming "%s" to "%s"'
DEBUG_MSG_WITH_TIMING = 'Alias Manager: Transformed args to %s in %.3fms'
POS_ARG_DEBUG_MSG = 'Alias Manager: Transforming "%s" to "%s", with the following positional arguments: %s'
DUPLICATED_PLACEHOLDER_ERROR = 'alias: Duplicated placeholders found when transforming "{}"'
RENDER_TEMPLATE_ERROR = 'alias: Encounted error when injecting positional arguments to "{}". Error detail: {}'
PLACEHOLDER_EVAL_ERROR = 'alias: Encounted error when evaluating "{}". Error detail: {}'
PLACEHOLDER_BRACKETS_ERROR = 'alias: Brackets in "{}" are not enclosed properly'
ALIAS_NOT_FOUND_ERROR = 'alias: "{}" alias not found'
INVALID_ALIAS_COMMAND_ERROR = 'alias: Invalid Azure CLI command "{}"'
EMPTY_ALIAS_ERROR = 'alias: Empty alias name or command is invalid'
INVALID_STARTING_CHAR_ERROR = 'alias: Alias name should not start with "{}"'
INCONSISTENT_ARG_ERROR = 'alias: Positional argument{} {} {} not in both alias name and alias command'
COMMAND_LVL_ERROR = 'alias: "{}" is a reserved command and cannot be used to represent "{}"'
ALIAS_FILE_NOT_FOUND_ERROR = 'alias: File not found'
ALIAS_FILE_DIR_ERROR = 'alias: {} is a directory'
ALIAS_FILE_URL_ERROR = 'alias: Encounted error when retrieving alias file from {}. Error detail: {}'
POST_EXPORT_ALIAS_MSG = 'alias: Exported alias configuration file to %s.'
FILE_ALREADY_EXISTS_ERROR = 'alias: {} already exists.'
71 changes: 71 additions & 0 deletions src/alias_msrc_test/azext_alias/_help.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

# pylint: disable=line-too-long

from knack.help_files import helps # pylint: disable=unused-import


helps['alias'] = """
type: group
short-summary: Manage Azure CLI Aliases.
"""


helps['alias create'] = """
type: command
short-summary: Create an alias.
examples:
- name: Create simple alias commands.
text: |
az alias create --name rg --command group

az alias create --name ls --command list
- name: Create a complex alias.
text: |
az alias create --name list-vm --command 'vm list --resource-group myResourceGroup'

- name: Create an alias command with arguments.
text: |
az alias create --name 'list-vm {{ resource_group }}' \\
--command 'vm list --resource-group {{ resource_group }}'

- name: Process arguments using Jinja2 templates.
text: |
az alias create --name 'storage-ls {{ url }}' \\
--command 'storage blob list
--account-name {{ url.replace("https://", "").split(".")[0] }}
--container-name {{ url.replace("https://", "").split("/")[1] }}'
"""


helps['alias export'] = """
type: command
short-summary: Export all registered aliases to a given path, as an INI configuration file. If no export path is specified, the alias configuration file is exported to the current working directory.
"""


helps['alias import'] = """
type: command
short-summary: Import aliases from an INI configuration file or an URL.
"""


helps['alias list'] = """
type: command
short-summary: List the registered aliases.
"""


helps['alias remove'] = """
type: command
short-summary: Remove one or more aliases. Aliases to be removed are space-delimited.
"""


helps['alias remove-all'] = """
type: command
short-summary: Remove all registered aliases.
"""
Loading
Loading