yaml icon indicating copy to clipboard operation
yaml copied to clipboard

Comment handling is off by one

Open bodinsamuel opened this issue 1 year ago • 4 comments

Describe the bug When dealing with nested object and comments, some comments get pushed into the parent until we reach the last level. Only the last element is correct.

To Reproduce

https://codesandbox.io/p/devbox/2cgfk7?file=%2Findex.js%3A15%2C1

[!NOTE] Check terminal

With this yaml

# A comment level1
level1:
  # A comment level2
  level2:
    # A comment level3.1
    level3.1: hello
    # A comment level3.2
    level3.2: hello

When we get('level1') the value of commentsBefore is # A comment level2, which is incorrect. Then it's the same for all levels until level3.1, this node does not have a comment and level3.2 have the correct one. Screenshot 2024-09-09 at 22 51 24

Expected behaviour commentsBefore should be assigned to the right node. Or at least it should be off by one consistently. I know the support for comment is not complete and an issue was opened/closed before regarding this. I don't think the closing was correct as the behavior is inconsistent.

Versions:

  • Environment:Node 20
  • yaml: 2.5.1

bodinsamuel avatar Sep 09 '24 20:09 bodinsamuel

The value you get from get('level1') is a mapping, which has a comment "A comment level2" before it. Which other node were you expecting the comment to be attached to?

eemeli avatar Sep 09 '24 21:09 eemeli

Maybe the wording is confusing but to me the comment before level1 is # A comment level1 And it's not consistent why level3.2 would contain the actual comment before itself while not the others

bodinsamuel avatar Sep 10 '24 07:09 bodinsamuel

The logic is that a comment with no empty lines after it gets attached to the next node.

"A comment level1" is a comment before the block mapping with a single key, level1, and so it gets attached to the mapping. With get('level1') you get the value of the level1 key-value pair, which is itself a mapping with a single key, level2, and the comment "A comment level2" is again attached to the mapping.

The comment "A comment level3.2" is also attached to the next node, the key-value pair with the key level3.2.

Perhaps your confusion is arising from comments being attachable to mappings as well as key-value pairs?

eemeli avatar Sep 10 '24 09:09 eemeli

I don't know, there is indeed something I don't understand even with the explanation. Especially why level3.1 and level3.2 would not get the same treatment. It makes the usage of those values programmatically a bit more complex than it could or hardly possible.

Anyway, feel free to discard the issue if it works as intended.

bodinsamuel avatar Sep 10 '24 12:09 bodinsamuel