python-poetry / tomlkit

Style-preserving TOML library for Python
MIT License
701 stars 99 forks source link

Newline lost when updating a table #318

Closed JulienPalard closed 1 year ago

JulienPalard commented 1 year ago

May be related to https://github.com/sdispater/tomlkit/issues/48.

Spotted a whitespace inconsistency between adding vs updating a table:

>>> import tomlkit
>>> d = tomlkit.document()
>>> d.setdefault("a", {})["b"] = {"foo": "bar"}
>>> d.setdefault("b", {})["b"] = {"foo": "bar"}
>>> print(tomlkit.dumps(d))  # I'm happy with the newlines ♥
[a.b]
foo = "bar"

[b.b]
foo = "bar"

>>> d = tomlkit.loads(tomlkit.dumps(d))
>>> d.setdefault("a", {})["b"] = {"foo": "baz"}
>>> print(tomlkit.dumps(d))  # Where are the newlines???
[a.b]
foo = "baz"
[b.b]
foo = "bar"
>>> tomlkit.__version__
'0.12.1'
frostming commented 1 year ago

What happened is, when you parse the TOML document, the newline is attached to the sub table foo = "bar". But later you replaced the whole table with a new one, then tomlkit doesn't know it should add a newline to the end, think of the subtable doesn't know its position in the parsed tree unless it looks up for siblings of parents, which would be complex.

image

To compare, make the second table a sibling of the first one, namely:

[a.b]
foo = "bar"

[a.c]
foo = "bar"

Then the tree would look like: image

I hope there would be more people reading the codebase and help improve this(kind of mess), instead of just opening an issue and complain why it doesn't work.

JulienPalard commented 1 year ago

I hope there would be more people reading the codebase and help improve this(kind of mess), instead of just opening an issue and complain why it doesn't work.

I feel you.

I would love to have the free time to yak-shave on FOSS projects while I'm yak-shaving on FOSS projects, but this day I just ran out of time.

So instead of just shutting down my laptop I though that opening an issue to document what I've found would be better than nothing.

I was really not complaining, just documenting the thing. Sorry.

Oh while I'm here, thanks for your time on this project !