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
310import (
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
2727type 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.
139140func flattenStruct (t reflect.Type , prefix []int ) (map [string ]jsonFieldInfo , []forceSendTarget ) {
140141 fields := make (map [string ]jsonFieldInfo )
141142 var forceSend []forceSendTarget
0 commit comments