def emit(self, ctx, modules, fd):
        """Main control function.

        Set up the top-level parts of the sample document, then process
        recursively all nodes in all data trees, and finally emit the
        sample XML document.
        """
        if ctx.opts.sample_path is not None:
            path = ctx.opts.sample_path.split('/')
            if path[0] == '':
                path = path[1:]
        else:
            path = []

        for (epos, etag, eargs) in ctx.errors:
            if error.is_error(error.err_level(etag)):
                raise error.EmitError(
                    "sample-xml-skeleton plugin needs a valid module")
        self.doctype = ctx.opts.doctype
        if self.doctype not in ("config", "data"):
            raise error.EmitError("Unsupported document type: %s" %
                                  self.doctype)
        self.annots = ctx.opts.sample_annots
        self.defaults = ctx.opts.sample_defaults
        self.node_handler = {
            "container": self.container,
            "leaf": self.leaf,
            "anyxml": self.anyxml,
            "choice": self.process_children,
            "case": self.process_children,
            "list": self.list,
            "leaf-list": self.leaf_list,
            "rpc": self.ignore,
            "action": self.ignore,
            "notification": self.ignore
        }
        self.ns_uri = {}
        for yam in modules:
            self.ns_uri[yam] = yam.search_one("namespace").arg
        self.top = etree.Element(
            self.doctype, {"xmlns": "urn:ietf:params:xml:ns:netconf:base:1.0"})
        tree = etree.ElementTree(self.top)
        for yam in modules:
            self.process_children(yam, self.top, None, path)
        if sys.version > "3":
            fd.write(
                str(
                    etree.tostring(tree,
                                   pretty_print=True,
                                   encoding="UTF-8",
                                   xml_declaration=True), "UTF-8"))
        elif sys.version > "2.7":
            tree.write(fd,
                       encoding="UTF-8",
                       pretty_print=True,
                       xml_declaration=True)
        else:
            tree.write(fd, pretty_print=True, encoding="UTF-8")
Пример #2
0
    def emit(self, ctx, module, fd):
        # cannot do XSD unless everything is ok for our module
        for (epos, etag, eargs) in ctx.errors:
            if (epos.top_name == module.arg
                    and error.is_error(error.err_level(etag))):
                raise error.EmitError("XSD translation needs a valid module")
        # we also need to have all other modules found
        for pre in module.i_prefixes:
            (modname, revision) = module.i_prefixes[pre]
            mod = statements.modulename_to_module(module, modname, revision)
            if mod == None:
                raise error.EmitError("cannot find module %s, needed by XSD"
                                      " translation" % modname)

        emit_xsd(ctx, module, fd)
Пример #3
0
    def emit(self, ctx, modules, fd):
        """Main control function.
        """
        for (epos, etag, eargs) in ctx.errors:
            if error.is_error(error.err_level(etag)):
                raise error.EmitError("sample-json-skeleton plugin needs a valid module")
        tree = {}
        self.defaults = ctx.opts.sample_defaults
        self.doctype = ctx.opts.doctype
        if self.doctype not in ("config", "data"):
            raise error.EmitError("Unsupported document type: %s" %
                                  self.doctype)

        for module in modules:
            self.process_children(module, tree, None)
        json.dump(tree, fd, indent=4)
