|
| 1 | +// Package merge layers one configuration value over another, and deep-copies |
| 2 | +// one, from the struct definitions themselves. |
| 3 | +// |
| 4 | +// It exists to delete a category of code: hand-written `if o.X != "" { s.X = o.X }` |
| 5 | +// chains, hand-written emptiness tests, and hand-written field-by-field copies. |
| 6 | +// Each of those has to be updated whenever a field is added, and each is a place |
| 7 | +// a field can be silently forgotten. Structural merging cannot forget a field, |
| 8 | +// so adding one to a spec needs no merge code at all. |
| 9 | +// |
| 10 | +// The default behaviour is: |
| 11 | +// |
| 12 | +// - scalars and strings — the override wins when it is set (a zero value means |
| 13 | +// "unset", so an override can turn a bool on but never off); |
| 14 | +// - slices — replaced wholesale when the override's is non-empty, because a |
| 15 | +// list of tools means exactly those tools; |
| 16 | +// - maps — merged key-wise, because a map is a set of independent settings; |
| 17 | +// - structs, including those behind a pointer — merged field by field, so |
| 18 | +// setting one sub-field does not erase its siblings. |
| 19 | +// |
| 20 | +// Policy names the exceptions, including the types whose merge is a domain rule |
| 21 | +// rather than a structural one and which therefore merge themselves. |
| 22 | +package merge |
| 23 | + |
| 24 | +import ( |
| 25 | + "fmt" |
| 26 | + "reflect" |
| 27 | + |
| 28 | + "dario.cat/mergo" |
| 29 | +) |
| 30 | + |
| 31 | +// Policy declares the exceptions to structural merging for one family of types. |
| 32 | +// The zero Policy is valid and means "no exceptions". |
| 33 | +type Policy struct { |
| 34 | + // Replace lists types that are indivisible: when the override's value is set |
| 35 | + // it replaces the base's wholesale instead of being merged into. A pointer |
| 36 | + // type counts as set when it is non-nil — which is how an explicit |
| 37 | + // *float64(0) or *bool(false) survives a merge that would otherwise read the |
| 38 | + // pointed-at zero as "unset" and drop it. |
| 39 | + // |
| 40 | + // Name a type by its zero value: merge.Policy{Replace: []any{(*float64)(nil)}}. |
| 41 | + Replace []any |
| 42 | + |
| 43 | + // Shared lists types that are referenced, not owned: Apply assigns them like |
| 44 | + // Replace, and Clone copies the reference instead of walking it. Registries, |
| 45 | + // catalogs and caches belong here — deep-copying one is both wasteful and |
| 46 | + // wrong, because consumers rely on pointer identity. |
| 47 | + Shared []any |
| 48 | + |
| 49 | + // Merger lists types that merge themselves. Each must declare the method |
| 50 | + // `Merge(T) T` on the type named; Apply calls base.Merge(override) and takes |
| 51 | + // the result instead of walking the type. It is where a merge rule that is a |
| 52 | + // domain decision rather than a structural one lives: a list that accumulates |
| 53 | + // across configuration layers instead of being replaced, or two fields that |
| 54 | + // only mean anything when they move together. |
| 55 | + // |
| 56 | + // The method always runs — a nil slice or map destination is materialised |
| 57 | + // first, so "the base had none" reaches Merge as an empty value rather than |
| 58 | + // silently bypassing it. A pointer type therefore cannot be a Merger (a nil |
| 59 | + // pointer has nothing to call the method on), and naming a type without that |
| 60 | + // exact method panics rather than quietly reverting to structural merging. |
| 61 | + Merger []any |
| 62 | +} |
| 63 | + |
| 64 | +// With returns the union of two policies, so a nested type's policy can be |
| 65 | +// composed into its container's rather than restated. |
| 66 | +func (p Policy) With(other Policy) Policy { |
| 67 | + return Policy{ |
| 68 | + Replace: append(append([]any{}, p.Replace...), other.Replace...), |
| 69 | + Shared: append(append([]any{}, p.Shared...), other.Shared...), |
| 70 | + Merger: append(append([]any{}, p.Merger...), other.Merger...), |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +// Apply returns base with override's set fields layered on top, per the package |
| 75 | +// default and policy's exceptions. Neither argument is mutated, and the result |
| 76 | +// shares no mutable memory with either — a merged spec can be edited without |
| 77 | +// reaching back into the config it inherited from. |
| 78 | +// |
| 79 | +// T must be a struct, map or slice type; anything else is a caller error and |
| 80 | +// panics, as does a mergo failure, which cannot occur for a well-formed T since |
| 81 | +// both operands are the same concrete type by construction. |
| 82 | +func Apply[T any](base, override T, policy Policy) T { |
| 83 | + mergers := mergerSet(policy.Merger) |
| 84 | + out := clone(base, policy, mergers) |
| 85 | + src := clone(override, policy, mergers) |
| 86 | + opts := []func(*mergo.Config){mergo.WithOverride} |
| 87 | + if t := policy.transformer(mergers); t != nil { |
| 88 | + opts = append(opts, mergo.WithTransformers(t)) |
| 89 | + } |
| 90 | + if err := mergo.Merge(&out, src, opts...); err != nil { |
| 91 | + panic(fmt.Sprintf("merge %T: %v", base, err)) |
| 92 | + } |
| 93 | + return out |
| 94 | +} |
| 95 | + |
| 96 | +// Clone returns a deep copy of v. Interfaces, functions and channels are copied |
| 97 | +// by reference — they carry behaviour rather than configuration — as are the |
| 98 | +// types named in policy.Shared. Unexported fields are copied as they stand. |
| 99 | +func Clone[T any](v T, policy Policy) T { |
| 100 | + return clone(v, policy, nil) |
| 101 | +} |
| 102 | + |
| 103 | +// clone is Clone plus Apply's extra duty: materialise the nil slices and maps |
| 104 | +// whose type declares its own Merge, so mergo — which skips its transformers for |
| 105 | +// a nil destination — cannot bypass one. |
| 106 | +func clone[T any](v T, policy Policy, materialize map[reflect.Type]bool) T { |
| 107 | + shared := typeSet(policy.Shared) |
| 108 | + if len(shared) == 0 { |
| 109 | + shared = nil |
| 110 | + } |
| 111 | + return cloneValue(reflect.ValueOf(&v).Elem(), shared, materialize).Interface().(T) |
| 112 | +} |
| 113 | + |
| 114 | +func cloneValue(v reflect.Value, shared, materialize map[reflect.Type]bool) reflect.Value { |
| 115 | + if !v.IsValid() || shared[v.Type()] { |
| 116 | + return v |
| 117 | + } |
| 118 | + switch v.Kind() { |
| 119 | + case reflect.Pointer: |
| 120 | + if v.IsNil() { |
| 121 | + return v |
| 122 | + } |
| 123 | + out := reflect.New(v.Type().Elem()) |
| 124 | + out.Elem().Set(cloneValue(v.Elem(), shared, materialize)) |
| 125 | + return out |
| 126 | + case reflect.Slice: |
| 127 | + if v.IsNil() { |
| 128 | + if !materialize[v.Type()] { |
| 129 | + return v |
| 130 | + } |
| 131 | + return reflect.MakeSlice(v.Type(), 0, 0) |
| 132 | + } |
| 133 | + out := reflect.MakeSlice(v.Type(), v.Len(), v.Len()) |
| 134 | + for i := range v.Len() { |
| 135 | + out.Index(i).Set(cloneValue(v.Index(i), shared, materialize)) |
| 136 | + } |
| 137 | + return out |
| 138 | + case reflect.Map: |
| 139 | + if v.IsNil() { |
| 140 | + if !materialize[v.Type()] { |
| 141 | + return v |
| 142 | + } |
| 143 | + return reflect.MakeMapWithSize(v.Type(), 0) |
| 144 | + } |
| 145 | + out := reflect.MakeMapWithSize(v.Type(), v.Len()) |
| 146 | + for iter := v.MapRange(); iter.Next(); { |
| 147 | + out.SetMapIndex(cloneValue(iter.Key(), shared, materialize), cloneValue(iter.Value(), shared, materialize)) |
| 148 | + } |
| 149 | + return out |
| 150 | + case reflect.Array: |
| 151 | + out := reflect.New(v.Type()).Elem() |
| 152 | + for i := range v.Len() { |
| 153 | + out.Index(i).Set(cloneValue(v.Index(i), shared, materialize)) |
| 154 | + } |
| 155 | + return out |
| 156 | + case reflect.Struct: |
| 157 | + out := reflect.New(v.Type()).Elem() |
| 158 | + out.Set(v) |
| 159 | + for i := range v.NumField() { |
| 160 | + if v.Type().Field(i).IsExported() { |
| 161 | + out.Field(i).Set(cloneValue(v.Field(i), shared, materialize)) |
| 162 | + } |
| 163 | + } |
| 164 | + return out |
| 165 | + default: |
| 166 | + return v |
| 167 | + } |
| 168 | +} |
| 169 | + |
| 170 | +// transformer returns the mergo hook that short-circuits every policy type, or |
| 171 | +// nil when the policy declares none. |
| 172 | +func (p Policy) transformer(mergers map[reflect.Type]bool) mergo.Transformers { |
| 173 | + assign := typeSet(append(append([]any{}, p.Replace...), p.Shared...)) |
| 174 | + if len(assign) == 0 && len(mergers) == 0 { |
| 175 | + return nil |
| 176 | + } |
| 177 | + return policyTransformer{assign: assign, mergers: mergers} |
| 178 | +} |
| 179 | + |
| 180 | +type policyTransformer struct { |
| 181 | + assign map[reflect.Type]bool |
| 182 | + mergers map[reflect.Type]bool |
| 183 | +} |
| 184 | + |
| 185 | +func (t policyTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { |
| 186 | + switch { |
| 187 | + case t.mergers[typ]: |
| 188 | + return func(dst, src reflect.Value) error { |
| 189 | + if dst.CanSet() { |
| 190 | + dst.Set(dst.MethodByName("Merge").Call([]reflect.Value{src})[0]) |
| 191 | + } |
| 192 | + return nil |
| 193 | + } |
| 194 | + case t.assign[typ]: |
| 195 | + return func(dst, src reflect.Value) error { |
| 196 | + if isSet(src) && dst.CanSet() { |
| 197 | + dst.Set(src) |
| 198 | + } |
| 199 | + return nil |
| 200 | + } |
| 201 | + default: |
| 202 | + return nil |
| 203 | + } |
| 204 | +} |
| 205 | + |
| 206 | +// isSet reports whether an override value carries an instruction. A pointer is |
| 207 | +// set when it is non-nil, so a pointer to a zero scalar still wins; every other |
| 208 | +// kind is set when it is not the zero value. |
| 209 | +func isSet(v reflect.Value) bool { |
| 210 | + switch v.Kind() { |
| 211 | + case reflect.Pointer, reflect.Interface, reflect.Map, reflect.Slice, reflect.Func, reflect.Chan: |
| 212 | + return !v.IsNil() |
| 213 | + default: |
| 214 | + return !v.IsZero() |
| 215 | + } |
| 216 | +} |
| 217 | + |
| 218 | +// mergerSet validates that every Merger type can actually merge itself. The |
| 219 | +// signature is checked here rather than at the merge, because a type whose method |
| 220 | +// was renamed or re-typed would otherwise fall back to structural merging — the |
| 221 | +// silent drift this package exists to remove. |
| 222 | +func mergerSet(values []any) map[reflect.Type]bool { |
| 223 | + set := typeSet(values) |
| 224 | + for typ := range set { |
| 225 | + if typ.Kind() == reflect.Pointer { |
| 226 | + panic(fmt.Sprintf("merge: policy Merger type %s must not be a pointer — a nil pointer has no value to merge into", typ)) |
| 227 | + } |
| 228 | + method, ok := typ.MethodByName("Merge") |
| 229 | + if !ok || method.Type.NumIn() != 2 || method.Type.In(1) != typ || |
| 230 | + method.Type.NumOut() != 1 || method.Type.Out(0) != typ { |
| 231 | + panic(fmt.Sprintf("merge: policy Merger type %s must declare a method Merge(%s) %s", typ, typ, typ)) |
| 232 | + } |
| 233 | + } |
| 234 | + return set |
| 235 | +} |
| 236 | + |
| 237 | +func typeSet(values []any) map[reflect.Type]bool { |
| 238 | + if len(values) == 0 { |
| 239 | + return nil |
| 240 | + } |
| 241 | + set := make(map[reflect.Type]bool, len(values)) |
| 242 | + for _, value := range values { |
| 243 | + typ := reflect.TypeOf(value) |
| 244 | + if typ == nil { |
| 245 | + panic("merge: policy type must be named by a typed zero value, e.g. (*float64)(nil)") |
| 246 | + } |
| 247 | + set[typ] = true |
| 248 | + } |
| 249 | + return set |
| 250 | +} |
0 commit comments