From f5c5711fc651e07be20a7567038255620d66f063 Mon Sep 17 00:00:00 2001 From: Kenta Mori Date: Wed, 13 Sep 2023 17:17:47 +0900 Subject: [PATCH] fix: skip encoding an inline field if it is null (#386) --- encode.go | 4 ++++ encode_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/encode.go b/encode.go index 7d8d81e..3b9b298 100644 --- a/encode.go +++ b/encode.go @@ -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() diff --git a/encode_test.go b/encode_test.go index 74b1aa5..e872c61 100644 --- a/encode_test.go +++ b/encode_test.go @@ -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))