From d1289593a820f913c8b9da37912b119e167bcef8 Mon Sep 17 00:00:00 2001 From: Taichi Shigematsu <65220900+shigetaichi@users.noreply.github.com> Date: Tue, 17 Oct 2023 11:56:44 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20prevent=20the=20error=20occurs=20when=20?= =?UTF-8?q?omitempty=20is=20present=20in=20a=20field=20of=E2=80=A6=20(#21)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: prevent the error occurs when omitempty is present in a field of an embedded pointer type structure https://github.com/shigetaichi/xsv/issues/20 * test: Creating a test when the embedded struct is a pointer type and all its fields have omitempty --- decode_test.go | 20 ++++++++++++++++++++ sample_structs_test.go | 14 ++++++++++++++ types.go | 8 +++++--- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/decode_test.go b/decode_test.go index bd63c2e..573a006 100644 --- a/decode_test.go +++ b/decode_test.go @@ -223,6 +223,26 @@ ff,gg,22,hh,ii,jj`) } } +func Test_readTo_embed_ptr_all_omitempty(t *testing.T) { + b := bytes.NewBufferString(`first,last,abc,Omit +aa,dd,ee,`) + + var rows []EmbedPtrAllOmitemptySample + if err := NewXsvRead[EmbedPtrAllOmitemptySample]().SetReader(csv.NewReader(b)).ReadTo(&rows); err != nil { + t.Fatalf(err.Error()) + } + expected := EmbedPtrAllOmitemptySample{ + Qux: "aa", + AllOmitEmpty: &AllOmitEmpty{ + Omit: nil, + }, + Quux: "dd", + } + if !reflect.DeepEqual(expected, rows[0]) { + t.Fatalf("expected first sample %v, got %+v", expected, rows[0]) + } +} + func Test_readTo_slice(t *testing.T) { b := bytes.NewBufferString(`Slice [] diff --git a/sample_structs_test.go b/sample_structs_test.go index 6e12878..4a89164 100644 --- a/sample_structs_test.go +++ b/sample_structs_test.go @@ -15,6 +15,12 @@ type Sample struct { Omit *string `csv:"Omit,omitempty"` } +type AllOmitEmpty struct { + Omit *string `csv:"Omit,omitempty"` + Omit2 *string `csv:"Omit2,omitempty"` + Omit3 *string `csv:"Omit3,omitempty"` +} + type SliceSample struct { Slice []int `csv:"Slice"` } @@ -101,6 +107,14 @@ type EmbedPtrSample struct { Quux string `csv:"last"` } +type EmbedPtrAllOmitemptySample struct { + Qux string `csv:"first"` + *AllOmitEmpty + Ignore string `csv:"-"` + Grault float64 `csv:"garply"` + Quux string `csv:"last"` +} + type SkipFieldSample struct { EmbedSample MoreIgnore string `csv:"-"` diff --git a/types.go b/types.go index 432c88c..53f5109 100644 --- a/types.go +++ b/types.go @@ -217,10 +217,12 @@ func toFloat(in interface{}) (float64, error) { func setField(field reflect.Value, value string, omitEmpty bool) error { if field.Kind() == reflect.Ptr { - if omitEmpty && value == "" { - return nil - } if field.IsNil() { + if omitEmpty && value == "" { + if field.Type().Elem().Kind() != reflect.Struct { + return nil + } + } field.Set(reflect.New(field.Type().Elem())) } field = field.Elem()