Exemple #1
0
    def representTextStruct(dumper, data):
        dataList = [
            #(stringNode('index'), stringNode('0x' + myhex(data.index, 4))),
        ]

        if len(data.indices) != 1:
            extraIndexList = data.indices
            assert (extraIndexList == sorted(extraIndexList))

            nameList = [stringNode(getTextName(x)) for x in extraIndexList]
            dataList.append((stringNode('name'),
                             yaml.SequenceNode('tag:yaml.org,2002:seq',
                                               nameList)))

            extraIndexList = [
                intNode('0x' + myhex(x & 0xff, 2)) for x in extraIndexList
            ]
            dataList.append((stringNode('index'),
                             yaml.SequenceNode('tag:yaml.org,2002:seq',
                                               extraIndexList)))
        else:
            assert (data.indices[0] == data.index)
            dataList.append(stringMap('name', data.name))
            dataList.append((stringNode('index'),
                             intNode('0x' + myhex(data.index & 0xff, 2))))

        dataList.append((stringNode('text'),
                         dumper.represent_scalar(stringTag, data.textData,
                                                 '|')))
        if not data.hasNullTerminator:
            dataList.append((stringNode('null_terminator'),
                             boolNode(data.hasNullTerminator)))

        return yaml.MappingNode('tag:yaml.org,2002:map', dataList)
Exemple #2
0
    def get_representation(self, value, v_type):
        ''''''
        if v_type.startswith("dict"):
            return self.represent_dict(value)
        elif v_type.startswith('list'):
            if 'ExtraPath' in v_type:
                # Represent this as a list of lists of quoted strings (each on one line).
                paths = []
                for path in list(value):
                    # Force the regular expressions to be quoted, so we don't have any issues with that.
                    pathnodes = [
                        self.represent_scalar(u'tag:yaml.org,2002:str',
                                              x,
                                              style="'") for x in path
                    ]
                    paths.append(
                        yaml.SequenceNode(u'tag:yaml.org,2002:seq',
                                          pathnodes,
                                          flow_style=True))
                return yaml.SequenceNode(u'tag:yaml.org,2002:seq',
                                         paths,
                                         flow_style=False)
            elif 'class' in v_type:
                # The "class" in this context is either a class reference or
                # a class name (string) that refers to a class defined in
                # this ZenPackSpec.
                classes = [
                    isinstance(x, type) and self.class_to_str(x) or x
                    for x in value
                ]
                return self.represent_list(classes)
            else:
                return self.represent_list(value)
        else:
            m = re.match('^SpecsParameter\((.*)\)$', v_type)
            if m:
                spectype = m.group(1)
                specmapping = OrderedDict()
                defaults = value.get('DEFAULTS', None)
                if defaults:
                    value.pop('DEFAULTS')
                for key, spec in value.items():
                    if type(spec).__name__ != spectype:
                        raise yaml.representer.RepresenterError(
                            "Unable to serialize {} object ({}):  Expected an object of type {}"
                            .format(type(spec).__name__, key, spectype))
                    else:
                        specmapping[self.represent_str(
                            key)] = self.represent_spec(spec,
                                                        defaults=defaults)
                return self.dict_representer(specmapping)

            else:
                self.LOG.debug("Using represent_data for {} ({})".format(
                    value, v_type))
                return self.represent_data(value)
        return None
Exemple #3
0
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
Exemple #4
0
def aws_cloudformation_intrinsic_function(loader, node):
    fn = f"Fn::{node.tag[1:]}"
    if node.tag in ('!Ref', '!Condition'):
        fn = 'Ref'
    elif node.tag == '!GetAtt' and isinstance(node.value, str):
        path = node.value.split(".", maxsplit=2)
        node = yaml.SequenceNode(tag="tag:yaml.org,2002:seq",
                                 value=[str_node(p) for p in path])
    sub_node: yaml.Node
    if isinstance(node, yaml.SequenceNode):
        sub_node = seq_node(node.value)
    elif isinstance(node, yaml.MappingNode):
        sub_node = map_node(node.value)
    elif node.value is None:
        sub_node = yaml.ScalarNode('tag:yaml.org,2002:null', node.value)
    elif isinstance(node.value, str):
        sub_node = yaml.ScalarNode('tag:yaml.org,2002:str', node.value)
    elif isinstance(node.value, bool):
        sub_node = yaml.ScalarNode('tag:yaml.org,2002:bool', node.value)
    elif isinstance(node.value, int):
        sub_node = yaml.ScalarNode('tag:yaml.org,2002:int', node.value)
    elif isinstance(node.value, float):
        sub_node = yaml.ScalarNode('tag:yaml.org,2002:float', node.value)
    else:
        raise ValueError(node)
    new_node = map_node([(str_node(fn), sub_node)])
    return loader.construct_object(new_node)