Пример #4
0
    def handle_stmt(self, stmt, p_elem, pset={}):
        """
        Run handler method for statement `stmt`.

        `p_elem` is the parent node in the output schema. `pset` is
        the current "patch set" - a dictionary with keys being QNames
        of schema nodes at the current level of hierarchy for which
        (or descendants thereof) any pending patches exist. The values
        are instances of the Patch class.

        All handler methods are defined below and must have the same
        arguments as this method. They should create the output schema
        fragment corresponding to `stmt`, apply all patches from
        `pset` belonging to `stmt`, insert the fragment under `p_elem`
        and perform all side effects as necessary.
        """
        if self.debug > 0:
            sys.stderr.write("Handling '%s %s'\n" %
                             (util.keyword_to_str(stmt.raw_keyword), stmt.arg))
        try:
            method = self.stmt_handler[stmt.keyword]
        except KeyError:
            if isinstance(stmt.keyword, tuple):
                try:
                    method = self.ext_handler[stmt.keyword[0]][stmt.keyword[1]]
                except KeyError:
                    method = self.rng_annotation
                method(stmt, p_elem)
                return
            else:
                raise error.EmitError(
                    "Unknown keyword %s - this should not happen.\n"
                    % stmt.keyword)
        method(stmt, p_elem, pset)
Пример #5
0
def emit_json_xsl(modules, ctx, fd):
    """Main control function.

    Set up the top-level parts of the stylesheet, the process
    recursively all nodes in all data trees, and finally emit the
    serialized stylesheet.
    """
    for (epos, etag, eargs) in ctx.errors:
        if error.is_error(error.err_level(etag)):
            raise error.EmitError("JSONXSL plugin needs a valid module")
    tree = ET.ElementTree(ss)
    ET.SubElement(ss, "output", method="text")
    xsltdir = os.environ.get("PYANG_XSLT_DIR", "/usr/local/share/yang/xslt")
    ET.SubElement(ss, "include", href=xsltdir + "/jsonxsl-templates.xsl")
    ET.SubElement(ss, "strip-space", elements="*")
    nsmap = ET.SubElement(ss, "template", name="nsuri-to-module")
    ET.SubElement(nsmap, "param", name="uri")
    choo = ET.SubElement(nsmap, "choose")
    for module in modules:
        ns_uri = module.search_one("namespace").arg
        ss.attrib["xmlns:" + module.i_prefix] = ns_uri
        when = ET.SubElement(choo, "when", test="$uri='" + ns_uri + "'")
        xsl_text(module.i_modulename, when)
        process_module(module)
    tree.write(fd, encoding="utf-8", xml_declaration=True)
Пример #6
0
 def emit(self, ctx, modules, fd):
   modulenames = [m.arg for m in modules]
   if not ctx.opts.ignore_errors:
     for (epos, etag, eargs) in ctx.errors:
       #
       #  When a module has not yet been parsed then the top.arg does
       #  not exist. This can be the case when an error is created early
       #  in the parsing process.
       #
       if not hasattr(epos.top, "arg"):
         raise error.EmitError("%s contains errors, and was not parsed"
             % (epos.ref))
       if (epos.top.arg in modulenames and
                 error.is_error(error.err_level(etag))):
           raise error.EmitError("%s contains errors" % epos.top.arg)
   emit_paths(ctx, modules, fd)
Пример #7
0
def find_stmt_by_path(module, path):
    logging.debug("in find_stmt_by_path with: %s %s path: %s", module.keyword, module.arg, path)

    if path is not None:
        spath = path.split("/")
        if spath[0] == '':
            spath = spath[1:]

    children = [child for child in module.i_children
                if child.keyword in statements.data_definition_keywords]

    while spath is not None and len(spath) > 0:
        match = [child for child in children if child.arg == spath[0]
                 and child.keyword in statements.data_definition_keywords]
        if len(match) > 0:
            logging.debug("Match on: %s, path: %s", match[0].arg, spath)
            spath = spath[1:]
            children = match[0].i_children
            logging.debug("Path is now: %s", spath)
        else:
            logging.debug("Miss at %s, path: %s", children, spath)
            raise error.EmitError("Path '%s' does not exist in module" % path)

    logging.debug("Ended up with %s %s", match[0].keyword, match[0].arg)
    return match[0]
