Skip to content

Commit

Permalink
fix encoding of anchor and alias
Browse files Browse the repository at this point in the history
  • Loading branch information
goccy committed Dec 22, 2024
1 parent beec790 commit a47e834
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 5 deletions.
15 changes: 10 additions & 5 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -787,12 +787,11 @@ func (e *Encoder) encodeStruct(ctx context.Context, value reflect.Value, column
}
var key ast.MapKeyNode = e.encodeString(structField.RenderName, column)
switch {
case structField.AnchorName != "":
anchorNode, err := e.encodeAnchor(structField.AnchorName, value, fieldValue, column)
if err != nil {
return nil, err
case value.Type() == ast.AliasType:
if structField.IsInline {
// if both used alias and inline, output `<<: *alias`
key = ast.MergeKey(token.New("<<", "<<", e.pos(column)))
}
value = anchorNode
case structField.IsAutoAlias:
if fieldValue.Kind() != reflect.Ptr {
return nil, fmt.Errorf(
Expand All @@ -814,6 +813,12 @@ func (e *Encoder) encodeStruct(ctx context.Context, value reflect.Value, column
// if both used alias and inline, output `<<: *alias`
key = ast.MergeKey(token.New("<<", "<<", e.pos(column)))
}
case structField.AnchorName != "":
anchorNode, err := e.encodeAnchor(structField.AnchorName, value, fieldValue, column)
if err != nil {
return nil, err
}
value = anchorNode
case structField.AliasName != "":
aliasName := structField.AliasName
alias := ast.Alias(token.New("*", "*", e.pos(column)))
Expand Down
42 changes: 42 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1675,3 +1675,45 @@ func TestIssue174(t *testing.T) {
t.Fatalf("failed to encode: %q", got)
}
}

func TestIssue259(t *testing.T) {
type AnchorValue struct {
Foo uint64
Bar string
}

type Value struct {
Baz string `yaml:"baz"`
Value *AnchorValue `yaml:"value,anchor"`
}

type Schema struct {
Values []*Value
}

schema := Schema{}
anchorValue := AnchorValue{Foo: 3, Bar: "bar"}
schema.Values = []*Value{
{Baz: "xxx", Value: &anchorValue},
{Baz: "yyy", Value: &anchorValue},
{Baz: "zzz", Value: &anchorValue},
}
b, err := yaml.Marshal(schema)
if err != nil {
t.Fatal(err)
}
expected := `
values:
- baz: xxx
value: &value
foo: 3
bar: bar
- baz: yyy
value: *value
- baz: zzz
value: *value
`
if strings.TrimPrefix(expected, "\n") != string(b) {
t.Fatalf("failed to encode: got = %s", string(b))
}
}

0 comments on commit a47e834

Please sign in to comment.