Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: skip encoding an inline field if it is null #386

Merged
merged 1 commit into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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