Пример #8
0
    def handle_stmt(self, stmt, p_elem, pset={}):
        """
        Run handler method for `stmt` in the context of `p_elem`.

        All handler methods are defined below and have the same
        arguments. They should create the schema fragment
        corresponding to `stmt`, apply all patches from `pset`
        belonging to `stmt`, insert the fragment under `p_elem` and
        perform all side effects as necessary.
        """
        if self.debug > 0:
            sys.stderr.write("Handling '%s %s'\n" %
                             (util.keyword_to_str(stmt.raw_keyword), stmt.arg))
        try:
            method = self.stmt_handler[stmt.keyword]
        except KeyError:
            if isinstance(stmt.keyword, tuple):  # extension
                self.handle_extension(stmt, p_elem)
                return
            else:
                raise error.EmitError(
                    "Unknown keyword %s (this should not happen)\n" %
                    stmt.keyword)

        method(stmt, p_elem, pset)
Пример #9
0
 def emit(self, ctx, modules, fd):
     modulenames = [m.arg for m in modules]
     if not ctx.opts.ignore_errors:
         for (epos, etag, eargs) in ctx.errors:
             if (epos.top.arg in modulenames
                     and error.is_error(error.err_level(etag))):
                 raise error.EmitError("%s contains errors" % epos.top.arg)
     emit_docs(ctx, modules, fd)
Пример #10
0
 def emit(self, ctx, modules, fd):
     # cannot do this unless everything is ok for our module
     modulenames = [m.arg for m in modules]
     for (epos, etag, eargs) in ctx.errors:
         if (epos.top.arg in modulenames
                 and error.is_error(error.err_level(etag))):
             raise error.EmitError("%s contains errors" % epos.top.arg)
     emit_depend(ctx, modules, fd)
Пример #11
0
 def emit(self, ctx, modules, fd):
     # cannot do this unless everything is ok for our module
     modulenames = [m.arg for m in modules]
     for (epos, etag, eargs) in ctx.errors:
         if ((epos.top is None or epos.top.arg in modulenames)
                 and error.is_error(error.err_level(etag))):
             raise error.EmitError("%s contains more fundamental errors "\
                 "than the pattern statements" % epos.top.arg)
     emit_clean_pattern(ctx, modules, fd)
Пример #12
0
def emit_dsdl(ctx, modules, fd):
    for (epos, etag, eargs) in ctx.errors:
        if error.is_error(error.err_level(etag)):
            raise error.EmitError("DSDL translation needs a valid module")
    schema = HybridDSDLSchema().from_modules(modules,
                                  ctx.opts.dsdl_no_dublin_core,
                                  ctx.opts.dsdl_no_documentation,
                                  ctx.opts.dsdl_record_defs, debug=0)
    fd.write(schema.serialize())
Пример #13
0
    def emit(self, ctx, modules, fd):
        # Require error-free modules
        modulenames = [m.arg for m in modules]
        for (epos, etag, eargs) in ctx.errors:
            if (epos.top.arg in modulenames
                    and error.is_error(error.err_level(etag))):
                raise error.EmitError("%s contains errors" % epos.top.arg)

        emit_dot(ctx, modules, fd)
