Python yaml.SequenceNode() Examples

The following are 11 code examples of yaml.SequenceNode(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module yaml , or try the search function .
Example #1
Source File: cfn_yaml.py    From checkov with Apache License 2.0 6 votes vote down vote up
def multi_constructor(loader, tag_suffix, node):
    """
    Deal with !Ref style function format
    """

    if tag_suffix not in UNCONVERTED_SUFFIXES:
        tag_suffix = '{}{}'.format(FN_PREFIX, tag_suffix)

    constructor = None
    if tag_suffix == 'Fn::GetAtt':
        constructor = construct_getatt
    elif isinstance(node, ScalarNode):
        constructor = loader.construct_scalar
    elif isinstance(node, SequenceNode):
        constructor = loader.construct_sequence
    elif isinstance(node, MappingNode):
        constructor = loader.construct_mapping
    else:
        raise 'Bad tag: !{}'.format(tag_suffix)

    return dict_node({tag_suffix: constructor(node)}, node.start_mark, node.end_mark) 
Example #2
Source File: yaml_loader.py    From aws-cfn-template-flip with Apache License 2.0 6 votes vote down vote up
def multi_constructor(loader, tag_suffix, node):
    """
    Deal with !Ref style function format
    """

    if tag_suffix not in UNCONVERTED_SUFFIXES:
        tag_suffix = "{}{}".format(FN_PREFIX, tag_suffix)

    constructor = None

    if tag_suffix == "Fn::GetAtt":
        constructor = construct_getatt
    elif isinstance(node, yaml.ScalarNode):
        constructor = loader.construct_scalar
    elif isinstance(node, yaml.SequenceNode):
        constructor = loader.construct_sequence
    elif isinstance(node, yaml.MappingNode):
        constructor = loader.construct_mapping
    else:
        raise Exception("Bad tag: !{}".format(tag_suffix))

    return ODict((
        (tag_suffix, constructor(node)),
    )) 
Example #3
Source File: yaml_odict.py    From airspyone_firmware with GNU General Public License v2.0 6 votes vote down vote up
def repr_pairs(dump, tag, sequence, flow_style=None):
    """This is the same code as BaseRepresenter.represent_sequence(),
    but the value passed to dump.represent_data() in the loop is a
    dictionary instead of a tuple."""
 
    value = []
    node = yaml.SequenceNode(tag, value, flow_style=flow_style)
    if dump.alias_key is not None:
        dump.represented_objects[dump.alias_key] = node
    best_style = True
    for (key, val) in sequence:
        item = dump.represent_data({key: val})
        if not (isinstance(item, yaml.ScalarNode) and not item.style):
            best_style = False
        value.append(item)
    if flow_style is None:
        if dump.default_flow_style is not None:
            node.flow_style = dump.default_flow_style
        else:
            node.flow_style = best_style
    return node 
Example #4
Source File: specific_function.py    From nxs-backup with GNU General Public License v3.0 6 votes vote down vote up
def include(self, node):
        if isinstance(node, yaml.ScalarNode):
            return self.extractFile(self.construct_scalar(node))

        elif isinstance(node, yaml.SequenceNode):
            result = []

            for i in self.construct_sequence(node):
                i = general_function.get_absolute_path(i, self._root)
                for j in general_files_func.get_ofs(i):
                    result += self.extractFile(j)
            return result

        elif isinstance(node, yaml.MappingNode):
            result = {}
            for k,v in self.construct_mapping(node).iteritems():
                result[k] = self.extractFile(v)
            return result

        else:
            print ('Error:: unrecognised node type in !include statement')
            raise yaml.constructor.ConstructorError 
Example #5
Source File: file_loader.py    From cfn-sphere with Apache License 2.0 5 votes vote down vote up
def handle_yaml_constructors(loader, suffix, node):
        """
        Constructor method for PyYaml to handle cfn intrinsic functions specified as yaml tags
        """
        function_mapping = {
            "!and": ("Fn::And", lambda x: x),
            "!base64": ("Fn::Base64", lambda x: x),
            "!condition": ("Condition", lambda x: x),
            "!equals": ("Fn::Equals", lambda x: x),
            "!findinmap": ("Fn::FindInMap", lambda x: x),
            "!getatt": ("Fn::GetAtt", lambda x: str(x).split(".", 1)),
            "!getazs": ("Fn::GetAZs", lambda x: x),
            "!if": ("Fn::If", lambda x: x),
            "!importvalue": ("Fn::ImportValue", lambda x: x),
            "!join": ("Fn::Join", lambda x: [x[0], x[1]]),
            "!not": ("Fn::Not", lambda x: x),
            "!or": ("Fn::Or", lambda x: x),
            "!ref": ("Ref", lambda x: x),
            "!select": ("Fn::Select", lambda x: x),
            "!split": ("Fn::Split", lambda x: x),
            "!sub": ("Fn::Sub", lambda x: x),
        }
        try:
            function, value_transformer = function_mapping[str(suffix).lower()]
        except KeyError as key:
            raise CfnSphereException(
                "Unsupported cfn intrinsic function tag found: {0}".format(key))

        if isinstance(node, yaml.ScalarNode):
            value = loader.construct_scalar(node)
        elif isinstance(node, yaml.SequenceNode):
            value = loader.construct_sequence(node)
        elif isinstance(node, yaml.MappingNode):
            value = loader.construct_mapping(node)
        else:
            raise CfnSphereException(
                "Invalid yaml node found while handling cfn intrinsic function tags")

        return {function: value_transformer(value)} 
Example #6
Source File: support.py    From StrategyEase-Python-SDK with MIT License 5 votes vote down vote up
def construct_odict(self, node):
        omap = OrderedDict()
        yield omap
        if not isinstance(node, yaml.SequenceNode):
            raise yaml.constructor.ConstructorError(
                "while constructing an ordered map",
                node.start_mark,
                "expected a sequence, but found %s" % node.id, node.start_mark
            )
        for subnode in node.value:
            if not isinstance(subnode, yaml.MappingNode):
                raise yaml.constructor.ConstructorError(
                    "while constructing an ordered map", node.start_mark,
                    "expected a mapping of length 1, but found %s" % subnode.id,
                    subnode.start_mark
                )
            if len(subnode.value) != 1:
                raise yaml.constructor.ConstructorError(
                    "while constructing an ordered map", node.start_mark,
                    "expected a single mapping item, but found %d items" % len(subnode.value),
                    subnode.start_mark
                )
            key_node, value_node = subnode.value[0]
            key = self.construct_object(key_node)
            value = self.construct_object(value_node)
            omap[key] = value 
Example #7
Source File: parser.py    From ambassador with Apache License 2.0 5 votes vote down vote up
def load(name: str, value: Any, *allowed: Tag) -> SequenceView:
    if isinstance(value, str):
        value = StringIO(value)
        value.name = name
    result = view(SequenceNode(Tag.SEQUENCE.value, list(compose_all(value))), ViewMode.PYTHON)
    for r in view(result, ViewMode.NODE):
        if r.tag not in allowed:
            raise ValueError("expecting %s, got %s" % (", ".join(t.name for t in allowed),
                                                       r.node.tag))
    return result 
Example #8
Source File: config.py    From insteon-mqtt with GNU General Public License v3.0 5 votes vote down vote up
def include(self, node):
        """!include file command.  Supports:

        foo: !include file.yaml
        foo: !include [file1.yaml, file2.yaml]

        Args:
          node:  The YAML node to load.
        """
        # input is a single file to load.
        if isinstance(node, yaml.ScalarNode):
            include_file = self.construct_scalar(node)
            return self._load_file(include_file)

        # input is a list of files to load.
        elif isinstance(node, yaml.SequenceNode):
            result = []
            for include_file in self.construct_sequence(node):
                result += self._load_file(include_file)
            return result

        else:
            msg = ("Error: unrecognized node type in !include statement: %s"
                   % str(node))
            raise yaml.constructor.ConstructorError(msg)

    #----------------------------------------------------------------------- 
Example #9
Source File: meta.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _repr_pairs(dump, tag, sequence, flow_style=None):
    """
    This is the same code as BaseRepresenter.represent_sequence(),
    but the value passed to dump.represent_data() in the loop is a
    dictionary instead of a tuple.

    Source: https://gist.github.com/weaver/317164
    License: Unspecified
    """
    import yaml

    value = []
    node = yaml.SequenceNode(tag, value, flow_style=flow_style)
    if dump.alias_key is not None:
        dump.represented_objects[dump.alias_key] = node
    best_style = True
    for (key, val) in sequence:
        item = dump.represent_data({key: val})
        if not (isinstance(item, yaml.ScalarNode) and not item.style):
            best_style = False
        value.append(item)
    if flow_style is None:
        if dump.default_flow_style is not None:
            node.flow_style = dump.default_flow_style
        else:
            node.flow_style = best_style
    return node 
Example #10
Source File: yaml_odict.py    From airspyone_firmware with GNU General Public License v2.0 4 votes vote down vote up
def construct_odict(load, node):
    """This is the same as SafeConstructor.construct_yaml_omap(),
    except the data type is changed to OrderedDict() and setitem is
    used instead of append in the loop.
 
    >>> yaml.load('''
    ... !!omap
    ... - foo: bar
    ... - mumble: quux
    ... - baz: gorp
    ... ''')
    OrderedDict([('foo', 'bar'), ('mumble', 'quux'), ('baz', 'gorp')])
 
    >>> yaml.load('''!!omap [ foo: bar, mumble: quux, baz : gorp ]''')
    OrderedDict([('foo', 'bar'), ('mumble', 'quux'), ('baz', 'gorp')])
    """
 
    omap = OrderedDict()
    yield omap
    if not isinstance(node, yaml.SequenceNode):
        raise yaml.constructor.ConstructorError(
            "while constructing an ordered map",
            node.start_mark,
            "expected a sequence, but found %s" % node.id, node.start_mark
        )
    for subnode in node.value:
        if not isinstance(subnode, yaml.MappingNode):
            raise yaml.constructor.ConstructorError(
                "while constructing an ordered map", node.start_mark,
                "expected a mapping of length 1, but found %s" % subnode.id,
                subnode.start_mark
            )
        if len(subnode.value) != 1:
            raise yaml.constructor.ConstructorError(
                "while constructing an ordered map", node.start_mark,
                "expected a single mapping item, but found %d items" % len(subnode.value),
                subnode.start_mark
            )
        key_node, value_node = subnode.value[0]
        key = load.construct_object(key_node)
        value = load.construct_object(value_node)
        omap[key] = value 
Example #11
Source File: meta.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _construct_odict(load, node):
    """
    Construct OrderedDict from !!omap in yaml safe load.

    Source: https://gist.github.com/weaver/317164
    License: Unspecified

    This is the same as SafeConstructor.construct_yaml_omap(),
    except the data type is changed to OrderedDict() and setitem is
    used instead of append in the loop

    Examples
    --------
    ::

      >>> yaml.load('''  # doctest: +SKIP
      ... !!omap
      ... - foo: bar
      ... - mumble: quux
      ... - baz: gorp
      ... ''')
      OrderedDict([('foo', 'bar'), ('mumble', 'quux'), ('baz', 'gorp')])

      >>> yaml.load('''!!omap [ foo: bar, mumble: quux, baz : gorp ]''')  # doctest: +SKIP
      OrderedDict([('foo', 'bar'), ('mumble', 'quux'), ('baz', 'gorp')])
    """
    import yaml

    omap = OrderedDict()
    yield omap
    if not isinstance(node, yaml.SequenceNode):
        raise yaml.constructor.ConstructorError(
            "while constructing an ordered map", node.start_mark,
            f"expected a sequence, but found {node.id}", node.start_mark)

    for subnode in node.value:
        if not isinstance(subnode, yaml.MappingNode):
            raise yaml.constructor.ConstructorError(
                "while constructing an ordered map", node.start_mark,
                f"expected a mapping of length 1, but found {subnode.id}",
                subnode.start_mark)

        if len(subnode.value) != 1:
            raise yaml.constructor.ConstructorError(
                "while constructing an ordered map", node.start_mark,
                "expected a single mapping item, but found {} items".format(len(subnode.value)),
                subnode.start_mark)

        key_node, value_node = subnode.value[0]
        key = load.construct_object(key_node)
        value = load.construct_object(value_node)
        omap[key] = value