go-yaml / yaml

YAML support for the Go language.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Comments rendering issue related to array nodes

qjebbs opened this issue · comments

For a array field, we have a key node and a value node, for cases below, the comments set for slice node goes to the num node:

  1. When the array is rendered inline (sure for an empty array), we set the key.LineComment, it is rendered at the wrong place:

    func Example_wrongComment() {
    	raw := `
    slice: [1]
    num: 1`
    	var d yaml.Node
    	err := yaml.Unmarshal([]byte(raw), &d)
    	if err != nil {
    		panic(err)
    	}
    	key := d.Content[0].Content[0]
    	if key.Value != "slice" {
    		panic("wrong node")
    	}
    	// Recurrence conditions:
    	// 1. slice is inlined
    	// 2. set key.LineComment
    	key.LineComment = "slice comment"
    	bs, err := yaml.Marshal(&d)
    	if err != nil {
    		panic(err)
    	}
    	fmt.Println(string(bs))
    	// Output:
    	// slice: [1]
    	// num: 1 # slice comment
    }
  2. When the array is rendered in block style, we set the value.LineComment, it is rendered at the wrong place:

    func Example_wrongComment2() {
    	raw := `
    slice:
        - a
    num: 1`
    	var d yaml.Node
    	err := yaml.Unmarshal([]byte(raw), &d)
    	if err != nil {
    		panic(err)
    	}
    	key := d.Content[0].Content[0]
    	value := d.Content[0].Content[1]
    	if key.Value != "slice" {
    		panic("wrong node")
    	}
    	// Recurrence conditions:
    	// 1. slice is not inlined
    	// 2. set value.LineComment
    	value.LineComment = "slice comment"
    	bs, err := yaml.Marshal(&d)
    	if err != nil {
    		panic(err)
    	}
    	fmt.Println(string(bs))
    	// Output:
    	// slice:
    	//     - a
    	// num: 1 # slice comment
    }

A workaround for this issue is (similar like what happens in yaml.Unmarshal()):

func(key, value *yaml.Node) error {
	if len(values) == 0 {
		value.LineComment = "comment"
	} else {
		key.LineComment = "comment"
	}
	return nil
}

It seems that a non-empty array is always rendered in block style in my case. The workaround doesn't work when the array is rendered like a: [1,2,3], and I don't know when it happens.