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.
            """
        command_table.clear()
        setattr(sys.modules[__name__], sample_sdk_method_with_weird_docstring.__name__, sample_sdk_method_with_weird_docstring) #pylint: disable=line-too-long
        cli_command(None, 'test command foo', '{}#{}'.format(__name__, sample_sdk_method_with_weird_docstring.__name__), None) #pylint: disable=line-too-long

        command_table['test command foo'].load_arguments()
        _update_command_definitions(command_table)

        command_metadata = command_table['test command foo']
        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.assertDictContainsSubset(some_expected_arguments[existing].settings,
                                          command_metadata.arguments[existing].options)
        command_table.clear()
Example #2
0
    def test_register_cli_argument(self):
        command_table.clear()
        cli_command(
            None, 'test register sample-vm-get',
            '{}#Test_command_registration.sample_vm_get'.format(__name__))
        register_cli_argument(
            'test register sample-vm-get', 'vm_name',
            CliArgumentType(options_list=('--wonky-name', '-n'),
                            metavar='VMNAME',
                            help='Completely WONKY name...',
                            required=False))

        command_table['test register sample-vm-get'].load_arguments()
        _update_command_definitions(command_table)

        self.assertEqual(len(command_table), 1,
                         'We expect exactly one command in the command table')
        command_metadata = command_table['test register sample-vm-get']
        self.assertEqual(len(command_metadata.arguments), 4,
                         'We expected exactly 4 arguments')
        some_expected_arguments = {
            'resource_group_name':
            CliArgumentType(dest='resource_group_name', required=True),
            'vm_name':
            CliArgumentType(dest='vm_name', required=False),
        }

        for probe in some_expected_arguments:
            existing = next(arg for arg in command_metadata.arguments
                            if arg == probe)
            self.assertDictContainsSubset(
                some_expected_arguments[existing].settings,
                command_metadata.arguments[existing].options)
        self.assertEqual(command_metadata.arguments['vm_name'].options_list,
                         ('--wonky-name', '-n'))
Example #3
0
    def test_override_using_register_cli_argument(self):
        def sample_sdk_method(param_a):  # pylint: disable=unused-argument
            pass

        def test_validator_completer():
            pass

        command_table.clear()
        setattr(sys.modules[__name__], sample_sdk_method.__name__,
                sample_sdk_method)
        cli_command(None, 'override_using_register_cli_argument foo',
                    '{}#{}'.format(__name__, sample_sdk_method.__name__), None)
        register_cli_argument('override_using_register_cli_argument',
                              'param_a',
                              options_list=('--overridden', '-r'),
                              validator=test_validator_completer,
                              completer=test_validator_completer,
                              required=False)

        command_table[
            'override_using_register_cli_argument foo'].load_arguments()
        _update_command_definitions(command_table)

        command_metadata = command_table[
            'override_using_register_cli_argument foo']
        self.assertEqual(len(command_metadata.arguments), 1,
                         'We expected exactly 1 arguments')

        actual_arg = command_metadata.arguments['param_a']
        self.assertEqual(actual_arg.options_list, ('--overridden', '-r'))
        self.assertEqual(actual_arg.validator, test_validator_completer)
        self.assertEqual(actual_arg.completer, test_validator_completer)
        self.assertFalse(actual_arg.options['required'])
        command_table.clear()
    def test_register_extra_cli_argument(self):
        command_table.clear()

        cli_command(None, 'test command sample-vm-get',
                    '{}#Test_command_registration.sample_vm_get'.format(__name__), None)
        register_extra_cli_argument(
            'test command sample-vm-get', 'added_param', options_list=('--added-param',),
            metavar='ADDED', help='Just added this right now!', required=True
        )

        command_table['test command sample-vm-get'].load_arguments()
        _update_command_definitions(command_table)

        self.assertEqual(len(command_table), 1,
                         'We expect exactly one command in the command table')
        command_metadata = command_table['test command sample-vm-get']
        self.assertEqual(len(command_metadata.arguments), 5, 'We expected exactly 5 arguments')

        some_expected_arguments = {
            'added_param': CliArgumentType(dest='added_param', required=True)
        }

        for probe in some_expected_arguments:
            existing = next(arg for arg in command_metadata.arguments if arg == probe)
            self.assertDictContainsSubset(some_expected_arguments[existing].settings,
                                          command_metadata.arguments[existing].options)

        command_table.clear()
Example #5
0
    def test_help_long_description_from_docstring(self):
        """ Verifies that the first sentence of a docstring is extracted as the short description.
        Verifies that line breaks in the long summary are removed and leaves the text wrapping
        to the help system. """

        def test_handler():
            """Short Description. Long description with\nline break."""
            pass

        setattr(sys.modules[__name__], test_handler.__name__, test_handler)

        cli_command(None, "test", "{}#{}".format(__name__, test_handler.__name__))
        _update_command_definitions(command_table)

        config = Configuration([])
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute("test -h".split())
        self.assertEqual(
            True,
            io.getvalue().startswith(
                "\nCommand\n    az test: Short Description.\n        Long description with line break."
            ),
        )  # pylint: disable=line-too-long
    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.
            """
        command_table.clear()
        setattr(sys.modules[__name__], sample_sdk_method_with_weird_docstring.__name__, sample_sdk_method_with_weird_docstring) #pylint: disable=line-too-long
        cli_command(None, 'test command foo', '{}#{}'.format(__name__, sample_sdk_method_with_weird_docstring.__name__), None) #pylint: disable=line-too-long

        command_table['test command foo'].load_arguments()
        _update_command_definitions(command_table)

        command_metadata = command_table['test command foo']
        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.assertDictContainsSubset(some_expected_arguments[existing].settings,
                                          command_metadata.arguments[existing].options)
        command_table.clear()
    def test_override_using_register_cli_argument(self):
        def sample_sdk_method(param_a): # pylint: disable=unused-argument
            pass

        def test_validator_completer():
            pass

        command_table.clear()
        setattr(sys.modules[__name__], sample_sdk_method.__name__, sample_sdk_method)
        cli_command(None, 'override_using_register_cli_argument foo',
                    '{}#{}'.format(__name__, sample_sdk_method.__name__),
                    None)
        register_cli_argument('override_using_register_cli_argument',
                              'param_a',
                              options_list=('--overridden', '-r'),
                              validator=test_validator_completer,
                              completer=test_validator_completer,
                              required=False)

        command_table['override_using_register_cli_argument foo'].load_arguments()
        _update_command_definitions(command_table)

        command_metadata = command_table['override_using_register_cli_argument foo']
        self.assertEqual(len(command_metadata.arguments), 1, 'We expected exactly 1 arguments')

        actual_arg = command_metadata.arguments['param_a']
        self.assertEqual(actual_arg.options_list, ('--overridden', '-r'))
        self.assertEqual(actual_arg.validator, test_validator_completer)
        self.assertEqual(actual_arg.completer, test_validator_completer)
        self.assertFalse(actual_arg.options['required'])
        command_table.clear()
    def test_register_cli_argument(self):
        command_table.clear()
        cli_command(None, 'test register sample-vm-get',
                    '{}#Test_command_registration.sample_vm_get'.format(__name__))
        register_cli_argument('test register sample-vm-get', 'vm_name', CliArgumentType(
            options_list=('--wonky-name', '-n'), metavar='VMNAME', help='Completely WONKY name...',
            required=False
        ))

        command_table['test register sample-vm-get'].load_arguments()
        _update_command_definitions(command_table)

        self.assertEqual(len(command_table), 1,
                         'We expect exactly one command in the command table')
        command_metadata = command_table['test register sample-vm-get']
        self.assertEqual(len(command_metadata.arguments), 4, 'We expected exactly 4 arguments')
        some_expected_arguments = {
            'resource_group_name': CliArgumentType(dest='resource_group_name', required=True),
            'vm_name': CliArgumentType(dest='vm_name', required=False),
        }

        for probe in some_expected_arguments:
            existing = next(arg for arg in command_metadata.arguments if arg == probe)
            self.assertDictContainsSubset(some_expected_arguments[existing].settings,
                                          command_metadata.arguments[existing].options)
        self.assertEqual(command_metadata.arguments['vm_name'].options_list, ('--wonky-name', '-n'))
