Skip to content

WithSmartAnchor produces invalid YAML when the anchored value is an empty slice #853

@jmooring

Description

@jmooring

MarshalWithOptions with WithSmartAnchor() generates invalid YAML when a map contains multiple keys with empty slice values. Two problems occur:

  1. The anchor and its value are placed on separate lines, breaking the YAML structure
  2. Subsequent keys emit both an anchor definition and an alias reference on the same node (&key1 *key1), which is invalid YAML

Reproducer:

package main

import (
    "fmt"
    "log"

    yaml "github.com/goccy/go-yaml"
)

func main() {
    m := map[string]interface{}{
        "key1": []string{},
        "key2": []string{},
        "key3": []string{"item1", "item2", "item3"},
    }

    b, err := yaml.MarshalWithOptions(m, yaml.WithSmartAnchor())
    if err != nil {
        log.Fatal(err)
    }

    fmt.Print(string(b))
}

Actual output:

key1: &key1
[]
key2: &key1 *key1
key3:
- item1
- item2
- item3

Expected output:

key1: &key1 []
key2: *key1
key3:
- item1
- item2
- item3

Notes:

  1. Reproducible with v1.19.2.
  2. The issue is specific to empty slices. Non-empty slices work correctly.
  3. &key1 *key1 (defining and referencing an anchor on the same node) is invalid per the YAML 1.2 specification.

Reference: gohugoio/hugo#14596

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions