-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathwalk.go
316 lines (277 loc) · 8.07 KB
/
walk.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// Copyright 2016-2023, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package walk
import (
"bytes"
"encoding/json"
"fmt"
"sort"
"strings"
hcty "github.com/hashicorp/go-cty/cty"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/zclconf/go-cty/cty"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim/schema"
)
// Represents locations in a tfshim.Schema value as a sequence of steps to locate it.
//
// An empty SchemaPath represents the current location.
//
// Values of this type are immutable by convention, use Copy as necessary for local mutations.
type SchemaPath []SchemaPathStep
func (p SchemaPath) GoString() string {
parts := []string{"walk", "NewSchemaPath()"}
for _, step := range p {
switch s := step.(type) {
case ElementStep:
parts = append(parts, "Element()")
case GetAttrStep:
parts = append(parts, fmt.Sprintf("GetAttr(%q)", s.Name))
}
}
return strings.Join(parts, ".")
}
func (p SchemaPath) Copy() SchemaPath {
ret := make(SchemaPath, len(p))
copy(ret, p)
return ret
}
func (p SchemaPath) Element() SchemaPath {
return p.WithStep(ElementStep{})
}
func (p SchemaPath) GetAttr(name string) SchemaPath {
return p.WithStep(GetAttrStep{name})
}
func (p SchemaPath) WithStep(suffix SchemaPathStep) SchemaPath {
ret := make(SchemaPath, len(p)+1)
copy(ret, p)
ret[len(p)] = suffix
return ret
}
func (p SchemaPath) EncodeSchemaPath() (string, error) {
var buf bytes.Buffer
for i, step := range p {
if i > 0 {
fmt.Fprintf(&buf, ".")
}
switch step := step.(type) {
case ElementStep:
fmt.Fprintf(&buf, "$")
case GetAttrStep:
if strings.Contains(step.Name, ".") {
return "", fmt.Errorf("Cannot encode SchemaPath %q containing '.'", step.Name)
}
if step.Name == "$" {
return "", fmt.Errorf("Cannot encode SchemaPath %q", step.Name)
}
fmt.Fprintf(&buf, "%s", step.Name)
default:
contract.Failf("impossible")
}
}
return buf.String(), nil
}
func (p SchemaPath) MustEncodeSchemaPath() string {
s, err := p.EncodeSchemaPath()
contract.AssertNoErrorf(err, "Unexpected SchemaPath encoding error")
return s
}
func DecodeSchemaPath(path string) SchemaPath {
p := NewSchemaPath()
if path == "" {
return p
}
for _, frag := range strings.Split(path, ".") {
if frag == "$" {
p = p.Element()
} else {
p = p.GetAttr(frag)
}
}
return p
}
var (
_ json.Marshaler = SchemaPath{}
_ json.Unmarshaler = &SchemaPath{}
)
func (p SchemaPath) MarshalJSON() ([]byte, error) {
s, err := p.EncodeSchemaPath()
if err != nil {
return nil, err
}
return json.Marshal(s)
}
func (p *SchemaPath) UnmarshalJSON(bytes []byte) error {
var s string
err := json.Unmarshal(bytes, &s)
if err != nil {
return err
}
*p = DecodeSchemaPath(s)
return nil
}
// Provide a stable ordering of SchemaPaths.
//
// Beyond determinism, there is no specific sort order.
func SortSchemaPaths(paths []SchemaPath) {
sort.Slice(paths, func(i, j int) bool {
return paths[i].GoString() < paths[j].GoString()
})
}
// Builds a new empty SchemaPath.
func NewSchemaPath() SchemaPath {
return make(SchemaPath, 0)
}
// Finds a nested Schema at a given path.
func LookupSchemaPath(path SchemaPath, schema shim.Schema) (shim.Schema, error) {
p := path
current := NewSchemaPath()
result := schema
for {
if len(p) == 0 {
return result, nil
}
nextResult, err := p[0].Lookup(result)
if err != nil {
return nil, fmt.Errorf("LookupSchemaPath failed at %s: %w", current.GoString(), err)
}
result, p, current = nextResult, p[1:], current.WithStep(p[0])
}
}
// Similar to LookupSchemaPath but starts the initial step from a SchemaMap.
func LookupSchemaMapPath(path SchemaPath, schemaMap shim.SchemaMap) (shim.Schema, error) {
return LookupSchemaPath(path, wrapSchemaMap(schemaMap))
}
// Represents elements of a SchemaPath.
//
// This interface is closed, the only the implementations given in the current package are allowed.
type SchemaPathStep interface {
isSchemaPathStep()
GoString() string
Lookup(shim.Schema) (shim.Schema, error)
}
// Drill down into an attribute by the given attribute name.
type GetAttrStep struct {
Name string
}
func (GetAttrStep) isSchemaPathStep() {}
func (step GetAttrStep) GoString() string {
return fmt.Sprintf("walk.GetAttrStep{%q}", step.Name)
}
func (step GetAttrStep) Lookup(s shim.Schema) (shim.Schema, error) {
if sm, ok := unwrapSchemaMap(s); ok {
s, found := sm.GetOk(step.Name)
if !found {
return nil, fmt.Errorf("%s not found", step.GoString())
}
return s, nil
}
return nil, fmt.Errorf("%s is not applicable", step.GoString())
}
// Drill down into a Map, Set or List element schema.
type ElementStep struct{}
func (ElementStep) isSchemaPathStep() {}
func (step ElementStep) GoString() string {
return "walk.ElementStep{}"
}
func (step ElementStep) Lookup(s shim.Schema) (shim.Schema, error) {
switch elem := s.Elem().(type) {
case shim.Resource:
switch s.Type() {
case shim.TypeMap:
return nil, fmt.Errorf("%s is not applicable to object types", step.GoString())
case shim.TypeList, shim.TypeSet:
return wrapSchemaMap(elem.Schema()), nil
default:
return nil, fmt.Errorf("%s is not applicable", step.GoString())
}
case shim.Schema:
return elem, nil
default:
return nil, fmt.Errorf("%s is not applicable", step.GoString())
}
}
func wrapSchemaMap(sm shim.SchemaMap) shim.Schema {
return (&schema.Schema{
Type: shim.TypeMap,
Elem: (&schema.Resource{Schema: sm}).Shim(),
}).Shim()
}
// Utility function to recognize nested object field type schemas encoded in shim.Schema.
func unwrapSchemaMap(s shim.Schema) (shim.SchemaMap, bool) {
switch elem := s.Elem().(type) {
case shim.Resource:
return elem.Schema(), true
default:
return nil, false
}
}
type SchemaVisitor = func(SchemaPath, shim.Schema)
// Visit all nested schemas, including the current one.
func VisitSchema(schema shim.Schema, visitor SchemaVisitor) {
visitSchemaInner(NewSchemaPath(), schema, visitor)
}
// Visit all nested schemas in a SchemaMap, keeping track of SchemaPath location.
func VisitSchemaMap(schemaMap shim.SchemaMap, visitor SchemaVisitor) {
visitSchemaMapInner(NewSchemaPath(), schemaMap, visitor)
}
func visitSchemaInner(path SchemaPath, schema shim.Schema, visitor SchemaVisitor) {
visitor(path, schema)
switch elem := schema.Elem().(type) {
case shim.Resource:
var nestedPath SchemaPath
if schema.Type() == shim.TypeMap {
// Single-nested blocks are special, drilling down into the elements of the block's object type
// can begin immediately without an Element step.
nestedPath = path
} else {
nestedPath = path.Element()
}
visitSchemaMapInner(nestedPath, elem.Schema(), visitor)
case shim.Schema:
visitSchemaInner(path.Element(), elem, visitor)
}
}
func visitSchemaMapInner(path SchemaPath, schemaMap shim.SchemaMap, visitor SchemaVisitor) {
schemaMap.Range(func(key string, schema shim.Schema) bool {
visitSchemaInner(path.GetAttr(key), schema, visitor)
return true
})
}
// Converts a value path to a Schema Path (zclconf package representation).
func FromCtyPath(path cty.Path) SchemaPath {
p := NewSchemaPath()
for _, subPath := range path {
switch s := subPath.(type) {
case cty.IndexStep:
p = p.Element()
case cty.GetAttrStep:
p = p.GetAttr(s.Name)
}
}
return p
}
// Converts a value path to a Schema Path (hashicorp/go-cty representation).
func FromHCtyPath(path hcty.Path) SchemaPath {
p := NewSchemaPath()
for _, subPath := range path {
switch s := subPath.(type) {
case hcty.IndexStep:
p = p.Element()
case hcty.GetAttrStep:
p = p.GetAttr(s.Name)
}
}
return p
}