kislyuk / yq

Command-line YAML, XML, TOML processor - jq wrapper for YAML/XML/TOML documents
https://kislyuk.github.io/yq/
Apache License 2.0
2.53k stars 81 forks source link

TOML comment and other formatting roundtripping #192

Open kislyuk opened 2 months ago

kislyuk commented 2 months ago

tomlkit provides the ability to emit comments as metadata keys, similar to what we do in yq -Y:

import tomlkit

def repr(i, indent=0):
    if isinstance(i, tomlkit.items.Item):
        print(" " * indent, "ITEM", type(i), type(i.value), "TRIVIA", i.trivia)
        if isinstance(i.value, tomlkit.container.Container):
            repr(i.value, indent=indent + 2)
        else:
            print(" " * indent, "SCALAR", type(i), i)
    if isinstance(i, tomlkit.container.Container):
        print(" " * indent, "CONTAINER", type(i))
        for k, v in i.body:
            print(" " * indent, k, "\t", type(v), "\t>>>", str(v)[:20] + "..." if len(str(v)) > 20 else str(v))
            if isinstance(v, (dict, list)):
                repr(v, indent=indent + 2)

with open("pyproject.toml") as fh:
    doc = tomlkit.parse(fh.read())
    repr(doc)