forked from databricks/terraform-provider-databricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtracking_context.go
98 lines (84 loc) · 2.51 KB
/
tracking_context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package common
import (
"maps"
"reflect"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
type trackingContext struct {
timesVisited map[string]int
maxDepthForTypes map[string]int
pathCtx schemaPathContext
}
type schemaPathContext struct {
// Path is used for refernces from resourceProviderRegistry as prefix, follows the format of `[a,0,b]`
path []string
schemaPath []*schema.Schema
}
func (tc trackingContext) withPath(fieldName string, schema *schema.Schema) trackingContext {
newTc := tc.copy()
// Special path element `"0"` is used to denote either arrays or sets of elements
newTc.pathCtx.path = append(tc.pathCtx.path, fieldName, "0")
newTc.pathCtx.schemaPath = append(tc.pathCtx.schemaPath, schema)
return newTc
}
func (tc trackingContext) depthExceeded(typeField reflect.StructField) bool {
typeName := getNameForType(typeField.Type)
if maxDepth, ok := tc.maxDepthForTypes[typeName]; ok {
return tc.timesVisited[typeName]+1 > maxDepth
}
return false
}
func (tc trackingContext) getMaxDepthForTypeField(typeField reflect.StructField) int {
typeName := getNameForType(typeField.Type)
return tc.maxDepthForTypes[typeName]
}
func (tc trackingContext) copy() trackingContext {
newTimesVisited := map[string]int{}
maps.Copy(newTimesVisited, tc.timesVisited)
newPath := make([]string, len(tc.pathCtx.path))
copy(newPath, tc.pathCtx.path)
newSchemaPath := make([]*schema.Schema, len(tc.pathCtx.schemaPath))
copy(newSchemaPath, tc.pathCtx.schemaPath)
return trackingContext{
timesVisited: newTimesVisited,
maxDepthForTypes: tc.maxDepthForTypes,
pathCtx: schemaPathContext{
path: newPath,
schemaPath: newSchemaPath,
},
}
}
func (tc trackingContext) withPathContext(scp schemaPathContext) trackingContext {
newTc := tc.copy()
newTc.pathCtx = scp
return newTc
}
func (tc trackingContext) visit(v reflect.Value) trackingContext {
newTc := tc.copy()
newTc.timesVisited[getNameForType(v.Type())] += 1
return newTc
}
func getEmptySchemaPathContext() schemaPathContext {
return schemaPathContext{
[]string{},
[]*schema.Schema{},
}
}
func getEmptyTrackingContext() trackingContext {
return trackingContext{
map[string]int{},
map[string]int{},
getEmptySchemaPathContext(),
}
}
func getTrackingContext(rp RecursiveResourceProvider) trackingContext {
return trackingContext{
map[string]int{},
rp.MaxDepthForTypes(),
getEmptySchemaPathContext(),
}
}
func getNameForType(t reflect.Type) string {
return strings.TrimPrefix(t.String(), "*")
}