Skip to content

Commit

Permalink
fix: skip encoding an inline field if it is null
Browse files Browse the repository at this point in the history
  • Loading branch information
zoncoen committed Sep 13, 2023
1 parent 42fb764 commit 137dbf9
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 9 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
47 changes: 38 additions & 9 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ import (
"github.com/goccy/go-yaml/ast"
)

var zero = 0
var emptyStr = ""
var (
zero = 0
emptyStr = ""
)

func TestEncoder(t *testing.T) {
tests := []struct {
Expand Down Expand Up @@ -643,12 +645,12 @@ func TestEncoder(t *testing.T) {
// time value
{
"v: 0001-01-01T00:00:00Z\n",
map[string]time.Time{"v": time.Time{}},
map[string]time.Time{"v": {}},
nil,
},
{
"v: 0001-01-01T00:00:00Z\n",
map[string]*time.Time{"v": &time.Time{}},
map[string]*time.Time{"v": {}},
nil,
},
{
Expand Down Expand Up @@ -980,6 +982,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 Expand Up @@ -1014,7 +1040,7 @@ func TestEncoder_FlowRecursive(t *testing.T) {
M map[string][]int `yaml:",flow"`
}
v.M = map[string][]int{
"test": []int{1, 2, 3},
"test": {1, 2, 3},
}
var buf bytes.Buffer
if err := yaml.NewEncoder(&buf).Encode(v); err != nil {
Expand Down Expand Up @@ -1311,6 +1337,7 @@ func (t *tMarshal) MarshalYAML() ([]byte, error) {
}
return buf.Bytes(), nil
}

func Test_Marshaler(t *testing.T) {
const expected = `- hello-world
`
Expand Down Expand Up @@ -1365,10 +1392,12 @@ type FastMarshaler struct {
A string
B int
}
type TextMarshaler int64
type TextMarshalerContainer struct {
Field TextMarshaler `yaml:"field"`
}
type (
TextMarshaler int64
TextMarshalerContainer struct {
Field TextMarshaler `yaml:"field"`
}
)

func (v SlowMarshaler) MarshalYAML() ([]byte, error) {
var buf bytes.Buffer
Expand Down

0 comments on commit 137dbf9

Please sign in to comment.