Skip to content

Commit 9ed6196

Browse files
denikIsaac
andcommitted
structcopy: extract the generic copier into libs/structs/structcopy
Move the reflection copier (compile-time type check, field/JSON-name copy, ForceSendFields filtering, lossless conversions) out of dresources into a reusable package beside structwalk/structdiff/structaccess. The direct engine wiring (buildCopiers, driven off SupportedResources) stays in dresources and now calls structcopy.Compile. Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 8c4b98f commit 9ed6196

5 files changed

Lines changed: 171 additions & 159 deletions

File tree

‎bundle/direct/dresources/adapter.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88

99
"github.com/databricks/cli/bundle/deployplan"
1010
"github.com/databricks/cli/libs/calladapt"
11+
"github.com/databricks/cli/libs/structs/structcopy"
1112
"github.com/databricks/cli/libs/structs/structpath"
1213
"github.com/databricks/cli/libs/structs/structvar"
1314
"github.com/databricks/databricks-sdk-go"
@@ -130,7 +131,7 @@ type Adapter struct {
130131
doCreate *calladapt.BoundCaller
131132

132133
// Optional:
133-
copier *copier
134+
copier *structcopy.Copier
134135
doDelete *calladapt.BoundCaller
135136
prepareInputConfig *calladapt.BoundCaller
136137
isEmptyState *calladapt.BoundCaller
@@ -532,7 +533,7 @@ func (a *Adapter) RemapState(remoteState any) (any, error) {
532533
return outs[0], nil
533534
}
534535
if a.copier != nil {
535-
return a.copier.copy(remoteState), nil
536+
return a.copier.Copy(remoteState), nil
536537
}
537538
// No custom method and no copier: validate() only allows this when
538539
// remoteType == stateType, so the remote is already the state type.

‎bundle/direct/dresources/all.go‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"strings"
88

99
"github.com/databricks/cli/libs/calladapt"
10+
"github.com/databricks/cli/libs/structs/structcopy"
1011
"github.com/databricks/databricks-sdk-go"
1112
)
1213