Пример #14
0
    def __init__(self, ctx):
        self._ctx = ctx
        self.ctx_fullpath = ctx.opts.longids
        self.ctx_description = ctx.opts.descr
        self.ctx_classesonly = ctx.opts.classes_only        
        # output dir from option -D or default img/
        if ctx.opts.outputdir is not None:
            self.ctx_outputdir = ctx.opts.outputdir
            if self.ctx_outputdir[len(self.ctx_outputdir)-1] != '/':
                self.ctx_outputdir += '/'
        else:
            self.ctx_outputdir = 'img/'

        # split into pages ? option -s
        if ctx.opts.pages_layout is not None:
            self.ctx_pagelayout = ctx.opts.pages_layout        

        # Title from option -t 
        self.ctx_title = ctx.opts.title

        self.ctx_inline_augments = ctx.opts.inline_augments

        self.ctx_leafrefs = not "leafref" in ctx.opts.no.split(",")
        self.ctx_uses = not "uses" in ctx.opts.no.split(",")
        self.ctx_annotations = not "annotation" in ctx.opts.no.split(",")
        self.ctx_identityrefs = not "identityref" in ctx.opts.no.split(",")
        self.ctx_identities = not "identity" in ctx.opts.no.split(",")
        self.ctx_typedefs = not "typedef" in ctx.opts.no.split(",")
        self.ctx_imports = not "import" in ctx.opts.no.split(",")
        self.ctx_circles = not "circles" in ctx.opts.no.split(",")
        self.ctx_stereotypes = not "stereotypes" in ctx.opts.no.split(",")

        nostrings = ("module", "leafref", "uses", "annotation", "identityref", "typedef", "import", "circles", "stereotypes")
        if ctx.opts.no != "":
            for no_opt in ctx.opts.no.split(","):
                if no_opt not in nostrings:
                    sys.stderr.write("\"%s\" no valid argument to --uml-no=...,  valid arguments: %s \n" %(no_opt, nostrings))
            
        self.ctx_filterfile = ctx.opts.gen_filter_file

        self.ctx_truncate_augments = "augment" in ctx.opts.truncate.split(",")
        self.ctx_truncate_leafrefs = "leafref" in ctx.opts.truncate.split(",")
        self.ctx_no_module = "module" in ctx.opts.no.split(",")

        truncatestrings = ("augment", "leafref")
        if ctx.opts.truncate != "":
            for trunc in ctx.opts.truncate.split(","):
                if trunc not in truncatestrings:
                    sys.stderr.write("\"%s\" no valid argument to --uml-truncate=...,  valid arguments: %s \n" %(trunc, truncatestrings))

        if ctx.opts.filter_file is not None:
            try:
                self.ctx_usefilterfile = open(ctx.opts.filter_file, "r")
                self.filterpaths = self.ctx_usefilterfile.readlines()
                self.ctx_usefilterfile.close()
            except IOError:
                raise error.EmitError("Filter file %s does not exist" %ctx.opts.filter_file, 2)
Пример #15
0
def emit_cts(ctx, module, fd):
    # No errors are allowed
    for (epos, etag, eargs) in ctx.errors:
        if (epos.top_name == module.arg
                and error.is_error(error.err_level(etag))):
            raise error.EmitError("CTS translation needs a valid module")
    schema = ConceptualTreeSchema().from_modules((module, ),
                                                 ctx.opts.cts_no_dublin_core,
                                                 ctx.opts.cts_no_documentation,
                                                 ctx.opts.cts_record_defs,
                                                 debug=0)
    fd.write(schema.serialize())
Пример #16
0
 def emit(self, ctx, modules, fd):
     """Main control function.
     """
     for (epos, etag, eargs) in ctx.errors:
         if error.is_error(error.err_level(etag)):
             raise error.EmitError("JTOX plugin needs a valid module")
     tree = {}
     mods = {}
     annots = {}
     for m, p in unique_prefixes(ctx).items():
         mods[m.i_modulename] = [p, m.search_one("namespace").arg]
     for module in modules:
         for ann in module.search(("ietf-yang-metadata", "annotation")):
             typ = ann.search_one("type")
             annots[module.arg + ":" + ann.arg] = ("string" if typ is None
                                                   else self.base_type(typ))
     for module in modules:
         self.process_children(module, tree, None)
     json.dump({"modules": mods, "tree": tree, "annotations": annots}, fd)
