Skip to content

Commit

Permalink
Remove old command decorators and simplify command table (#265)
Browse files Browse the repository at this point in the history
  • Loading branch information
johanste committed May 16, 2016
1 parent ac698d7 commit 517872a
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 106 deletions.
14 changes: 9 additions & 5 deletions src/azure/cli/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import azure.cli._logging as _logging

logger = _logging.get_az_logger(__name__)
APPLICATION = None

class Configuration(object): # pylint: disable=too-few-public-methods
"""The configuration object tracks session specific data such
Expand All @@ -37,13 +36,11 @@ class Application(object):
TRANSFORM_RESULT = 'Application.TransformResults'
FILTER_RESULT = 'Application.FilterResults'
GLOBAL_PARSER_CREATED = 'GlobalParser.Created'
COMMAND_PARSER_CREATED = 'CommandParser.Created'
COMMAND_PARSER_LOADED = 'CommandParser.Loaded'
COMMAND_PARSER_PARSED = 'CommandParser.Parsed'

def __init__(self, configuration):
def __init__(self, config=None):
self._event_handlers = defaultdict(lambda: [])
self.configuration = configuration

# Register presence of and handlers for global parameters
self.register(self.GLOBAL_PARSER_CREATED, Application._register_builtin_arguments)
Expand All @@ -58,7 +55,12 @@ def __init__(self, configuration):
self.raise_event(self.GLOBAL_PARSER_CREATED, global_group=global_group)

self.parser = AzCliCommandParser(prog='az', parents=[self.global_parser])
self.raise_event(self.COMMAND_PARSER_CREATED, parser=self.parser)

if config:
self.initialize(config)

def initialize(self, configuration):
self.configuration = configuration

def execute(self, argv):
command_table = self.configuration.get_command_table()
Expand Down Expand Up @@ -159,3 +161,5 @@ def _handle_builtin_arguments(self, **kwargs):
args = kwargs['args']
self.configuration.output_format = args._output_format #pylint: disable=protected-access
del args._output_format

APPLICATION = Application()
36 changes: 1 addition & 35 deletions src/azure/cli/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,40 +107,6 @@ class CommandTable(defaultdict):
def __init__(self):
super(CommandTable, self).__init__(lambda: {'arguments': []})

def command(self, name, **kwargs):
def wrapper(func):
self[func]['name'] = name
self[func].update(kwargs)
return func
return wrapper

def description(self, description):
def wrapper(func):
self[func]['description'] = description
return func
return wrapper

def help(self, help_file):
def wrapper(func):
self[func]['help_file'] = help_file
return func
return wrapper

def option(self, name, **kwargs):
def wrapper(func):
opt = dict(kwargs)
opt['name'] = name
self[func]['arguments'].append(opt)
return func
return wrapper

def option_set(self, options):
def wrapper(func):
for opt in options:
self[func]['arguments'].append(opt)
return func
return wrapper

def _get_command_table(module_name):
module = import_module('azure.cli.command_modules.' + module_name)
return module.command_table
Expand All @@ -167,5 +133,5 @@ def get_command_table(module_name=None):
for mod in INSTALLED_COMMAND_MODULES:
command_table.update(_get_command_table(mod))

ordered_commands = OrderedDict(sorted(command_table.items(), key=lambda item: item[1]['name']))
ordered_commands = OrderedDict(command_table)
return ordered_commands
4 changes: 2 additions & 2 deletions src/azure/cli/commands/_auto_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,8 @@ def build_operation(command_name,
for arg in extra_parameters.keys():
options.append(extra_parameters[arg].copy())

command_table[func] = {
'name': ' '.join([command_name, op.opname]),
full_command_name = ' '.join([command_name, op.opname])
command_table[full_command_name] = {
'handler': func,
'arguments': options
}
11 changes: 6 additions & 5 deletions src/azure/cli/main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
import sys

import azure.cli.application as application
from azure.cli.application import APPLICATION, Configuration
import azure.cli._logging as _logging
from ._session import Session
from ._output import OutputProducer
Expand Down Expand Up @@ -34,14 +34,15 @@ def main(args, file=sys.stdout): #pylint: disable=redefined-builtin
'locale',
CONFIG.get('locale', 'en-US')))

config = application.Configuration(args)
application.APPLICATION = app = application.Application(config)
config = Configuration(args)
APPLICATION.initialize(config)

try:
cmd_result = app.execute(args)
cmd_result = APPLICATION.execute(args)
# Commands can return a dictionary/list of results
# If they do, we print the results.
if cmd_result:
formatter = OutputProducer.get_formatter(app.configuration.output_format)
formatter = OutputProducer.get_formatter(APPLICATION.configuration.output_format)
OutputProducer(formatter=formatter, file=file).out(cmd_result)
except CLIError as ex:
logger.error(ex.args[0])
Expand Down
12 changes: 6 additions & 6 deletions src/azure/cli/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ def load_command_table(self, command_table):
sp.required = True
self.subparsers = {(): sp}

for handler, metadata in command_table.items():
subparser = self._get_subparser(metadata['name'].split())
command_name = metadata['name'].split()[-1]
for command_name, metadata in command_table.items():
subparser = self._get_subparser(command_name.split())
command_verb = command_name.split()[-1]
# To work around http://bugs.python.org/issue9253, we artificially add any new
# parsers we add to the "choices" section of the subparser.
subparser.choices[command_name] = command_name
command_parser = subparser.add_parser(command_name,
subparser.choices[command_verb] = command_verb
command_parser = subparser.add_parser(command_verb,
description=metadata.get('description'),
parents=self.parents, conflict_handler='resolve',
help_file=metadata.get('help_file'))
Expand All @@ -45,7 +45,7 @@ def load_command_table(self, command_table):
*names, **{k:v for k, v in arg.items() if k != 'name'})
param.completer = completer

command_parser.set_defaults(func=handler, command=metadata['name'])
command_parser.set_defaults(func=metadata['handler'], command=command_name)

def _get_subparser(self, path):
"""For each part of the path, walk down the tree of
Expand Down
14 changes: 5 additions & 9 deletions src/azure/cli/tests/test_autocommand.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,7 @@ def test_autocommand_basic(self):
command_table)

