Exemplo n.º 1
0
def test_stringEscapeMD():
    from demisto_sdk.commands.generate_docs.common import string_escape_md
    res = string_escape_md(
        'First fetch timestamp (<number> <time unit>, e.g., 12 hours, 7 days)')
    assert '<' not in res
    assert '>' not in res
    res = string_escape_md("new line test \n", escape_multiline=True)
    assert '\n' not in res
    assert '<br/>' in res
    res = string_escape_md('Here are "Double Quotation" marks')
    assert '"' in res
    res = string_escape_md("Here are 'Single Quotation' marks")
    assert "'" in res
Exemplo n.º 2
0
def get_outputs(script):
    """
    Gets script outputs.
    :param script: the script object.
    :return: list of outputs and list of errors.
    """
    errors = []
    outputs = []

    if not script.get('outputs'):
        return {}, []

    for arg in script.get('outputs'):
        if not arg.get('description'):
            errors.append(
                'Error! You are missing description in script output {}'.
                format(arg.get('contextPath')))

        outputs.append({
            'Path':
            arg.get('contextPath'),
            'Description':
            string_escape_md(arg.get('description', '')),
            'Type':
            arg.get('type', 'Unknown')
        })

    return outputs, errors
Exemplo n.º 3
0
def get_inputs(script):
    """
    Gets script inputs.
    :param script: the script object.
    :return: list of inputs and list of errors.
    """
    errors = []
    inputs = []

    if not script.get('args'):
        return {}, []

    for arg in script.get('args'):
        if not arg.get('description'):
            errors.append(
                'Error! You are missing description in script input {}'.format(
                    arg.get('name')))

        inputs.append({
            'Argument Name':
            arg.get('name'),
            'Description':
            string_escape_md(arg.get('description', ''))
        })

    return inputs, errors
Exemplo n.º 4
0
def get_outputs(playbook):
    """
    Gets playbook outputs.
    :param playbook: the playbook object.
    :return: list of outputs and list of errors.
    """
    errors = []
    outputs = []

    if not playbook.get('outputs'):
        return {}, []

    for output in playbook.get('outputs'):
        if not output.get('description'):
            errors.append(
                'Error! You are missing description in playbook output {}'.
                format(output.get('contextPath')))

        output_type = output.get('type')
        if not output_type:
            output_type = 'unknown'

        outputs.append({
            'Path':
            output.get('contextPath'),
            'Description':
            string_escape_md(output.get('description', '')),
            'Type':
            output_type
        })

    return outputs, errors
Exemplo n.º 5
0
def generate_setup_section(yaml_data: dict):
    section = [
        '1. Navigate to **Settings** > **Integrations** > **Servers & Services**.',
        '2. Search for {}.'.format(yaml_data['name']),
        '3. Click **Add instance** to create and configure a new integration instance.'
    ]
    access_data = []

    for conf in yaml_data['configuration']:
        access_data.append({
            'Parameter':
            conf.get('display'),
            'Description':
            string_escape_md(conf.get('additionalinfo', '')),
            'Required':
            conf.get('required', '')
        })

    # Check if at least one parameter has additional info field.
    # If not, remove the description column from the access data table section.
    access_data_with_description = list(
        filter(lambda x: x.get('Description', '') != '', access_data))
    if len(access_data_with_description) == 0:
        list(map(lambda x: x.pop('Description'), access_data))

    section.extend(
        generate_table_section(access_data,
                               '',
                               horizontal_rule=False,
                               numbered_section=True))
    section.append(
        '4. Click **Test** to validate the URLs, token, and connection.')

    return section