Пример #17
0
    def emit(self, ctx, modules, fd):
        """Main control function.

        Set up the top-level parts of the stylesheet, then process
        recursively all nodes in all data trees, and finally emit the
        serialized stylesheet.
        """
        for (epos, etag, eargs) in ctx.errors:
            if error.is_error(error.err_level(etag)):
                raise error.EmitError("JSONXSL plugin needs a valid module")
        self.real_prefix = unique_prefixes(ctx)
        self.top_names = []
        for m in modules:
            self.top_names.extend([
                c.arg for c in m.i_children
                if c.keyword not in ("rpc", "notification")
            ])
        tree = ET.ElementTree(ss)
        ET.SubElement(ss, "output", method="text")
        xsltdir = os.environ.get("PYANG_XSLT_DIR",
                                 "/usr/local/share/yang/xslt")
        ET.SubElement(ss, "include", href=xsltdir + "/jsonxsl-templates.xsl")
        ET.SubElement(ss, "strip-space", elements="*")
        nsmap = ET.SubElement(ss, "template", name="nsuri-to-module")
        ET.SubElement(nsmap, "param", name="uri")
        choo = ET.SubElement(nsmap, "choose")
        for module in self.real_prefix.keys():
            ns_uri = module.search_one("namespace").arg
            ss.attrib["xmlns:" + self.real_prefix[module]] = ns_uri
            when = ET.SubElement(choo, "when", test="$uri='" + ns_uri + "'")
            self.xsl_text(module.i_modulename, when)
            self.process_module(module)
        if sys.version > "3":
            tree.write(fd, encoding="unicode", xml_declaration=True)
        elif sys.version > "2.7":
            tree.write(fd, encoding="UTF-8", xml_declaration=True)
        else:
            tree.write(fd, encoding="UTF-8")
Пример #18
0
def emit_jtox(modules, ctx, fd):
    """Main control function.
    """
    for (epos, etag, eargs) in ctx.errors:
        if error.is_error(error.err_level(etag)):
            raise error.EmitError("JTOX plugin needs a valid module")
    tree = {}
    prefixes = []
    def unique_prefix(p):
        """Disambiguate the module prefix."""
        suffix = 0
        while p == "nc" or p in prefixes:
            p += "%d" % suffix
            suffix += 1
        return p
    for module in modules:
        uri = module.search_one("namespace").arg
        prf = unique_prefix(module.i_prefix)
        prefixes.append(prf)
        mods[module.i_modulename] = [prf, uri]
    for module in modules:
        process_children(module, tree)
    json.dump({"modules": mods, "tree": tree}, fd)
Пример #19
0
def get_arg_value(arg, currarg=None):
    if arg is None or arg[0] not in ['%', '@']:
        return arg, True
    else:
        replace = False
        try:
            argval = ''
            specs = arg.split('+')
            for spec in specs:
                if argval != '':
                    argval += '\n\n'
                if spec[0] not in ['%', '@']:
                    argval += spec
                elif spec[0] == '%':
                    if spec == '%SUMMARY':
                        summary = get_arg_summary(currarg)
                        if summary:
                            argval += summary
                    elif spec.startswith('%SUBST/'):
                        (ignore, old, new) = spec.split('/')
                        if currarg is None:
                            if argval == '':
                                argval = None
                        else:
                            argval = currarg.replace(old, new)
                        replace = True
                    elif spec == '%DELETE':
                        argval = ''
                        replace = True
                    else:
                        argval += spec
                elif spec[0] == '@':
                    argval += open(spec[1:], 'r').read().rstrip()
            return argval, replace
        except IOError as e:
            raise error.EmitError(str(e))
Пример #20
0
 def fatal(self, exitCode=1):
     """Raise an EmitError"""
     raise error.EmitError(self, exitCode)
Пример #21
0
 def fatal(self, exitCode=1):
     raise error.EmitError(self, exitCode)
