1"""
2native parser
3
4This is the native parser for use with the cli_parse module and action plugin.
5The parser functionality used by the network resource modules is leveraged here.
6
7"""
8from __future__ import absolute_import, division, print_function
9
10__metaclass__ = type
11
12DOCUMENTATION = """
13    author: Bradley Thornton (@cidrblock)
14    name: native
15    short_description: Define configurable options for C(native) sub-plugin of C(cli_parse) module
16    description:
17    - This plugin documentation provides the configurable options that can be passed
18      to the I(ansible.utils.cli_parse) plugins when I(ansible.netcommon.native) is used as a value for
19      I(name) option.
20    version_added: 1.0.0
21"""
22
23EXAMPLES = r"""
24- name: "Run command and parse with native"
25  ansible.utils.cli_parse:
26    command: "show interface"
27    parser:
28      name: ansible.netcommon.native
29    set_fact: POpqMQoJWTiDpEW
30  register: nxos_native_command
31
32- name: "Pass text and template_path"
33  ansible.utils.cli_parse:
34    text: "{{ nxos_native_command['stdout'] }}"
35    parser:
36      name: ansible.netcommon.native
37      template_path: "/home/user/templates/nxos_show_interface.yaml"
38  register: nxos_native_text
39"""
40
41from ansible.module_utils._text import to_native
42
43from ansible_collections.ansible.utils.plugins.plugin_utils.base.cli_parser import (
44    CliParserBase,
45)
46from ansible_collections.ansible.netcommon.plugins.module_utils.cli_parser.cli_parsertemplate import (
47    CliParserTemplate,
48)
49
50
51try:
52    import yaml
53
54    try:
55        from yaml import CSafeLoader as SafeLoader
56    except ImportError:
57        from yaml import SafeLoader
58    HAS_YAML = True
59except ImportError:
60    HAS_YAML = False
61
62
63class CliParser(CliParserBase):
64    """ The native parser class
65    Convert raw text to structured data using the resource module parser
66    """
67
68    DEFAULT_TEMPLATE_EXTENSION = "yaml"
69    PROVIDE_TEMPLATE_CONTENTS = True
70
71    def parse(self, *_args, **kwargs):
72        """ Std entry point for a cli_parse parse execution
73
74        :return: Errors or parsed text as structured data
75        :rtype: dict
76
77        :example:
78
79        The parse function of a parser should return a dict:
80        {"errors": [a list of errors]}
81        or
82        {"parsed": obj}
83        """
84        # res = self._check_reqs()
85        # if res.get("errors"):
86        #     return res
87
88        template_contents = kwargs["template_contents"]
89        parser = CliParserTemplate(
90            lines=self._task_args.get("text").splitlines()
91        )
92        try:
93            template_obj = yaml.load(template_contents, SafeLoader)
94        except Exception as exc:
95            return {"errors": [to_native(exc)]}
96
97        try:
98            parser.PARSERS = template_obj
99            return {"parsed": parser.parse()}
100        except Exception as exc:
101            msg = "Native parser returned an error while parsing. Error: {err}"
102            return {"errors": [msg.format(err=to_native(exc))]}
103