Exemple #5
0
 def format_node(cls, mapping, metric):
     if mapping.tag in [
             'tag:yaml.org,2002:str', Bytes2Kibibytes.yaml_tag,
             Number.yaml_tag, StripExtraDash.yaml_tag
     ]:
         return yaml.ScalarNode(mapping.tag, mapping.value.format(**metric))
     elif mapping.tag == 'tag:yaml.org,2002:map':
         values = []
         for key, value in mapping.value:
             values.append((yaml.ScalarNode(key.tag, key.value),
                            cls.format_node(value, metric)))
         return yaml.MappingNode(mapping.tag, values)
     elif mapping.tag in [ArrayItem.yaml_tag, ValueItem.yaml_tag]:
         values = []
         for seq in mapping.value:
             map_values = list()
             for key, value in seq.value:
                 if key.value == 'SELECT':
                     map_values.append((yaml.ScalarNode(key.tag, key.value),
                                        cls.format_node(value, metric)))
                 else:
                     map_values.append((yaml.ScalarNode(key.tag,
                                                        key.value), value))
             values.append(yaml.MappingNode(seq.tag, map_values))
         return yaml.SequenceNode(mapping.tag, values)
     elif mapping.tag in [MapValue.yaml_tag]:
         values = []
         for key, value in mapping.value:
             if key.value == 'VALUE':
                 values.append((yaml.ScalarNode(key.tag, key.value),
                                cls.format_node(value, metric)))
             else:
                 values.append((yaml.ScalarNode(key.tag, key.value), value))
         return yaml.MappingNode(mapping.tag, values)
     return mapping
Exemple #6
0
 def _node(self):
     """
     Create a yaml node object.
     """
     node = yaml.SequenceNode(
         tag='tag:yaml.org,2002:seq',
         value=[
             yaml.ScalarNode(tag='tag:yaml.org,2002:str', value='a'),
             yaml.ScalarNode(tag='tag:yaml.org,2002:str', value='b'),
             yaml.ScalarNode(tag='tag:yaml.org,2002:str', value='c'),
         ])
     return node
Exemple #7
0
def represent_ordereddict(dumper, data):
    # TODO: Again, adjust for preferred flow style, and other stylistic details
    # NOTE: For block style this uses the compact omap notation, but for flow style
    # it does not.
    values = []
    node = yaml.SequenceNode(u'tag:yaml.org,2002:seq', values, flow_style=True)
    if dumper.alias_key is not None:
        dumper.represented_objects[dumper.alias_key] = node
    for key, value in data.items():
        key_item = dumper.represent_data(key)
        value_item = dumper.represent_data(value)
        node_item = yaml.MappingNode(u'tag:yaml.org,2002:map', [(key_item, value_item)],
                                     flow_style=False)
        values.append(node_item)
    return node
Exemple #8
0
def represent_ordered_mapping(dumper, tag, data):
    # TODO: Again, adjust for preferred flow style, and other stylistic details
    # NOTE: For block style this uses the compact omap notation, but for flow style
    # it does not.

    # TODO: Need to see if I can figure out a mechanism so that classes that
    # use this representer can specify which values should use flow style
    values = []
    node = yaml.SequenceNode(tag, values, flow_style=dumper.default_flow_style)
    if dumper.alias_key is not None:
        dumper.represented_objects[dumper.alias_key] = node
    for key, value in data.items():
        key_item = dumper.represent_data(key)
        value_item = dumper.represent_data(value)
        node_item = yaml.MappingNode(YAML_OMAP_TAG, [(key_item, value_item)],
                                     flow_style=False)
        values.append(node_item)
    return node
Exemple #9
0
def seq_node(value) -> yaml.SequenceNode:
    return yaml.SequenceNode(tag="tag:yaml.org,2002:seq", value=value)