Example #9
0
    def test_register_extra_cli_argument(self):
        command_table.clear()

        cli_command(
            None, 'test command sample-vm-get',
            '{}#Test_command_registration.sample_vm_get'.format(__name__),
            None)
        register_extra_cli_argument('test command sample-vm-get',
                                    'added_param',
                                    options_list=('--added-param', ),
                                    metavar='ADDED',
                                    help='Just added this right now!',
                                    required=True)

        command_table['test command sample-vm-get'].load_arguments()
        _update_command_definitions(command_table)

        self.assertEqual(len(command_table), 1,
                         'We expect exactly one command in the command table')
        command_metadata = command_table['test command sample-vm-get']
        self.assertEqual(len(command_metadata.arguments), 5,
                         'We expected exactly 5 arguments')

        some_expected_arguments = {
            'added_param': CliArgumentType(dest='added_param', required=True)
        }

        for probe in some_expected_arguments:
            existing = next(arg for arg in command_metadata.arguments
                            if arg == probe)
            self.assertDictContainsSubset(
                some_expected_arguments[existing].settings,
                command_metadata.arguments[existing].options)

        command_table.clear()
    def test_register_cli_argument_with_overrides(self):
        command_table.clear()

        global_vm_name_type = CliArgumentType(
            options_list=('--foo', '-f'), metavar='FOO', help='foo help'
        )
        derived_vm_name_type = CliArgumentType(base_type=global_vm_name_type,
                                               help='first modification')

        cli_command('test vm-get', Test_command_registration.sample_vm_get, None)
        cli_command('test command vm-get-1', Test_command_registration.sample_vm_get, None)
        cli_command('test command vm-get-2', Test_command_registration.sample_vm_get, None)

        register_cli_argument('test', 'vm_name', global_vm_name_type)
        register_cli_argument('test command', 'vm_name', derived_vm_name_type)
        register_cli_argument('test command vm-get-2', 'vm_name', derived_vm_name_type,
                              help='second modification')

        _update_command_definitions(command_table)

        self.assertEqual(len(command_table), 3,
                         'We expect exactly three commands in the command table')
        command1 = command_table['test vm-get'].arguments['vm_name']
        command2 = command_table['test command vm-get-1'].arguments['vm_name']
        command3 = command_table['test command vm-get-2'].arguments['vm_name']

        self.assertTrue(command1.options['help'] == 'foo help')
        self.assertTrue(command2.options['help'] == 'first modification')
        self.assertTrue(command3.options['help'] == 'second modification')
        command_table.clear()
