go-yaml / yaml

YAML support for the Go language.
Other
6.84k stars 1.04k forks source link

v3: Head comment confused with foot comment #695

Open mruzicka opened 3 years ago

mruzicka commented 3 years ago

The following YAML document:

spec:
    resources:
        # need more cpu upon initialization, therefore burstable class
        requests:
            cpu: 100m
            memory: 32Mi
        limits:
            cpu: 500m
            memory: 128Mi

when decoded into a yaml.Node & then encoded again on linux while the input document uses Windows line breaks results in the following output:

spec:
    resources:
        requests:
            cpu: 100m
            memory: 32Mi
        # need more cpu upon initialization, therefore burstable class

        limits:
            cpu: 500m
            memory: 128Mi

Please note the misplaced comment on the spec.resources.requests attribute.

Additional info

tempoz commented 2 years ago

This may further illuminate the issue: https://go.dev/play/p/-129ko9r4-A image As can be seen, head comments for the value Node of a pair of key-value Nodes in a mapping Node are (I believe, incorrectly) placed below the foot comments.

I am not honestly sure why the key comments are used at all, as I would expect given the Unmarshaler interface:

type Unmarshaler interface {
    UnmarshalYAML(value *[Node](https://pkg.go.dev/gopkg.in/yaml.v3#Node)) [error](https://pkg.go.dev/builtin#error)
}

that the comments on a value should be able to be fully controlled from the value Node, given that that is the only Node one has access to while in the UnmarshalYAML function. Furthermore, when parsing, it is not clear to me how one could distinguish between a key head comment and a value head comment (or, incidentally, a key foot comment and a value foot comment), which I think is why we see the behavior described in the original bug description: A comment is read in as a value head comment, and then output as a value head comment, which are currently being output as the last comment, below both foot comments, whereas in slightly different circumstances, it instead is read in as a key head comment, and output as a key head comment, which places it at the top of all comments.

GavinZhang80 commented 1 year ago

HeadComment is not implemented, cannot be parsed, and cannot be generated.