self.assertEqual(len(command_table), 1, 'We expect exactly one command in the command table')
command_metadata = list(command_table.values())[0]
self.assertEqual(command_metadata['name'], 'test autocommand sample-vm-get', 'Unexpected command name...')
command_metadata = command_table['test autocommand sample-vm-get']
self.assertEqual(len(command_metadata['arguments']), 4, 'We expected exactly 4 arguments')
some_expected_arguments = [
{'name': '--resource-group -g', 'dest': 'resource_group_name', 'required': True, 'help':'The name of the resource group'},
Expand Down Expand Up @@ -85,8 +84,7 @@ def test_autocommand_with_parameter_alias(self):
)

self.assertEqual(len(command_table), 1, 'We expect exactly one command in the command table')
command_metadata = list(command_table.values())[0]
self.assertEqual(command_metadata['name'], 'test autocommand sample-vm-get', 'Unexpected command name...')
command_metadata = command_table['test autocommand sample-vm-get']
self.assertEqual(len(command_metadata['arguments']), 4, 'We expected exactly 4 arguments')
some_expected_arguments = [
{'name': '--resource-group -g', 'dest': 'resource_group_name', 'required': True},
Expand Down Expand Up @@ -156,8 +154,7 @@ def test_autocommand_with_extra_parameters(self):
)

self.assertEqual(len(command_table), 1, 'We expect exactly one command in the command table')
command_metadata = list(command_table.values())[0]
self.assertEqual(command_metadata['name'], 'test autocommand sample-vm-get', 'Unexpected command name...')
command_metadata = command_table['test autocommand sample-vm-get']
self.assertEqual(len(command_metadata['arguments']), 5, 'We expected exactly 5 arguments')
some_expected_arguments = [
{'name': '--resource-group -g', 'dest': 'resource_group_name', 'required': True},
Expand All @@ -181,8 +178,7 @@ def test_autocommand_with_command_alias(self):
)

self.assertEqual(len(command_table), 1, 'We expect exactly one command in the command table')
command_metadata = list(command_table.values())[0]
self.assertEqual(command_metadata['name'], 'test autocommand woot', 'Unexpected command name...')
self.assertTrue('test autocommand woot' in command_table, 'Unexpected command name...')

def test_autocommand_build_argument_help_text(self):
def sample_sdk_method_with_weired_docstring(self, param_a, param_b, param_c):
Expand All @@ -207,7 +203,7 @@ def sample_sdk_method_with_weired_docstring(self, param_a, param_b, param_c):
],
command_table)

command_metadata = list(command_table.values())[0]
command_metadata = command_table['test autocommand sample-sdk-method-with-weired-docstring']
self.assertEqual(len(command_metadata['arguments']), 3, 'We expected exactly 3 arguments')
some_expected_arguments = [
{'name': '--param-a', 'dest': 'param_a', 'required': True, 'help': ''},
Expand Down
Loading

0 comments on commit 517872a

Please sign in to comment.