Beispiel #1
0
def main():
    """ the main function """

    azure_folder = cli_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)

    config = CONFIGURATION

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        APPLICATION.execute(["configure"])
        print("When in doubt, ask for 'help'")
        config.firsttime()

    shell_app = Shell(
        completer=AZCOMPLETER,
        lexer=AzLexer,
        history=FileHistory(os.path.join(CONFIGURATION.get_config_dir(), config.get_history())),
        app=APPLICATION,
        # cli_config=os.path.join(azure_folder, 'config')
    )
    shell_app.run()
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
Beispiel #3
0
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
Beispiel #4
0
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 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')
Beispiel #6
0
    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 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
Beispiel #9
0
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
Beispiel #10
0
                break
        if not all_match:
            test_list.pop()
        else:
            return test_entry
    return '_ROOT_'

def _process_null_values(dict_):
    if hide_nulls:
        null_values = [x for x in dict_.keys() if dict_[x] is None]
        for key in null_values:
            dict_.pop(key)

def _dashed_to_camel(string):
    return string.replace('-', '_')

parser = argparse.ArgumentParser(description='Command Table Parser')
parser.add_argument('--commands', metavar='N', nargs='+', help='Filter by first level command (OR)')
parser.add_argument('--params', metavar='N', nargs='+', help='Filter by parameters (OR)')
parser.add_argument('--hide-nulls', action='store_true', default=False, help='Show null entries')
args = parser.parse_args()
cmd_set_names = args.commands
param_names = [_dashed_to_camel(x) for x in args.params or []]
hide_nulls = args.hide_nulls

PRIMITIVES = (str, int, bool, float)
IGNORE_ARGS = ['help', 'help_file', 'base_type']

APPLICATION.register(Application.COMMAND_PARSER_LOADED, _dump_command_table)
APPLICATION.execute([])
            dict_.pop(key)


def _dashed_to_camel(string):
    return string.replace('-', '_')


parser = argparse.ArgumentParser(description='Command Table Parser')
parser.add_argument('--commands',
                    metavar='N',
                    nargs='+',
                    help='Filter by first level command (OR)')
parser.add_argument('--params',
                    metavar='N',
                    nargs='+',
                    help='Filter by parameters (OR)')
parser.add_argument('--hide-nulls',
                    action='store_true',
                    default=False,
                    help='Show null entries')
args = parser.parse_args()
cmd_set_names = args.commands
param_names = [_dashed_to_camel(x) for x in args.params or []]
hide_nulls = args.hide_nulls

PRIMITIVES = (str, int, bool, float)
IGNORE_ARGS = ['help', 'help_file', 'base_type']

APPLICATION.register(Application.COMMAND_PARSER_LOADED, _dump_command_table)
APPLICATION.execute([])
def execute_cli_command(command):
    cmd_result = APPLICATION.execute(command)
    return cmd_result.result
def execute(command):
    try:
        ex_result = APPLICATION.execute(command)
        return {'result': ex_result.result, 'error': None}
    except CLIError as err:
        return {'result': None, 'error': err.args}