def test_string_escape_md():
    from demisto_sdk.commands.generate_docs.common import string_escape_md
    res = string_escape_md(
        'First fetch timestamp (<number> <time unit>, e.g., 12 hours, 7 days)')
    assert '<' not in res
    assert '>' not in res
    res = string_escape_md("new line test \n", escape_multiline=True)
    assert '\n' not in res
    assert '<br/>' in res
    res = string_escape_md('Here are "Double Quotation" marks')
    assert '"' in res
    res = string_escape_md("Here are 'Single Quotation' marks")
    assert "'" in res
    res = string_escape_md(
        '- This _sentence_ has _wrapped_with_underscore_ and _another_ words.')
    assert '\\_wrapped_with_underscore\\_' in res
    assert '\\_sentence\\_' in res
    assert '\\_another\\_' in res
    assert res.startswith('\\-')
Exemplo n.º 7
0
def get_inputs(
        playbook: Dict[str, List[Dict]]) -> Tuple[List[Dict], List[str]]:
    """Gets playbook inputs.

    Args:
        playbook (dict): the playbook object.

    Returns:
        (tuple): list of inputs and list of errors.
    """
    errors = []
    inputs = []

    if not playbook.get('inputs'):
        return [], []

    playbook_inputs: List = playbook.get('inputs', [])
    for _input in playbook_inputs:
        name = _input.get('key')
        description = string_escape_md(_input.get('description', ''))
        required_status = 'Required' if _input.get('required') else 'Optional'
        _value: Optional[str] = get_input_data(_input)

        playbook_input_query: Dict[str, str] = _input.get('playbookInputQuery')
        # a playbook input section whose 'key' key is empty and whose 'playbookInputQuery' key is a dict
        # is an Indicators Query input section
        if not name and isinstance(playbook_input_query, dict):
            name = 'Indicator Query'
            _value = playbook_input_query.get('query')
            default_description = 'Indicators matching the indicator query will be used as playbook input'
            description = description if description else default_description

        if not description:
            errors.append(
                'Error! You are missing description in playbook input {}'.
                format(name))

        inputs.append({
            'Name': name,
            'Description': description,
            'Default Value': _value,
            'Required': required_status,
        })

    return inputs, errors
Exemplo n.º 8
0
def generate_setup_section(yaml_data: dict):
    section = [
        '1. Navigate to **Settings** > **Integrations** > **Servers & Services**.',
        '2. Search for {}.'.format(yaml_data['name']),
        '3. Click **Add instance** to create and configure a new integration instance.'
    ]
    access_data = []

    for conf in yaml_data['configuration']:
        access_data.append({
            'Parameter':
            conf.get('name', ''),
            'Description':
            string_escape_md(conf.get('display', '')),
            'Required':
            conf.get('required', '')
        })

    section.extend(
        generate_table_section(access_data, '', horizontal_rule=False))
    section.append(
        '4. Click **Test** to validate the URLs, token, and connection.')

    return section
