Skip to content

Commit

Permalink
Ignore unexported struct field
Browse files Browse the repository at this point in the history
There is an error when users try to compare structs that has unexported
field inside, although it's not being used. To fix the issue, I ignore
unexported fields when comparing the struct.
  • Loading branch information
haritsfahreza committed Jun 11, 2023
1 parent aaeed42 commit 23dc5ee
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
4 changes: 4 additions & 0 deletions pkg/comparator/struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ func (c *StructComparator) Compare(ctx context.Context, oldVal, newVal reflect.V
oldField := oldVal.Field(i)
newField := newVal.Field(i)

if !typeField.IsExported() {
continue
}

tag := typeField.Tag.Get("libra")
if tag == "ignore" || tag == "id" {
continue
Expand Down
28 changes: 28 additions & 0 deletions pkg/comparator/struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ type anotherPerson struct {
Name string
}

type structWithPrivateField struct {
ID int `libra:"id"`
Name string
secretName string
}

func TestStructComparator_Compare(t *testing.T) {
oldEmbeddedAddress := embeddedAddress{}
oldEmbeddedAddress.ID = 10
Expand Down Expand Up @@ -263,6 +269,28 @@ func TestStructComparator_Compare(t *testing.T) {
New: "Jalan ABC",
}},
false,
}, {
"succeed when compare struct with private field",
args{
ctx: nil,
old: structWithPrivateField{
ID: 10,
Name: "test1",
},
new: structWithPrivateField{
ID: 10,
Name: "test2",
},
},
[]diff.Diff{{
ChangeType: diff.Changed,
ObjectType: "comparator_test.structWithPrivateField",
Field: "Name",
ObjectID: "10",
Old: "test1",
New: "test2",
}},
false,
},
}
for _, tt := range tests {
Expand Down

0 comments on commit 23dc5ee

Please sign in to comment.