-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathtransform.go
78 lines (65 loc) · 2.46 KB
/
transform.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
/*
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 schema
import (
"fmt"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/utils/ptr"
)
// AddPreserveUnknownFields recurses through an *apiextensionsv1.JSONSchemaProps
// data structure, adding `x-kubernetes-preserve-unknown-fields: true` at every level
// that type is equal to "object", "array", or is undefined.
func AddPreserveUnknownFields(sch *apiextensionsv1.JSONSchemaProps) error {
switch sch.Type {
// An object can have values not described in the schema. A blank Type could be anything,
// including an object, so we add x-kubernetes-preserve-unknown-fields: true to both.
case "", "object":
sch.XPreserveUnknownFields = ptr.To[bool](true)
case "array":
// If the type is array, the schema of the array's items must be structural. If the schema
// is undefined, we must add a blank one with x-kubernetes-preserve-unknown-fields to meet
// this structural item schema requirement.
if sch.Items == nil || (sch.Items.Schema == nil && sch.Items.JSONSchemas == nil) {
sch.Items = &apiextensionsv1.JSONSchemaPropsOrArray{
Schema: &apiextensionsv1.JSONSchemaProps{
XPreserveUnknownFields: ptr.To[bool](true),
},
}
}
}
if sch.Properties != nil {
for k := range sch.Properties {
v := sch.Properties[k]
if err := AddPreserveUnknownFields(&v); err != nil {
return err
}
// As v is not a pointer, we need to set the contents of v back into the original data structure
sch.Properties[k] = v
}
}
if sch.Items != nil {
if sch.Items.Schema != nil {
if err := AddPreserveUnknownFields(sch.Items.Schema); err != nil {
return err
}
}
if sch.Items.JSONSchemas != nil {
return fmt.Errorf("non-nil JSONSchemas encountered, multiple schemas are not supported")
}
}
if sch.AdditionalProperties != nil && sch.AdditionalProperties.Schema != nil {
if err := AddPreserveUnknownFields(sch.AdditionalProperties.Schema); err != nil {
return err
}
}
return nil
}