Exemplo n.º 9
0
def generate_single_command_section(cmd: dict, example_dict: dict,
                                    command_permissions_dict):
    errors = []
    cmd_example = example_dict.get(cmd['name'])
    if command_permissions_dict:
        if command_permissions_dict.get(cmd['name']):
            cmd_permission_example = [
                '#### Required Permissions',
                command_permissions_dict.get(cmd['name'])
            ]
        else:
            errors.append(
                f"Error! Command Permissions were not found for command {cmd['name']}"
            )
            cmd_permission_example = ['#### Required Permissions', '']
    elif isinstance(command_permissions_dict,
                    dict) and not command_permissions_dict:
        cmd_permission_example = [
            '#### Required Permissions',
            '**FILL IN REQUIRED PERMISSIONS HERE**'
        ]
    else:  # no permissions for this command
        cmd_permission_example = ['', '']

    section = [
        '### {}'.format(cmd['name']), '***',
        cmd.get('description',
                ' '), cmd_permission_example[0], cmd_permission_example[1],
        '#### Base Command', '', '`{}`'.format(cmd['name']), '#### Input', ''
    ]

    # Inputs
    arguments = cmd.get('arguments')
    if arguments is None:
        section.append('There are no input arguments for this command.')
    else:
        section.extend([
            '| **Argument Name** | **Description** | **Required** |',
            '| --- | --- | --- |',
        ])
        for arg in arguments:
            description = arg.get('description')
            if not description:
                errors.append(
                    'Error! You are missing description in input {} of command {}'
                    .format(arg['name'], cmd['name']))
            if not description.endswith('.'):
                description = f'{description}.'

            argument_description = f'{description} Possible values are: {", ".join(arg.get("predefined"))}.' \
                if arg.get('predefined') else description
            if arg.get('defaultValue'):
                argument_description = f'{argument_description} Default is {arg.get("defaultValue")}.'

            required_status = 'Required' if arg.get('required') else 'Optional'
            section.append('| {} | {} | {} | '.format(
                arg['name'], string_escape_md(argument_description, True,
                                              True), required_status))
        section.append('')

    # Context output
    section.extend([
        '',
        '#### Context Output',
        '',
    ])
    outputs = cmd.get('outputs')
    if outputs is None:
        section.append('There is no context output for this command.')
    else:
        section.extend(
            [CONTEXT_OUTPUT_README_TABLE_HEADER, '| --- | --- | --- |'])
        for output in outputs:
            if not output.get('description'):
                errors.append(
                    'Error! You are missing description in output {} of command {}'
                    .format(output['contextPath'], cmd['name']))
            section.append('| {} | {} | {} | '.format(
                output['contextPath'], output.get('type', 'unknown'),
                string_escape_md(output.get('description', ''))))
        section.append('')

    # Raw output:
    example_section, example_errors = generate_command_example(
        cmd, cmd_example)
    section.extend(example_section)
    errors.extend(example_errors)

    return section, errors
Exemplo n.º 10
0
def generate_single_command_section(cmd: dict, example_dict: dict,
                                    command_permissions_dict):
    cmd_example = example_dict.get(cmd['name'])
    if command_permissions_dict:
        cmd_permission_example = [
            '#### Required Permissions',
            command_permissions_dict.get(cmd['name'])
        ]
    elif isinstance(command_permissions_dict,
                    dict) and not command_permissions_dict:
        cmd_permission_example = [
            '#### Required Permissions',
            '**FILL IN REQUIRED PERMISSIONS HERE**'
        ]
    else:  # no permissions for this command
        cmd_permission_example = ['', '']

    errors = []
    section = [
        '### {}'.format(cmd['name']), '***',
        cmd.get('description',
                ' '), cmd_permission_example[0], cmd_permission_example[1],
        '#### Base Command', '', '`{}`'.format(cmd['name']), '#### Input', ''
    ]

    # Inputs
    arguments = cmd.get('arguments')
    if arguments is None:
        section.append('There are no input arguments for this command.')
    else:
        section.extend([
            '| **Argument Name** | **Description** | **Required** |',
            '| --- | --- | --- |',
        ])
        for arg in arguments:
            if not arg.get('description'):
                errors.append(
                    'Error! You are missing description in input {} of command {}'
                    .format(arg['name'], cmd['name']))
            required_status = 'Required' if arg.get('required') else 'Optional'
            section.append('| {} | {} | {} | '.format(
                arg['name'],
                string_escape_md(arg.get('description', ''), True, True),
                required_status))
        section.append('')

    # Context output
    section.extend([
        '',
        '#### Context Output',
        '',
    ])
    outputs = cmd.get('outputs')
    if outputs is None:
        section.append('There is no context output for this command.')
    else:
        section.extend([
            '| **Path** | **Type** | **Description** |', '| --- | --- | --- |'
        ])
        for output in outputs:
            if not output.get('description'):
                errors.append(
                    'Error! You are missing description in output {} of command {}'
                    .format(output['contextPath'], cmd['name']))
            section.append('| {} | {} | {} | '.format(
                output['contextPath'], output.get('type', 'unknown'),
                string_escape_md(output.get('description', ''))))
        section.append('')

    # Raw output:
    example_section, example_errors = generate_command_example(
        cmd, cmd_example)
    section.extend(example_section)
    errors.extend(example_errors)

    return section, errors