@@ -93,9 +94,9 @@ var SupportedResources = map[string]any{
9394
// RemapState method and are skipped here.
9495
var copiers = buildCopiers()
9596

96-
func buildCopiers() map[reflect.Type]*copier {
97+
func buildCopiers() map[reflect.Type]*structcopy.Copier {
9798
iface := reflect.TypeFor[IResource]()
98-
out := make(map[reflect.Type]*copier)
99+
out := make(map[reflect.Type]*structcopy.Copier)
99100
var errs []string
100101

101102
for resourceType, resource := range SupportedResources {
@@ -130,9 +131,9 @@ func buildCopiers() map[reflect.Type]*copier {
130131
continue // identity: the adapter returns the remote unchanged, no copier needed
131132
}
132133

133-
copier, err := compileCopier(remoteType, stateType)
134+
copier, err := structcopy.Compile(remoteType, stateType)
134135
if err != nil {
135-
errs = append(errs, fmt.Sprintf("%s: %v", resourceType, err))
136+
errs = append(errs, fmt.Sprintf("%s: %v (implement RemapState for this resource)", resourceType, err))
136137
continue
137138
}
138139
out[implType] = copier

‎bundle/direct/dresources/copier_test.go‎

Lines changed: 3 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import (
55
"slices"
66
"testing"
77

8+
"github.com/databricks/cli/libs/structs/structcopy"
89
"github.com/stretchr/testify/assert"
9-
"github.com/stretchr/testify/require"
1010
)
1111

1212
// TestNoRedundantRemapState enforces the "only override when needed" rule: a resource that
@@ -35,7 +35,7 @@ func TestNoRedundantRemapState(t *testing.T) {
3535
continue // identity, the copier is not involved
3636
}
3737

38-
copier, err := compileCopier(remoteType, stateType)
38+
copier, err := structcopy.Compile(remoteType, stateType)
3939
if err != nil {
4040
continue // copier cannot handle it, so the override is required
4141
}
@@ -45,7 +45,7 @@ func TestNoRedundantRemapState(t *testing.T) {
4545
setForceSendFields(remote.Elem())
4646

4747
want := m.Call([]reflect.Value{remote})[0].Interface()
48-
got := copier.copy(remote.Interface())
48+
got := copier.Copy(remote.Interface())
4949
if reflect.DeepEqual(want, got) {
5050
redundant = append(redundant, resourceType)
5151
}
@@ -55,101 +55,6 @@ func TestNoRedundantRemapState(t *testing.T) {
5555
assert.Empty(t, redundant, "these resources have a RemapState the auto-copier reproduces exactly; delete the method and let buildCopiers handle it")
5656
}
5757

58-
type copierKindA string
59-
60-
type copierKindB string
61-
62-
type copierRemote struct {
63-
Name string `json:"name"`
64-
Extra string `json:"extra"` // absent from state -> dropped
65-
Kind copierKindA `json:"kind"` // same underlying type as state, distinct name -> converted
66-
ForceSendFields []string
67-
}
68-
69-
type copierState struct {
70-
Name string `json:"name"`
71-
Missing string `json:"missing"` // absent from remote -> left zero
72-
Kind copierKindB `json:"kind"`
73-
ForceSendFields []string
74-
}
75-
76-
func TestRemapCopierCopy(t *testing.T) {
77-
copier, err := compileCopier(reflect.TypeFor[*copierRemote](), reflect.TypeFor[*copierState]())
78-
require.NoError(t, err)
79-
80-
remote := &copierRemote{
81-
Name: "n",
82-
Extra: "e",
83-
Kind: "classic",
84-
ForceSendFields: []string{"Name", "Extra", "Kind"},
85-
}
86-
got := copier.copy(remote).(*copierState)
87-
88-
assert.Equal(t, "n", got.Name)
89-
assert.Empty(t, got.Missing) // absent from remote
90-
assert.Equal(t, copierKindB("classic"), got.Kind) // converted across enum types
91-
assert.Equal(t, []string{"Name", "Kind"}, got.ForceSendFields) // "Extra" filtered out (not a state field)
92-
}
93-
94-
type copierUnsafeRemote struct {
95-
N int `json:"n"`
96-
}
97-
98-
type copierUnsafeState struct {
99-
N string `json:"n"`
100-
}
101-
102-
func TestRemapCopierCompileRejectsUnsafe(t *testing.T) {
103-
_, err := compileCopier(reflect.TypeFor[*copierUnsafeRemote](), reflect.TypeFor[*copierUnsafeState]())
104-
require.Error(t, err)
105-
assert.Contains(t, err.Error(), "implement RemapState")
106-
}
107-
108-
func TestSafeConvert(t *testing.T) {
109-
tests := []struct {
110-
name string
111-
dst reflect.Type
112-
src reflect.Type
113-
want bool
114-
}{
115-
{
116-
name: "identical",
117-
dst: reflect.TypeFor[string](),
118-
src: reflect.TypeFor[string](),
119-
want: true,
120-
},
121-
{
122-
name: "same underlying string enums",
123-
dst: reflect.TypeFor[copierKindA](),
124-
src: reflect.TypeFor[copierKindB](),
125-
want: true,
126-
},
127-
{
128-
name: "int to string",
129-
dst: reflect.TypeFor[string](),
130-
src: reflect.TypeFor[int](),
131-
want: false,
132-
},
133-
{
134-
name: "int64 to int32",
135-
dst: reflect.TypeFor[int32](),
136-
src: reflect.TypeFor[int64](),
137-
want: false,
138-
},
139-
{
140-
name: "bytes to string",
141-
dst: reflect.TypeFor[string](),
142-
src: reflect.TypeFor[[]byte](),
143-
want: false,
144-
},
145-
}
146-
for _, tt := range tests {
147-
t.Run(tt.name, func(t *testing.T) {
148-
assert.Equal(t, tt.want, safeConvert(tt.dst, tt.src))
149-
})
150-
}
151-
}
152-
15358
// setForceSendFields recursively sets every struct's ForceSendFields to its own field names,
15459
// so the copier's ForceSendFields-filtering path is exercised at every level. fillNonZero
15560
// deliberately leaves ForceSendFields empty (round-trip tests need that), so we populate it
Lines changed: 56 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
package dresources
1+
// Package structcopy compiles a reflection-based copier between two struct types.
2+
// The copier moves fields that match by JSON name, filters ForceSendFields to the
3+
// destination type, and applies only lossless conversions. The plan is compiled once
4+
// from the two types (see Compile); executing it on any values of those types cannot fail.
5+
//
6+
// It underpins the direct engine's automatic RemapState (bundle/direct/dresources): when a
7+
// resource's state type is a plain subset of its remote type, no hand-written copy is needed.
8+
package structcopy
29

310
import (
411
"fmt"
@@ -10,28 +17,21 @@ import (
1017
"github.com/databricks/cli/libs/utils"
1118
)
1219

13-
// copier is a reflection-built RemapState: it copies fields from a remote
14-
// struct into a fresh state struct by matching JSON field names. It replaces the
15-
// hand-written "dumb copy" RemapState methods (see README.md) for resources whose
16-
// state type is a plain subset of the remote type.
17-
//
18-
// The plan is compiled once from the two types (see compileCopier); executing it
19-
// on any pair of values of those types cannot fail. Anything the plan cannot copy
20-
// safely is rejected at compile time, so a resource that needs real logic surfaces
21-
// as a build/init error rather than a silent drift bug — see buildCopiers.
22-
type copier struct {
23-
stateElem reflect.Type // struct type behind *StateType
24-
ops []copyOp
20+
// Copier copies fields from a source struct into a fresh destination struct by matching
21+
// JSON field names. Build one with Compile; the compiled plan cannot fail at Copy time.
22+
type Copier struct {
23+
dstElem reflect.Type // struct type behind the destination pointer type
24+
ops []copyOp
2525
}
2626

2727
type copyOp struct {
2828
// forceSendFields ops recompute a ForceSendFields slice; field-copy ops move one field.
2929
forceSendFields bool
3030

31-
dstIndex []int // FieldByIndex path in the state struct
31+
dstIndex []int // FieldByIndex path in the destination struct
3232

3333
// field-copy ops:
34-
srcIndex []int // FieldByIndex path in the remote struct
34+
srcIndex []int // FieldByIndex path in the source struct
3535
convert bool // use reflect.Convert (distinct but same-underlying types) instead of a direct set
3636
dstType reflect.Type // target type for Convert
3737

@@ -53,22 +53,22 @@ type forceSendTarget struct {
5353
ownerType reflect.Type
5454
}
5555

56-
// compileCopier builds the copy plan for remoteType -> stateType (both pointers to
57-
// structs). It returns an error if any state field that also exists on the remote cannot
58-
// be copied without a value-changing conversion; such a field needs a custom RemapState.
59-
func compileCopier(remoteType, stateType reflect.Type) (*copier, error) {
60-
stateElem := stateType.Elem()
61-
remoteElem := remoteType.Elem()
56+
// Compile builds the copy plan for srcType -> dstType (both pointers to structs). It returns
57+
// an error if a destination field that also exists on the source cannot be copied without a
58+
// value-changing conversion, so callers can reject such a type pair up front rather than
59+
// silently dropping the field.
60+
func Compile(srcType, dstType reflect.Type) (*Copier, error) {
61+
dstElem := dstType.Elem()
62+
srcElem := srcType.Elem()
6263

63-
dstFields, dstForceSend := flattenStruct(stateElem, nil)
64-
srcFields, _ := flattenStruct(remoteElem, nil)
64+
dstFields, dstForceSend := flattenStruct(dstElem, nil)
65+
srcFields, _ := flattenStruct(srcElem, nil)
6566

6667
var ops []copyOp
6768
for name, dst := range dstFields {
6869
src, ok := srcFields[name]
6970
if !ok {
70-
// Field absent from the remote type: always nil/zero in the remapped
71-
// state. This is the missing_in_remote invariant the planner relies on.
71+
// Field absent from the source type is left zero in the destination.
7272
continue
7373
}
7474
switch {
@@ -77,65 +77,66 @@ func compileCopier(remoteType, stateType reflect.Type) (*copier, error) {
7777
case safeConvert(dst.typ, src.typ):
7878
ops = append(ops, copyOp{forceSendFields: false, dstIndex: dst.index, srcIndex: src.index, convert: true, dstType: dst.typ, ownerType: nil})
7979
default:
80-
return nil, fmt.Errorf("field %q: state type %s cannot be copied from remote type %s; implement RemapState", name, dst.typ, src.typ)
80+
return nil, fmt.Errorf("field %q: destination type %s is not assignable or safely convertible from source type %s", name, dst.typ, src.typ)
8181
}
8282
}
8383

8484
for _, target := range dstForceSend {
8585
ops = append(ops, copyOp{forceSendFields: true, dstIndex: target.index, srcIndex: nil, convert: false, dstType: nil, ownerType: target.ownerType})
8686
}
8787

88-
return &copier{stateElem: stateElem, ops: ops}, nil
89-
}
90-
91-
// safeConvert reports whether a value of src can be converted to dst without changing
92-
// the value. Distinct named types with the same underlying type (e.g. two string enums)
93-
// qualify; kind-changing conversions (int<->string, float->int, []byte<->string) do not,
94-
// because reflect.Convert would silently corrupt the value.
95-
func safeConvert(dst, src reflect.Type) bool {
96-
return src.ConvertibleTo(dst) && src.Kind() == dst.Kind()
97-
}
98-
99-
// rootForceSendFields returns the ForceSendFields slice of the remote struct's root, or nil.
100-
func rootForceSendFields(remote reflect.Value) []string {
101-
f := remote.FieldByName("ForceSendFields")
102-
if !f.IsValid() || f.Kind() != reflect.Slice {
103-
return nil
104-
}
105-
fields, _ := reflect.TypeAssert[[]string](f)
106-
return fields
88+
return &Copier{dstElem: dstElem, ops: ops}, nil
10789
}
10890

109-
// copy builds a fresh *StateType populated from remote (a *RemoteType).
110-
func (c *copier) copy(remote any) any {
111-
src := reflect.ValueOf(remote).Elem()
112-
dstPtr := reflect.New(c.stateElem)
113-
dst := dstPtr.Elem()
91+
// Copy builds a fresh destination value (a pointer to the destination struct) populated
92+
// from src (a pointer to the source struct).
93+
func (c *Copier) Copy(src any) any {
94+
srcVal := reflect.ValueOf(src).Elem()
95+
dstPtr := reflect.New(c.dstElem)
96+
dstVal := dstPtr.Elem()
11497

11598
var srcForceSend []string
11699
for _, op := range c.ops {
117100
if op.forceSendFields {
118101
if srcForceSend == nil {
119-
srcForceSend = rootForceSendFields(src)
102+
srcForceSend = rootForceSendFields(srcVal)
120103
}
121104
filtered := utils.FilterFieldsType(op.ownerType, srcForceSend)
122-
dst.FieldByIndex(op.dstIndex).Set(reflect.ValueOf(filtered))
105+
dstVal.FieldByIndex(op.dstIndex).Set(reflect.ValueOf(filtered))
123106
continue
124107
}
125-
val := src.FieldByIndex(op.srcIndex)
108+
val := srcVal.FieldByIndex(op.srcIndex)
126109
if op.convert {
127110
val = val.Convert(op.dstType)
128111
}
129-
dst.FieldByIndex(op.dstIndex).Set(val)
112+
dstVal.FieldByIndex(op.dstIndex).Set(val)
130113
}
131114

132115
return dstPtr.Interface()
133116
}
134117

118+
// safeConvert reports whether a value of src can be converted to dst without changing
119+
// the value. Distinct named types with the same underlying type (e.g. two string enums)
120+
// qualify; kind-changing conversions (int<->string, float->int, []byte<->string) do not,
121+
// because reflect.Convert would silently corrupt the value.
122+
func safeConvert(dst, src reflect.Type) bool {
123+
return src.ConvertibleTo(dst) && src.Kind() == dst.Kind()
124+
}
125+
126+
// rootForceSendFields returns the ForceSendFields slice at the struct's root, or nil.
127+
func rootForceSendFields(v reflect.Value) []string {
128+
f := v.FieldByName("ForceSendFields")
129+
if !f.IsValid() || f.Kind() != reflect.Slice {
130+
return nil
131+
}
132+
fields, _ := reflect.TypeAssert[[]string](f)
133+
return fields
134+
}
135+
135136
// flattenStruct enumerates a struct's top-level JSON fields (descending through
136137
// encoding/json-flattened embeds and accumulating the field-index prefix) plus every
137138
// ForceSendFields slice reachable through those embeds. Names follow the same JSON tag
138-
// resolution the diff engine uses, so copied state compares consistently.
139+
// resolution the diff engine uses, so copied values compare consistently.
139140
func flattenStruct(t reflect.Type, prefix []int) (map[string]jsonFieldInfo, []forceSendTarget) {
140141
fields := make(map[string]jsonFieldInfo)
141142
var forceSend []forceSendTarget

0 commit comments

Comments
 (0)