Пример #22
0
def emit_xsd(ctx, module, fd):
    if module.keyword == 'submodule':
        belongs_to = module.search_one('belongs-to')
        parent_modulename = belongs_to.arg
        parent_module = ctx.read_module(parent_modulename)
        if parent_module is not None:
            i_namespace = parent_module.search_one('namespace').arg
            i_prefix = parent_module.search_one('prefix').arg
        else:
            raise error.EmitError("cannot find module %s, needed by XSD"
                                  " translation" % parent_modulename)
    else:
        i_namespace = module.search_one('namespace').arg
        i_prefix = module.search_one('prefix').arg

    # initialize some XSD specific variables
    module.i_namespace = i_namespace
    module.i_prefix = i_prefix
    module.i_gen_typedef = []
    module.i_gen_import = []
    module.i_gen_augment_idx = 0
    module.i_local_typedefs = []
    module.i_local_ctdefs = []

    # first, create top-level typedefs of local typedefs
    expand_locally_defined_defs(ctx, module, 'typedef',
                                module.i_local_typedefs)
    # first, create top-level complex types of local complex types
    expand_locally_defined_defs(ctx, module, complex_type,
                                module.i_local_ctdefs)

    # first pass, which might generate new imports
    ctx.i_pass = '******'
    dummyfd = DummyFD()
    print_children(ctx, module, dummyfd, module.i_children, '  ', [])
    for c in module.search('typedef'):
        print_simple_type(ctx, module, dummyfd, '  ', c.search_one('type'), '',
                          None)

    prefixes = [module.i_prefix] + [p for p in module.i_prefixes]
    if module.i_prefix in ['xs', 'yin', 'nc', 'ncn']:
        i = 0
        pre = "p" + str(i)
        while pre in prefixes:
            i = i + 1
            pre = "p" + str(i)
        prefixes.append(pre)
        module.i_prefix = pre

    has_rpc = False
    has_notifications = False
    for c in module.substmts:
        if c.keyword == 'notification':
            has_notifications = True
        elif c.keyword == 'rpc':
            has_rpc = True

    fd.write('<?xml version="1.0" encoding="UTF-8"?>\n')
    fd.write('<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"\n')
    if ctx.opts.xsd_no_appinfo != True:
        fd.write('           ' \
                       'xmlns:yin="urn:ietf:params:xml:schema:yang:yin:1"\n')
    if has_rpc == True:
        fd.write('           ' \
                       'xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"\n')
    if has_notifications == True:
        fd.write('           xmlns:ncn="urn:ietf:params:xml:ns:' \
                       'netconf:notification:1.0"\n')
    fd.write('           targetNamespace="%s"\n' % module.i_namespace)
    fd.write('           xmlns="%s"\n' % module.i_namespace)
    fd.write('           elementFormDefault="qualified"\n')
    fd.write('           attributeFormDefault="unqualified"\n')
    if len(module.search('revision')) > 0:
        fd.write('           version="%s"\n' %
                 module.search('revision')[0].arg)
    fd.write('           xml:lang="en"')
    for pre in module.i_prefixes:
        (modname, revision) = module.i_prefixes[pre]
        if modname == module.arg:
            mod = module
        else:
            mod = ctx.get_module(modname, revision)
        if mod.keyword == 'module':
            if pre in ['xs', 'yin', 'nc', 'ncn']:
                # someone uses one of our prefixes
                # generate a new prefix for that module
                i = 0
                pre = "p" + str(i)
                while pre in prefixes:
                    i = i + 1
                    pre = "p" + str(i)
                prefixes.append(pre)
            mod.i_prefix = pre
            uri = mod.search_one('namespace').arg
            fd.write('\n           xmlns:' + pre + '=' + quoteattr(uri))
    fd.write('>\n\n')

    if ctx.opts.xsd_no_imports != True:
        imports = module.search('import') + module.i_gen_import
        for x in imports:
            rev = None
            r = x.search_one('revision-date')
            if r is not None:
                rev = r.arg
            mod = ctx.get_module(x.arg, rev)
            uri = mod.search_one('namespace').arg
            fd.write('  <xs:import namespace="%s"\n' \
                     '             schemaLocation="%s.xsd"/>\n' %
                       (uri, x.arg))
        if has_rpc and module.arg == 'ietf-netconf':
            # this is the YANG mdoule for the NETCONF operations
            # FIXME: when 4741bis has been published, change
            # the schema location to a http uri
            fd.write('  <xs:include\n')
            fd.write('    schemaLocation="netconf.xsd"/>')
        elif has_rpc:
            fd.write('  <xs:import\n')
            fd.write('     namespace=' \
                           '"urn:ietf:params:xml:ns:netconf:base:1.0"\n')
            fd.write('     schemaLocation="http://www.iana.org/assignments/' \
                         'xml-registry/schema/netconf.xsd"/>')
        if has_notifications:
            fd.write('  <xs:import\n')
            fd.write('     namespace="urn:ietf:params:xml:ns:netconf:' \
                           'notification:1.0"\n')
            fd.write('     schemaLocation="http://www.iana.org/assignments/' \
                         'xml-registry/schema/notification.xsd"/>')
        if len(imports) > 0 or has_rpc or has_notifications:
            fd.write('\n')

    if ctx.opts.xsd_no_includes != True:
        for inc in module.search('include'):
            fd.write('  <xs:include schemaLocation="%s.xsd"/>\n' % inc.arg)

    if ctx.opts.xsd_no_lecture != True:
        fd.write('  <xs:annotation>\n')
        fd.write('    <xs:documentation>\n')
        fd.write('      This schema was generated from the YANG module %s\n' % \
                     module.arg)
        fd.write('      by pyang version %s.\n' % pyang.__version__)
        fd.write('\n')
        fd.write(
            '      The schema describes an instance document consisting\n')
        fd.write('      of the entire configuration data store, operational\n')
        fd.write('      data, rpc operations, and notifications.\n')
        fd.write('      This schema can thus NOT be used as-is to\n')
        fd.write('      validate NETCONF PDUs.\n')
        fd.write('    </xs:documentation>\n')
        fd.write('  </xs:annotation>\n\n')

    print_annotation(ctx, fd, '  ', module)
    ctx.i_pass = '******'

    # print typedefs
    if len(module.search('typedef')) > 0:
        fd.write('\n  <!-- YANG typedefs -->\n')
    for c in module.search('typedef'):
        fd.write('\n')
        print_simple_type(ctx, module, fd, '  ', c.search_one('type'),
                          ' name="%s"' % c.i_xsd_name,
                          c.search_one('description'))

    # print locally defined typedefs
    if len(module.i_local_typedefs) > 0:
        fd.write('\n  <!-- local YANG typedefs -->\n')
    for c in module.i_local_typedefs:
        fd.write('\n')
        print_simple_type(ctx, module, fd, '  ', c.search_one('type'),
                          ' name="%s"' % c.i_xsd_name,
                          c.search_one('description'))

    # print groups
    if len(module.search('grouping')) > 0:
        fd.write('\n  <!-- YANG groupings -->\n')
    for c in module.search('grouping'):
        fd.write('\n')
        print_grouping(ctx, module, fd, '  ', c)

    # print complex types
    if len(module.search(('complex-types', 'complex-type'))) > 0:
        fd.write('\n  <!-- YANG complex-types -->\n')
    for c in module.search(('complex-types', 'complex-type')):
        fd.write('\n')
        print_complex_type(ctx, module, fd, '  ', c)

    # print locally defined complex types
    if len(module.i_local_ctdefs) > 0:
        fd.write('\n  <!-- local YANG complex types -->\n')
    for c in module.i_local_ctdefs:
        fd.write('\n')
        print_complex_type(ctx, module, fd, '  ', c)

    # print augments
    # filter away local augments; they are printed inline in the XSD
    augment = [a for a in module.search('augment') \
                   if a.i_target_node.i_module.arg != module.arg]
    if len(augment) > 0:
        fd.write('\n  <!-- YANG augments -->\n')
    for c in augment:
        fd.write('\n')
        print_augment(ctx, module, fd, '  ', c)

    fd.write('\n')
    # print data definitions
    print_children(ctx, module, fd, module.i_children, '  ', [])

    # then print all generated 'dummy' simpleTypes, if any
    if len(module.i_gen_typedef) > 0:
        fd.write('\n  <!-- locally generated simpleType helpers -->\n')
    for c in module.i_gen_typedef:
        fd.write('\n')
        print_simple_type(ctx, module, fd, '  ', c.search_one('type'),
                          ' name="%s"' % c.arg, None)

    fd.write('\n</xs:schema>\n')