Example #11
0
def dump_no_help(modules):
    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)

    command_list = []
    subgroups_list = []
    parameters = {}
    for cmd in cmd_table:
        if not cmd_table[cmd].description and cmd not in helps:
            command_list.append(cmd)
            exit_val = 1
        group_name = " ".join(cmd.split()[:-1])
        if group_name not in helps:
            exit_val = 1
            if group_name not in subgroups_list:
                subgroups_list.append(group_name)

        param_list = []
        for key in cmd_table[cmd].arguments:
            if not cmd_table[cmd].arguments[key].type.settings.get('help'):
                exit_val = 1
                param_list.append(cmd_table[cmd].arguments[key].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
    }

    print(json.dumps(data, indent=2, sort_keys=True))

    return exit_val
Example #12
0
def dump_no_help(modules):
    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)

    command_list = []
    subgroups_list = []
    parameters = {}
    for cmd in cmd_table:
        if not cmd_table[cmd].description and cmd not in helps:
            command_list.append(cmd)
            exit_val = 1
        group_name = " ".join(cmd.split()[:-1])
        if group_name not in helps:
            exit_val = 1
            if group_name not in subgroups_list:
                subgroups_list.append(group_name)

        param_list = []
        for key in cmd_table[cmd].arguments:
            if not cmd_table[cmd].arguments[key].type.settings.get('help'):
                exit_val = 1
                param_list.append(cmd_table[cmd].arguments[key].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
    }

    print(json.dumps(data, indent=2, sort_keys=True))

    return exit_val
Example #13
0
    def test_register_cli_argument_with_overrides(self):
        command_table.clear()

        global_vm_name_type = CliArgumentType(options_list=('--foo', '-f'),
                                              metavar='FOO',
                                              help='foo help')
        derived_vm_name_type = CliArgumentType(base_type=global_vm_name_type,
                                               help='first modification')

        cli_command(
            None, 'test vm-get',
            '{}#Test_command_registration.sample_vm_get'.format(__name__),
            None)
        cli_command(
            None, 'test command vm-get-1',
            '{}#Test_command_registration.sample_vm_get'.format(__name__),
            None)
        cli_command(
            None, 'test command vm-get-2',
            '{}#Test_command_registration.sample_vm_get'.format(__name__),
            None)

        register_cli_argument('test', 'vm_name', global_vm_name_type)
        register_cli_argument('test command', 'vm_name', derived_vm_name_type)
        register_cli_argument('test command vm-get-2',
                              'vm_name',
                              derived_vm_name_type,
                              help='second modification')

        command_table['test vm-get'].load_arguments()
        command_table['test command vm-get-1'].load_arguments()
        command_table['test command vm-get-2'].load_arguments()
        _update_command_definitions(command_table)

        self.assertEqual(
            len(command_table), 3,
            'We expect exactly three commands in the command table')
        command1 = command_table['test vm-get'].arguments['vm_name']
        command2 = command_table['test command vm-get-1'].arguments['vm_name']
        command3 = command_table['test command vm-get-2'].arguments['vm_name']

        self.assertTrue(command1.options['help'] == 'foo help')
        self.assertTrue(command2.options['help'] == 'first modification')
        self.assertTrue(command3.options['help'] == 'second modification')
        command_table.clear()
    def set_up_command_table(self, required_arg=False):
        command_table.clear()

        module_name = __name__ + '.' + self._testMethodName
        cli_command(module_name, 'test sample-vm-list',
                    '{}#TestCommandWithConfiguredDefaults.sample_vm_list'.format(__name__))

        register_cli_argument('test sample-vm-list', 'resource_group_name',
                              CliArgumentType(options_list=('--resource-group-name', '-g'),
                                              configured_default='group', required=required_arg))

        command_table['test sample-vm-list'].load_arguments()
        _update_command_definitions(command_table)

        self.argv = 'az test sample-vm-list'.split()
        config = Configuration(self.argv)
        config.get_command_table = lambda: command_table
        self.application = Application(config)
