~martijnbraam/bare-py

30592effb7b6e567bafa370a01559e280dc38e1e — Martijn Braam 8 months ago ade421e
Better union label handling in dump
1 files changed, 21 insertions(+), 5 deletions(-)

M bare/dump.py
M bare/dump.py => bare/dump.py +21 -5
@@ 53,9 53,9 @@ def import_schema(schema):
    return schema_module


def dump(data, type, module):
def dump(data, type, module, name):
    node = type._ast
    label = None
    label = name
    offset = 0
    nodelist = []
    indent = 0


@@ 69,6 69,15 @@ def dump(data, type, module):
                newnodes.append((node._ast.fields[fieldname], fieldname))
            nodelist = newnodes + [(None, None)] + nodelist
            indent += 1
        elif isinstance(node, StructType):
            yield Line(b'', 'struct {}'.format(label), '', indent)
            end_offset = offset

            newnodes = []
            for fieldname in node.fields:
                newnodes.append((node.fields[fieldname], fieldname))
            nodelist = newnodes + [(None, None)] + nodelist
            indent += 1
        elif hasattr(node, '_ast') and isinstance(node._ast, BarePrimitive):
            nodelist = [(node._ast, label)] + nodelist
        elif isinstance(node, UnionType):


@@ 78,8 87,15 @@ def dump(data, type, module):
                    break
            else:
                raise ValueError("Cannot find type for tag {}".format(tag))
            yield Line(data[offset:end_offset], 'Union', 'tag = {} ({})'.format(tag, type.type.name), indent)
            nodelist = [(getattr(module, type.type.name), type.type.name), (None, None)] + nodelist
            if isinstance(type.type, BarePrimitive):
                name = type.type.type.name
            else:
                name = type.type.name
            yield Line(data[offset:end_offset], label, 'union, tag = {} ({})'.format(tag, name), indent)
            if isinstance(type.type, BarePrimitive):
                nodelist = [(type.type, name), (None, None)] + nodelist
            else:
                nodelist = [(getattr(module, type.type.name), type.type.name), (None, None)] + nodelist
            indent += 1
        elif isinstance(node, BarePrimitive):
            value, end_offset = _unpack_primitive(node, data, offset)


@@ 162,7 178,7 @@ def main():
    schema = import_schema(args.schema.read())
    type = getattr(schema, args.type)

    for line in dump(message, type, schema):
    for line in dump(message, type, schema, args.type):
        print(line, end='')