Пример #23
0
 def emit(self, ctx, modules, fd):
     if 'submodule' in [ m.keyword for m in modules ]:
         raise error.EmitError("Cannot translate submodules")
     emit_dsdl(ctx, modules, fd)
Пример #24
0
 def from_modules(self, modules, no_dc=False, no_a=False,
                  record_defs=False, lax_yang_version=False, debug=0):
     """Return the instance representing mapped input modules."""
     self.namespaces = {
         "urn:ietf:params:xml:ns:netmod:dsdl-annotations:1" : "nma",
     }
     if not no_dc: self.namespaces[self.dc_uri] = "dc"
     if not no_a: self.namespaces[self.a_uri] = "a"
     self.global_defs = {}
     self.all_defs = {}
     self.identity_deps = {}
     self.identities = {}
     self.debug = debug
     self.module_prefixes = {}
     gpset = {}
     self.gg_level = 0
     metadata = []
     self.has_meta = False
     for module in modules[0].i_ctx.modules.values():
         yver = module.search_one("yang-version")
         if yver and float(yver.arg) > 1.0 and not lax_yang_version:
             raise error.EmitError(
                 "DSDL plugin supports only YANG version 1.")
         if module.keyword == "module":
             for idn in module.i_identities.values():
                 self.register_identity(idn)
     for module in modules:
         self.add_namespace(module)
         self.module = module
         annots = module.search(("ietf-yang-metadata", "annotation"))
         for ann in annots:
             aname = (self.module_prefixes[ann.main_module().arg] + ":" +
                      ann.arg)
             optel = SchemaNode("optional")
             atel = SchemaNode("attribute", optel).set_attr("name", aname)
             self.handle_substmts(ann, atel)
             metadata.append(optel)
     if metadata:
         self.has_meta = True
         metel = SchemaNode.define("__yang_metadata__")
         self.global_defs["__yang_metadata__"] = metel
         for mattr in metadata:
             metel.subnode(mattr)
     for module in modules:
         self.module = module
         self.prefix_stack = [self.module_prefixes[module.arg]]
         for aug in module.search("augment"):
             self.add_patch(gpset, aug)
         for sub in [ module.i_ctx.get_module(inc.arg)
                      for inc in module.search("include") ]:
             for aug in sub.search("augment"):
                 self.add_patch(gpset, aug)
     self.setup_top()
     for module in modules:
         self.module = module
         self.local_defs = {}
         if record_defs: self.preload_defs()
         self.prefix_stack = [self.module_prefixes[module.arg]]
         self.create_roots(module)
         self.lookup_expand(module, list(gpset.keys()))
         self.handle_substmts(module, self.data, gpset)
         for d in list(self.local_defs.values()):
             self.local_grammar.subnode(d)
         self.tree.subnode(self.local_grammar)
         self.all_defs.update(self.local_defs)
     self.all_defs.update(self.global_defs)
     self.dc_element(self.top_grammar, "date", time.strftime("%Y-%m-%d"))
     return self
Пример #25
0
 def yang_version_stmt(self, stmt, p_elem, pset):
     if float(stmt.arg) > self.YANG_version:
         raise error.EmitError("Unsupported YANG version: %s" % stmt.arg)
Пример #26
0
 def emit(self, ctx, module, fd):
     if module.keyword == 'submodule':
         raise error.EmitError("Cannot translate submodules")
     emit_cts(ctx, module, fd)