def main(args, file=sys.stdout): #pylint: disable=redefined-builtin _logging.configure_logging(args) if len(args) > 0 and args[0] == '--version': show_version_info_exit(file) azure_folder = os.path.expanduser('~/.azure') if not os.path.exists(azure_folder): os.makedirs(azure_folder) ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json')) CONFIG.load(os.path.join(azure_folder, 'az.json')) SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600) config = Configuration(args) APPLICATION.initialize(config) try: cmd_result = APPLICATION.execute(args) # Commands can return a dictionary/list of results # If they do, we print the results. if cmd_result and cmd_result.result: formatter = OutputProducer.get_formatter( APPLICATION.configuration.output_format) OutputProducer(formatter=formatter, file=file).out(cmd_result) except Exception as ex: # pylint: disable=broad-except log_telemetry('Error', log_type='trace') error_code = handle_exception(ex) return error_code
def main(args, file=sys.stdout): # pylint: disable=redefined-builtin azlogging.configure_logging(args) logger.debug('Command arguments %s', args) if len(args) > 0 and args[0] == '--version': show_version_info_exit(file) azure_folder = get_config_dir() if not os.path.exists(azure_folder): os.makedirs(azure_folder) ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json')) CONFIG.load(os.path.join(azure_folder, 'az.json')) SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600) APPLICATION.initialize(Configuration()) try: cmd_result = APPLICATION.execute(args) # Commands can return a dictionary/list of results # If they do, we print the results. if cmd_result and cmd_result.result is not None: from azure.cli.core._output import OutputProducer formatter = OutputProducer.get_formatter(APPLICATION.configuration.output_format) OutputProducer(formatter=formatter, file=file).out(cmd_result) except Exception as ex: # pylint: disable=broad-except # TODO: include additional details of the exception in telemetry telemetry.set_exception(ex, 'outer-exception', 'Unexpected exception caught during application execution.') telemetry.set_failure() error_code = handle_exception(ex) return error_code
def main(args, file=sys.stdout): #pylint: disable=redefined-builtin _logging.configure_logging(args) if len(args) > 0 and args[0] == '--version': show_version_info_exit(file) azure_folder = os.path.expanduser('~/.azure') if not os.path.exists(azure_folder): os.makedirs(azure_folder) ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json')) CONFIG.load(os.path.join(azure_folder, 'az.json')) SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600) config = Configuration(args) APPLICATION.initialize(config) try: cmd_result = APPLICATION.execute(args) # Commands can return a dictionary/list of results # If they do, we print the results. if cmd_result and cmd_result.result: from azure.cli.core._output import OutputProducer formatter = OutputProducer.get_formatter(APPLICATION.configuration.output_format) OutputProducer(formatter=formatter, file=file).out(cmd_result) except Exception as ex: # pylint: disable=broad-except from azure.cli.core.telemetry import log_telemetry log_telemetry('Error', log_type='trace') error_code = handle_exception(ex) return error_code
def initialize_client(): azure_folder = get_config_dir() if not os.path.exists(azure_folder): os.makedirs(azure_folder) ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json')) CONFIG.load(os.path.join(azure_folder, 'az.json')) SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600) APPLICATION.initialize(Configuration())
def mock_echo_args(command_name, parameters): try: argv = ' '.join((command_name, parameters)).split() APPLICATION.initialize(Configuration(argv)) command_table = APPLICATION.configuration.get_command_table() prefunc = command_table[command_name].handler command_table[command_name].handler = lambda args: args parsed_namespace = APPLICATION.execute(argv) return parsed_namespace finally: command_table[command_name].handler = prefunc
def mock_echo_args(command_name, parameters): try: argv = ' '.join((command_name, parameters)).split() APPLICATION.initialize(Configuration(argv)) command_table = APPLICATION.configuration.get_command_table() prefunc = command_table[command_name].handler command_table[command_name].handler = lambda args: args parsed_namespace = APPLICATION.execute(argv) return parsed_namespace finally: command_table[command_name].handler = prefunc
def test_command_consistency(self): argv = ['vm'] APPLICATION.initialize(Configuration()) command_table = APPLICATION.configuration.get_command_table(argv) vm_commands = ((vm_command, metadata) for vm_command, metadata in command_table.items() if vm_command.startswith('vm')) for command_name, command_metadata in vm_commands: for argument_name, expected_options_list in self.consistent_arguments.items(): try: actual_options_list = command_metadata.arguments[argument_name].options_list self.assertEqual(actual_options_list, expected_options_list, 'Argument {} of command {} has inconsistent flags'.format( argument_name, command_name )) except KeyError: pass
def test_generic_update_ids(self): my_objs = [ { 'prop': 'val', 'list': [ 'a', 'b', ['c', {'d': 'e'}] ] }, { 'prop': 'val', 'list': [ 'a', 'b', ['c', {'d': 'e'}] ] }] def my_get(name, resource_group): #pylint:disable=unused-argument # name is None when tests are run in a batch on Python <=2.7.9 if sys.version_info < (2, 7, 10): return my_objs[0] return my_objs[int(name)] def my_set(**kwargs): #pylint:disable=unused-argument return my_objs register_cli_argument('gencommand', 'name', CliArgumentType(options_list=('--name', '-n'), metavar='NAME', id_part='name')) cli_generic_update_command('gencommand', my_get, my_set) config = Configuration([]) APPLICATION.initialize(config) id_str = ('/subscriptions/00000000-0000-0000-0000-0000000000000/resourceGroups/rg/' 'providers/Microsoft.Compute/virtualMachines/') APPLICATION.execute('gencommand --ids {0}0 {0}1 --resource-group bar --set prop=newval' .format(id_str).split()) self.assertEqual(my_objs[0]['prop'], 'newval', 'first object updated') # name is None when tests are run in a batch on Python <=2.7.9 if not sys.version_info < (2, 7, 10): self.assertEqual(my_objs[1]['prop'], 'newval', 'second object updated')
def test_generic_update_ids(self): my_objs = [{ 'prop': 'val', 'list': ['a', 'b', ['c', { 'd': 'e' }]] }, { 'prop': 'val', 'list': ['a', 'b', ['c', { 'd': 'e' }]] }] def my_get(name, resource_group): #pylint:disable=unused-argument # name is None when tests are run in a batch on Python <=2.7.9 if sys.version_info < (2, 7, 10): return my_objs[0] return my_objs[int(name)] def my_set(**kwargs): #pylint:disable=unused-argument return my_objs register_cli_argument( 'gencommand', 'name', CliArgumentType(options_list=('--name', '-n'), metavar='NAME', id_part='name')) cli_generic_update_command('gencommand', my_get, my_set) config = Configuration([]) APPLICATION.initialize(config) id_str = ( '/subscriptions/00000000-0000-0000-0000-0000000000000/resourceGroups/rg/' 'providers/Microsoft.Compute/virtualMachines/') APPLICATION.execute( 'gencommand --ids {0}0 {0}1 --resource-group bar --set prop=newval' .format(id_str).split()) self.assertEqual(my_objs[0]['prop'], 'newval', 'first object updated') # name is None when tests are run in a batch on Python <=2.7.9 if not sys.version_info < (2, 7, 10): self.assertEqual(my_objs[1]['prop'], 'newval', 'second object updated')
def main(args, output=sys.stdout, logging_stream=None): configure_logging(args, logging_stream) logger = get_az_logger(__name__) logger.debug('Command arguments %s', args) if args and (args[0] == '--version' or args[0] == '-v'): show_version_info_exit(output) azure_folder = get_config_dir() if not os.path.exists(azure_folder): os.makedirs(azure_folder) ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json')) CONFIG.load(os.path.join(azure_folder, 'az.json')) SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600) APPLICATION.initialize(Configuration()) try: cmd_result = APPLICATION.execute(args) # Commands can return a dictionary/list of results # If they do, we print the results. if cmd_result and cmd_result.result is not None: from azure.cli.core._output import OutputProducer formatter = OutputProducer.get_formatter( APPLICATION.configuration.output_format) OutputProducer(formatter=formatter, file=output).out(cmd_result) except Exception as ex: # pylint: disable=broad-except # TODO: include additional details of the exception in telemetry telemetry.set_exception( ex, 'outer-exception', 'Unexpected exception caught during application execution.') telemetry.set_failure() error_code = handle_exception(ex) return error_code
def dump_no_help(modules): APPLICATION.initialize(Configuration()) cmd_table = APPLICATION.configuration.get_command_table() exit_val = 0 for cmd in cmd_table: cmd_table[cmd].load_arguments() for mod in modules: try: import_module('azure.cli.command_modules.' + mod).load_params(mod) except Exception as ex: print("EXCEPTION: " + str(mod)) _update_command_definitions(cmd_table) add_id_parameters(cmd_table) with open(WHITE_DATA_FILE, 'r') as white: white_data = json.load(white) white_list_commands = set(white_data.get('commands', [])) white_list_subgroups = set(white_data.get('subgroups', [])) white_list_parameters = white_data.get('parameters', {}) command_list = set() subgroups_list = set() parameters = {} for cmd in cmd_table: if not cmd_table[cmd].description and cmd not in helps and cmd not in white_list_commands: command_list.add(cmd) exit_val = 1 group_name = " ".join(cmd.split()[:-1]) if group_name not in helps: if group_name not in subgroups_list and group_name not in white_list_subgroups and group_name: exit_val = 1 subgroups_list.add(group_name) param_list = set() for key in cmd_table[cmd].arguments: name = cmd_table[cmd].arguments[key].name if not cmd_table[cmd].arguments[key].type.settings.get('help') and \ name not in white_list_parameters.get(cmd, []): exit_val = 1 param_list.add(name) if param_list: parameters[cmd] = param_list for cmd in helps: diction_help = yaml.load(helps[cmd]) if "short-summary" in diction_help and "type" in diction_help: if diction_help["type"] == "command" and cmd in command_list: command_list.remove(cmd) elif diction_help["type"] == "group" and cmd in subgroups_list: subgroups_list.remove(cmd) if "parameters" in diction_help: for param in diction_help["parameters"]: if "short-summary" in param and param["name"].split()[0] in parameters: parameters.pop(cmd, None) data = { "subgroups": subgroups_list, "commands": command_list, "parameters": parameters } return exit_val, data
from __future__ import print_function from importlib import import_module import json import os import pkgutil import yaml from azure.cli.core.application import APPLICATION, Configuration from azure.cli.core.commands import _update_command_definitions, BLACKLISTED_MODS from azure.cli.core.help_files import helps from azure.cli.core.commands.arm import add_id_parameters import azclishell.configuration as config APPLICATION.initialize(Configuration()) CMD_TABLE = APPLICATION.configuration.get_command_table() def install_modules(): for cmd in CMD_TABLE: CMD_TABLE[cmd].load_arguments() try: mods_ns_pkg = import_module('azure.cli.command_modules') installed_command_modules = [ modname for _, modname, _ in pkgutil.iter_modules(mods_ns_pkg.__path__) if modname not in BLACKLISTED_MODS ] except ImportError:
def dump_no_help(modules): APPLICATION.initialize(Configuration()) cmd_table = APPLICATION.configuration.get_command_table() exit_val = 0 for cmd in cmd_table: cmd_table[cmd].load_arguments() for mod in modules: try: import_module('azure.cli.command_modules.' + mod).load_params(mod) except Exception as ex: print("EXCEPTION: {} for module {}".format(ex, str(mod))) _update_command_definitions(cmd_table) add_id_parameters(cmd_table) with open(WHITE_DATA_FILE, 'r') as white: white_data = json.load(white) white_list_commands = set(white_data.get('commands', [])) white_list_subgroups = set(white_data.get('subgroups', [])) white_list_parameters = white_data.get('parameters', {}) command_list = set() subgroups_list = set() parameters = {} for cmd in cmd_table: if not cmd_table[ cmd].description and cmd not in helps and cmd not in white_list_commands: command_list.add(cmd) exit_val = 1 group_name = " ".join(cmd.split()[:-1]) if group_name not in helps: if group_name not in subgroups_list and group_name not in white_list_subgroups and group_name: exit_val = 1 subgroups_list.add(group_name) param_list = set() for key in cmd_table[cmd].arguments: name = cmd_table[cmd].arguments[key].name if not cmd_table[cmd].arguments[key].type.settings.get( 'help') and name not in white_list_parameters.get(cmd, []): exit_val = 1 param_list.add(name) if param_list: parameters[cmd] = param_list for cmd in helps: diction_help = yaml.load(helps[cmd]) if "short-summary" in diction_help and "type" in diction_help: if diction_help["type"] == "command" and cmd in command_list: command_list.remove(cmd) elif diction_help["type"] == "group" and cmd in subgroups_list: subgroups_list.remove(cmd) if "parameters" in diction_help: for param in diction_help["parameters"]: if "short-summary" in param and param["name"].split( )[0] in parameters: parameters.pop(cmd, None) data = { "subgroups": subgroups_list, "commands": command_list, "parameters": parameters } return exit_val, data
def load_command_table(): APPLICATION.initialize(Configuration()) command_table = APPLICATION.configuration.get_command_table() _install_modules(command_table) return command_table
from __future__ import print_function from importlib import import_module import json import os import pkgutil import yaml from azure.cli.core.application import APPLICATION, Configuration from azure.cli.core.commands import _update_command_definitions, BLACKLISTED_MODS from azure.cli.core.help_files import helps from azure.cli.core.commands.arm import add_id_parameters import azclishell.configuration as config APPLICATION.initialize(Configuration()) CMD_TABLE = APPLICATION.configuration.get_command_table() def install_modules(): installed_command_modules = [] for cmd in CMD_TABLE: try: CMD_TABLE[cmd].load_arguments() except (ImportError, ValueError): pass mods_ns_pkg = import_module('azure.cli.command_modules') for _, modname, _ in pkgutil.iter_modules(mods_ns_pkg.__path__): if modname not in BLACKLISTED_MODS: installed_command_modules.append(modname)