Example #15
0
    def test_help_long_description_from_docstring(self):
        """ Verifies that the first sentence of a docstring is extracted as the short description.
        Verifies that line breaks in the long summary are removed and leaves the text wrapping
        to the help system. """

        def test_handler():
            """Short Description. Long description with\nline break."""
            pass

        cli_command('test', test_handler)
        _update_command_definitions(command_table)

        config = Configuration([])
        app = Application(config)

        with self.assertRaises(SystemExit):
            app.execute('test -h'.split())
        self.assertEqual(True, io.getvalue().startswith('\nCommand\n    az test: Short Description.\n        Long description with line break.')) # pylint: disable=line-too-long
Example #16
0
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__)
        ]
    except ImportError:
        pass
    for mod in installed_command_modules:
        try:
            import_module('azure.cli.command_modules.' + mod).load_params(mod)
        except Exception:  # pylint: disable=broad-except
            print("Error loading: {}".format(mod))
    _update_command_definitions(CMD_TABLE)
    def set_up_command_table(self, required_arg=False):
        command_table.clear()

        module_name = __name__ + '.' + self._testMethodName
        cli_command(module_name, 'test sample-vm-list',
                    '{}#TestCommandWithConfiguredDefaults.sample_vm_list'.format(__name__))

        register_cli_argument('test sample-vm-list', 'resource_group_name',
                              CliArgumentType(options_list=('--resource-group-name', '-g'),
                                              configured_default='group', required=required_arg))

        command_table['test sample-vm-list'].load_arguments()
        _update_command_definitions(command_table)

        self.argv = 'az test sample-vm-list'.split()
        config = Configuration()
        config.get_command_table = lambda argv: command_table
        self.application = Application(config)
Example #18
0
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)

    for mod in installed_command_modules:
        try:
            mod = import_module('azure.cli.command_modules.' + mod)
            mod.load_params(mod)
            mod.load_commands()

        except Exception:  # pylint: disable=broad-except
            print("Error loading: {}".format(mod))
    _update_command_definitions(CMD_TABLE)
Example #19
0
    def install_modules(self):
        installed_command_modules = []
        for cmd in self.command_table:
            try:
                self.command_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)

        for mod in installed_command_modules:
            try:
                mod = import_module('azure.cli.command_modules.' + mod)
                mod.load_params(mod)
                mod.load_commands()

            except Exception:  # pylint: disable=broad-except
                print("Error loading: {}".format(mod))
        _update_command_definitions(self.command_table)
Example #20
0
def _install_modules(command_table):
    for cmd in command_table:
        command_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:
        pass
    for mod in installed_command_modules:
        try:
            mod = import_module('azure.cli.command_modules.' + mod)
            mod.load_params(mod)
            mod.load_commands()

        except Exception:  # pylint: disable=broad-except
            print("Error loading: {}".format(mod), file=stderr)
            traceback.print_exc(file=stderr)
    _update_command_definitions(command_table)
