Skip to content

Commit

Permalink
fix: skip encoding an inline field if it is null (#386)
Browse files Browse the repository at this point in the history
  • Loading branch information
zoncoen authored Sep 13, 2023
1 parent 42fb764 commit f5c5711
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -823,6 +823,10 @@ func (e *Encoder) encodeStruct(ctx context.Context, value reflect.Value, column
}
mapNode, ok := value.(ast.MapNode)
if !ok {
// if an inline field is null, skip encoding it
if _, ok := value.(*ast.NullNode); ok {
continue
}
return nil, xerrors.Errorf("inline value is must be map or struct type")
}
mapIter := mapNode.MapRange()
Expand Down
24 changes: 24 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -980,6 +980,30 @@ c: true
}
}

func TestEncoder_InlineNil(t *testing.T) {
type base struct {
A int
B string
}
var buf bytes.Buffer
enc := yaml.NewEncoder(&buf)
if err := enc.Encode(struct {
*base `yaml:",inline"`
C bool
}{
C: true,
}); err != nil {
t.Fatalf("%+v", err)
}
expect := `
c: true
`
actual := "\n" + buf.String()
if expect != actual {
t.Fatalf("inline marshal error: expect=[%s] actual=[%s]", expect, actual)
}
}

func TestEncoder_Flow(t *testing.T) {
var buf bytes.Buffer
enc := yaml.NewEncoder(&buf, yaml.Flow(true))
Expand Down

0 comments on commit f5c5711

Please sign in to comment.