Skip to content

Commit 152acef

Browse files
denikIsaac
andcommitted
structs: share per-type struct field info
structdiff and structwalk re-parsed struct tags for every visited field, and each package kept its own copy of the field rules (flattened embeds, json:"-", EmbeddedSlice, ForceSendFields). structaccess.GetStructInfo now computes them once per type for structdiff, structwalk and structaccess. ForceSendFields now always comes from the struct that declares the field. structdiff and structwalk used to fall back to one promoted from an embedded struct; that list can only name the embedded struct's own fields (the SDK marshaller rejects other names), so it was misapplied to an outer field that shadows an embedded one. Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 35ed095 commit 152acef

8 files changed

Lines changed: 268 additions & 157 deletions

File tree

‎libs/structs/structaccess/get.go‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -327,13 +327,11 @@ func forceSendFields(owner reflect.Value) reflect.Value {
327327
if !owner.IsValid() || owner.Kind() != reflect.Struct {
328328
return reflect.Value{}
329329
}
330-
for i := range owner.Type().NumField() {
331-
field := owner.Type().Field(i)
332-
if field.Name == "ForceSendFields" && !field.Anonymous {
333-
return owner.Field(i)
334-
}
330+
index := GetStructInfo(owner.Type()).ForceSendFieldsIndex
331+
if index < 0 {
332+
return reflect.Value{}
335333
}
336-
return reflect.Value{}
334+
return owner.Field(index)
337335
}
338336

339337
// forceSendFieldsContains reports whether a struct forces the named field to be sent.
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package structaccess
2+
3+
import (
4+
"reflect"
5+
"sync"
6+
7+
"github.com/databricks/cli/libs/structs/structtag"
8+
)
9+
10+
const forceSendFieldsName = "ForceSendFields"
11+
12+
// Field describes one struct field the way encoding/json and the structs packages see it.
13+
type Field struct {
14+
// Index is the field's index for reflect.Value.Field.
15+
Index int
16+
17+
StructField reflect.StructField
18+
19+
// Name is the JSON key: the json tag name, or the Go field name when the tag has none.
20+
Name string
21+
22+
OmitEmpty bool
23+
24+
// Flattened marks an anonymous struct that encoding/json promotes into the parent, so its
25+
// fields appear at the parent's path. An anonymous field carrying a json name is not one of
26+
// these: encoding/json serializes it as a nested object, so it is a named field.
27+
Flattened bool
28+
29+
// EmbeddedSlice marks the EmbeddedSliceFieldName field, whose elements appear at the parent's path.
30+
EmbeddedSlice bool
31+
}
32+
33+
// StructInfo is the per-type view of a struct's fields, computed once per type.
34+
type StructInfo struct {
35+
// Fields lists the exported fields in declaration order, except ForceSendFields and
36+
// fields tagged exactly `json:"-"`.
37+
Fields []Field
38+
39+
// ForceSendFieldsIndex is the index of the ForceSendFields []string the struct declares
40+
// itself, or -1. A ForceSendFields promoted from an embedded struct only governs that
41+
// struct's fields: the SDK marshaller rejects names of fields its struct does not have.
42+
ForceSendFieldsIndex int
43+
}
44+
45+
// Keyed by reflect.Type; struct walkers visit the same types many times.
46+
var structInfoCache sync.Map
47+
48+
// GetStructInfo returns the StructInfo of struct type t.
49+
func GetStructInfo(t reflect.Type) *StructInfo {
50+
if cached, ok := structInfoCache.Load(t); ok {
51+
return cached.(*StructInfo)
52+
}
53+
info := newStructInfo(t)
54+
structInfoCache.Store(t, info)
55+
return info
56+
}
57+
58+
func newStructInfo(t reflect.Type) *StructInfo {
59+
info := &StructInfo{ForceSendFieldsIndex: -1}
60+
for i := range t.NumField() {
61+
sf := t.Field(i)
62+
if sf.Name == forceSendFieldsName {
63+
if !sf.Anonymous && sf.Type == reflect.TypeFor[[]string]() {
64+
info.ForceSendFieldsIndex = i
65+
}
66+
continue
67+
}
68+
if !sf.IsExported() {
69+
continue
70+
}
71+
if IsFlattenedEmbed(sf) {
72+
info.Fields = append(info.Fields, Field{Index: i, StructField: sf, Flattened: true})
73+
continue
74+
}
75+
if IsSkippedField(sf) {
76+
continue
77+
}
78+
79+
jsonTag := structtag.JSONTag(sf.Tag.Get("json"))
80+
name := jsonTag.Name()
81+
if name == "" {
82+
name = sf.Name
83+
}
84+
info.Fields = append(info.Fields, Field{
85+
Index: i,
86+
StructField: sf,
87+
Name: name,
88+
OmitEmpty: jsonTag.OmitEmpty(),
89+
EmbeddedSlice: sf.Name == EmbeddedSliceFieldName,
90+
})
91+
}
92+
return info
93+
}
94+
95+
// ForceSendFields returns the ForceSendFields that struct v declares itself, or nil.
96+
func (info *StructInfo) ForceSendFields(v reflect.Value) []string {
97+
if info.ForceSendFieldsIndex < 0 {
98+
return nil
99+
}
100+
result, _ := reflect.TypeAssert[[]string](v.Field(info.ForceSendFieldsIndex))
101+
return result
102+
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package structaccess
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
type InfoInner struct {
11+
A string `json:"a,omitempty"`
12+
ForceSendFields []string `json:"-"`
13+
}
14+
15+
type InfoTagged struct {
16+
B string `json:"b"`
17+
}
18+
19+
type infoOuter struct {
20+
InfoInner
21+
InfoTagged `json:"tagged"`
22+
Named string `json:"named,omitempty"`
23+
NoTag int
24+
Skipped string `json:"-"`
25+
Dash string `json:"-,omitempty"` //nolint:staticcheck // the field is named "-"
26+
EmbeddedSlice []string `json:"items"`
27+
unexported string //nolint:unused
28+
ForceSendFields []string `json:"-"`
29+
}
30+
31+
type infoPromoted struct {
32+
InfoInner
33+
Own string `json:"own,omitempty"`
34+
}
35+
36+
func TestGetStructInfo(t *testing.T) {
37+
info := GetStructInfo(reflect.TypeFor[infoOuter]())
38+
39+
type summary struct {
40+
Index int
41+
Name string
42+
OmitEmpty bool
43+
Flattened bool
44+
EmbeddedSlice bool
45+
}
46+
var got []summary
47+
for _, f := range info.Fields {
48+
got = append(got, summary{f.Index, f.Name, f.OmitEmpty, f.Flattened, f.EmbeddedSlice})
49+
}
50+
assert.Equal(t, []summary{
51+
{Index: 0, Flattened: true},
52+
{Index: 1, Name: "tagged"},
53+
{Index: 2, Name: "named", OmitEmpty: true},
54+
{Index: 3, Name: "NoTag"},
55+
{Index: 5, Name: "-", OmitEmpty: true},
56+
{Index: 6, Name: "items", EmbeddedSlice: true},
57+
}, got)
58+
assert.Equal(t, 8, info.ForceSendFieldsIndex)
59+
60+
v := reflect.ValueOf(infoOuter{ForceSendFields: []string{"Named"}})
61+
assert.Equal(t, []string{"Named"}, info.ForceSendFields(v))
62+
63+
assert.Same(t, info, GetStructInfo(reflect.TypeFor[infoOuter]()))
64+
}
65+
66+
// A ForceSendFields promoted from an embedded struct governs only that struct's fields.
67+
func TestGetStructInfoPromotedForceSendFields(t *testing.T) {
68+
info := GetStructInfo(reflect.TypeFor[infoPromoted]())
69+
assert.Equal(t, -1, info.ForceSendFieldsIndex)
70+
71+
v := reflect.ValueOf(infoPromoted{ForceSendFields: []string{"Own"}})
72+
assert.Nil(t, info.ForceSendFields(v))
73+
}

‎libs/structs/structdiff/diff.go‎

Lines changed: 18 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import (
99

1010
"github.com/databricks/cli/libs/structs/structaccess"
1111
"github.com/databricks/cli/libs/structs/structpath"
12-
"github.com/databricks/cli/libs/structs/structtag"
1312
)
1413

1514
type Change struct {
@@ -218,69 +217,35 @@ func equalLeaf(v1, v2 reflect.Value) bool {
218217
}
219218

220219
func diffStruct(ctx *diffContext, path *structpath.PathNode, s1, s2 reflect.Value, changes *[]Change) error {
221-
t := s1.Type()
222-
forced1 := getForceSendFields(s1)
223-
forced2 := getForceSendFields(s2)
220+
info := structaccess.GetStructInfo(s1.Type())
221+
forced1 := info.ForceSendFields(s1)
222+
forced2 := info.ForceSendFields(s2)
224223

225-
for i := range t.NumField() {
226-
sf := t.Field(i)
227-
if !sf.IsExported() || sf.Name == "ForceSendFields" {
228-
continue
229-
}
224+
for _, f := range info.Fields {
225+
v1Field := s1.Field(f.Index)
226+
v2Field := s2.Field(f.Index)
230227

231-
// Continue traversing embedded structs. Do not add the key to the path though. An
232-
// anonymous field carrying a json name is not one of these: encoding/json serializes it
233-
// as a nested object, so it is handled as a named field below.
234-
if structaccess.IsFlattenedEmbed(sf) {
235-
if err := diffValues(ctx, path, s1.Field(i), s2.Field(i), changes); err != nil {
228+
// Continue traversing embedded structs. Do not add the key to the path though.
229+
if f.Flattened {
230+
if err := diffValues(ctx, path, v1Field, v2Field, changes); err != nil {
236231
return err
237232
}
238233
continue
239234
}
240235

241-
// Only the exact tag json:"-" skips a field; json:"-," names it "-".
242-
if structaccess.IsSkippedField(sf) {
243-
continue
244-
}
245-
246-
jsonTag := structtag.JSONTag(sf.Tag.Get("json"))
247-
248-
// Resolve field name from JSON tag or fall back to Go field name
249-
fieldName := jsonTag.Name()
250-
251-
isEmbed := sf.Name == structaccess.EmbeddedSliceFieldName
252-
253-
if fieldName == "" || isEmbed {
254-
fieldName = sf.Name
255-
}
256-
257-
v1Field := s1.Field(i)
258-
v2Field := s2.Field(i)
259-
260-
zero1 := v1Field.IsZero()
261-
zero2 := v2Field.IsZero()
262-
263-
if zero1 || zero2 {
264-
if jsonTag.OmitEmpty() {
265-
if zero1 {
266-
if !slices.Contains(forced1, sf.Name) {
267-
v1Field = reflect.ValueOf(nil)
268-
}
269-
}
270-
if zero2 {
271-
if !slices.Contains(forced2, sf.Name) {
272-
v2Field = reflect.ValueOf(nil)
273-
}
274-
}
236+
if f.OmitEmpty {
237+
if v1Field.IsZero() && !slices.Contains(forced1, f.StructField.Name) {
238+
v1Field = reflect.ValueOf(nil)
239+
}
240+
if v2Field.IsZero() && !slices.Contains(forced2, f.StructField.Name) {
241+
v2Field = reflect.ValueOf(nil)
275242
}
276243
}
277244

278245
// EmbeddedSlice: diff at parent path level without adding field name.
279-
var node *structpath.PathNode
280-
if isEmbed {
281-
node = path
282-
} else {
283-
node = structpath.NewDotString(path, fieldName)
246+
node := path
247+
if !f.EmbeddedSlice {
248+
node = structpath.NewDotString(path, f.Name)
284249
}
285250

286251
if err := diffValues(ctx, node, v1Field, v2Field, changes); err != nil {
@@ -352,21 +317,6 @@ func diffStringMaps(path *structpath.PathNode, m1, m2 map[string]string, changes
352317
}
353318
}
354319

355-
func getForceSendFields(v reflect.Value) []string {
356-
if !v.IsValid() || v.Kind() != reflect.Struct {
357-
return nil
358-
}
359-
fsField := v.FieldByName("ForceSendFields")
360-
if !fsField.IsValid() || fsField.Kind() != reflect.Slice {
361-
return nil
362-
}
363-
result, ok := reflect.TypeAssert[[]string](fsField)
364-
if ok {
365-
return result
366-
}
367-
return nil
368-
}
369-
370320
// findKeyFunc returns the KeyFunc for the given path, or nil if none matches.
371321
// Path patterns support [*] to match any slice index.
372322
func (ctx *diffContext) findKeyFunc(path *structpath.PathNode) KeyFunc {

‎libs/structs/structdiff/diff_test.go‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1125,3 +1125,31 @@ func TestGetStructDiffPathsSharingPrefix(t *testing.T) {
11251125
assert.Equal(t, Change{Path: changes[2].Path, Old: nil, New: "2"}, changes[2])
11261126
assert.Equal(t, Change{Path: changes[3].Path, Old: "1", New: nil}, changes[3])
11271127
}
1128+
1129+
type PromotedInner struct {
1130+
A string `json:"a,omitempty"`
1131+
ForceSendFields []string `json:"-"`
1132+
}
1133+
1134+
type promotedOuter struct {
1135+
PromotedInner
1136+
Own string `json:"own,omitempty"`
1137+
}
1138+
1139+
// The embedded struct's ForceSendFields does not force the outer struct's own fields;
1140+
// the SDK marshaller would reject a name its struct does not have.
1141+
func TestGetStructDiffEmbeddedForceSendFieldsDoNotApplyToOuterFields(t *testing.T) {
1142+
forced := promotedOuter{ForceSendFields: []string{"A", "Own"}}
1143+
plain := promotedOuter{}
1144+
1145+
changes, err := GetStructDiff(forced, plain, nil)
1146+
require.NoError(t, err)
1147+
assert.Equal(t, []ResolvedChange{{Field: "a", Old: "", New: nil}}, resolveChanges(changes))
1148+
assert.False(t, IsEqual(forced, plain))
1149+
1150+
forced.ForceSendFields = []string{"Own"}
1151+
changes, err = GetStructDiff(forced, plain, nil)
1152+
require.NoError(t, err)
1153+
assert.Empty(t, changes)
1154+
assert.True(t, IsEqual(forced, plain))
1155+
}

0 commit comments

Comments
 (0)