Example #21
0
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
def build_command_table():
    import azure.cli.core.commands as commands
    cmd_table = commands.get_command_table()
    for cmd in cmd_table:
        cmd_table[cmd].load_arguments()
    _update_command_definitions(cmd_table)

    data = {}
    for cmd in cmd_table:
        com_descip = {}
        param_descrip = {}
        com_descip['short-summary'] = cmd_table[cmd].description() \
            if callable(cmd_table[cmd].description) \
            else cmd_table[cmd].description or ''
        com_descip['examples'] = ''

        for key in cmd_table[cmd].arguments:
            required = ''
            help_desc = ''
            if cmd_table[cmd].arguments[key].type.settings.get('required'):
                required = '[REQUIRED]'
            if cmd_table[cmd].arguments[key].type.settings.get('help'):
                help_desc = cmd_table[cmd].arguments[key].type.settings.get('help')

            name_options = []
            for name in cmd_table[cmd].arguments[key].options_list:
                name_options.append(name)

            options = {
                'name': name_options,
                'required': required,
                'help': help_desc
            }
            param_descrip[cmd_table[cmd].arguments[key].options_list[0]] = options

        com_descip['parameters'] = param_descrip
        data[cmd] = com_descip

    for cmd in helps:
        diction_help = yaml.load(helps[cmd])
        if cmd not in data:
            data[cmd] = {
                'short-summary': diction_help.get(
                    'short-summary', ''),
                'long-summary': diction_help.get('long-summary', ''),
                'parameters': {}
            }
        else:
            data[cmd]['short-summary'] = diction_help.get('short-summary',
                                                          data[cmd].get('short-summary', ''))
            data[cmd]['long-summary'] = diction_help.get("long-summary", '')
            data[cmd]['parameters'] = {}

        if 'parameters' in diction_help:
            for param in diction_help["parameters"]:
                if param['name'].split()[0] not in data[cmd]['parameters']:
                    options = {
                        'name': name_options,
                        'required': required,
                        'help': help_desc
                    }
                    data[cmd]['parameters'] = {
                        param["name"].split()[0]: options
                    }
                if 'short-summary' in param:
                    data[cmd]['parameters'][param['name'].split()[0]]['help'] \
                        = param['short-summary']
        if 'examples' in diction_help:
            string_example = ''
            for example in diction_help['examples']:
                string_example += example.get('name', '') + '\n' + example.get('text', '') + '\n'
            data[cmd]['examples'] = string_example

    return data
Example #23
0
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 dump_command_table():
    """ dumps the command table """
    global CMD_TABLE
    cmd_table = CMD_TABLE

    command_file = config.CONFIGURATION.get_help_files()

    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__)
        ]
    except ImportError:
        pass
    for mod in installed_command_modules:
        try:
            import_module('azure.cli.command_modules.' + mod).load_params(mod)
        except Exception as ex:
            print("EXCPETION: " + ex.message)
    _update_command_definitions(cmd_table)

    data = {}
    for cmd in cmd_table:
        com_descip = {}
        param_descrip = {}
        com_descip['help'] = cmd_table[cmd].description
        com_descip['examples'] = ""

        for key in cmd_table[cmd].arguments:
            required = ""
            help_desc = ""
            if cmd_table[cmd].arguments[key].type.settings.get('required'):
                required = "[REQUIRED]"
            if cmd_table[cmd].arguments[key].type.settings.get('help'):
                help_desc = cmd_table[cmd].arguments[key].type.settings.get(
                    'help')

            name_options = []
            for name in cmd_table[cmd].arguments[key].options_list:
                name_options.append(name)

            options = {
                'name': name_options,
                'required': required,
                'help': help_desc
            }
            param_descrip[
                cmd_table[cmd].arguments[key].options_list[0]] = options

        com_descip['parameters'] = param_descrip
        data[cmd] = com_descip

    for cmd in helps:
        diction_help = yaml.load(helps[cmd])
        if "short-summary" in diction_help:
            if cmd in data:
                data[cmd]['help'] = diction_help["short-summary"]
            else:
                data[cmd] = {
                    'help': diction_help["short-summary"],
                    'parameters': {}
                }

        if "parameters" in diction_help:
            for param in diction_help["parameters"]:

                if param["name"].split()[0] not in data[cmd]['parameters']:
                    options = {
                        'name': name_options,
                        'required': required,
                        'help': help_desc
                    }
                    data[cmd]['parameters'] = {
                        param["name"].split()[0]: options
                    }
                if "short-summary" in param:
                    data[cmd]['parameters'][param["name"].split()[0]]['help']\
                     = param["short-summary"]
                # if "choices" in param:
                #     print("choices")
        if "examples" in diction_help:
            examples = []
            for example in diction_help["examples"]:
                examples.append([example['name'], example['text']])
            data[cmd]['examples'] = examples

    with open(os.path.join(get_cache_dir(), command_file), 'w') as help_file:
        json.dump(data, help_file)