Skip to content

Commit 53d4007

Browse files
committed
diff: ignore kind and apiVersion when diffing
1 parent 3280848 commit 53d4007

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

pkg/util/diff.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package util
1818
import (
1919
"errors"
2020
"fmt"
21+
"reflect"
2122
"sort"
2223
"strings"
2324

@@ -129,6 +130,10 @@ func (d *differ) Diff(a, b client.Object) (DiffResult, error) {
129130
return nil, errObjectsToCompareCannotBeNil
130131
}
131132

133+
if reflect.TypeOf(a) != reflect.TypeOf(b) {
134+
return nil, fmt.Errorf("objects to diff are not of the same type: %T != %T", a, b)
135+
}
136+
132137
// 1. Convert the objects to unstructured.
133138
unstructuredA, err := runtime.DefaultUnstructuredConverter.ToUnstructured(a)
134139
if err != nil {
@@ -196,6 +201,10 @@ func (d *differ) Diff(a, b client.Object) (DiffResult, error) {
196201
// NewDefaultDiffer creates a new default differ with the default options.
197202
func NewDefaultDiffer(opts ...diffopts) *differ {
198203
return newDiffer(append(opts,
204+
// Always ignore kind and apiVersion as they may not be always set. Instead the differ checks if the input objects have the same type.
205+
WithIgnoreField("kind"),
206+
WithIgnoreField("apiVersion"),
207+
199208
// Options for handling of metadata fields.
200209

201210
// Special handling for Cluster API's conversion-data label.

pkg/util/diff_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,22 @@ package util
1818
import (
1919
. "github.com/onsi/ginkgo/v2"
2020
. "github.com/onsi/gomega"
21+
mapiv1beta1 "github.com/openshift/api/machine/v1beta1"
2122
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
2223
)
2324

2425
var _ = Describe("Unit test Diff", func() {
2526

27+
Describe("error cases", func() {
28+
It("should return an error if the objects are not of the same type", func() {
29+
a := &mapiv1beta1.MachineSet{}
30+
b := &mapiv1beta1.Machine{}
31+
_, err := NewDefaultDiffer().Diff(a, b)
32+
Expect(err).To(HaveOccurred())
33+
Expect(err).To(MatchError(ContainSubstring("objects to diff are not of the same type")))
34+
})
35+
})
36+
2637
type testInput struct {
2738
a unstructured.Unstructured
2839
b unstructured.Unstructured

0 commit comments

Comments
 (0)