forked from kubernetes-sigs/controller-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
328 lines (288 loc) · 9.18 KB
/
util.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
317
318
319
320
321
322
323
324
325
326
327
328
/*
Copyright 2018 The Kubernetes Authors.
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 parse
import (
"fmt"
"log"
"path/filepath"
"strconv"
"strings"
"github.com/pkg/errors"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
"k8s.io/gengo/types"
)
// Options contains the parser options
type Options struct {
SkipMapValidation bool
// SkipRBACValidation flag determines whether to check RBAC annotations
// for the controller or not at parse stage.
SkipRBACValidation bool
}
// IsAPIResource returns true if:
// 1. t has a +resource/+kubebuilder:resource comment tag
// 2. t has TypeMeta and ObjectMeta in its member list.
func IsAPIResource(t *types.Type) bool {
for _, c := range t.CommentLines {
if strings.Contains(c, "+resource") || strings.Contains(c, "+kubebuilder:resource") {
return true
}
}
typeMetaFound, objMetaFound := false, false
for _, m := range t.Members {
if m.Name == "TypeMeta" && m.Type.String() == "k8s.io/apimachinery/pkg/apis/meta/v1.TypeMeta" {
typeMetaFound = true
}
if m.Name == "ObjectMeta" && m.Type.String() == "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta" {
objMetaFound = true
}
if typeMetaFound && objMetaFound {
return true
}
}
return false
}
// IsNonNamespaced returns true if t has a +nonNamespaced comment tag
func IsNonNamespaced(t *types.Type) bool {
if !IsAPIResource(t) {
return false
}
for _, c := range t.CommentLines {
if strings.Contains(c, "+genclient:nonNamespaced") {
return true
}
}
for _, c := range t.SecondClosestCommentLines {
if strings.Contains(c, "+genclient:nonNamespaced") {
return true
}
}
return false
}
// IsController returns true if t has a +controller or +kubebuilder:controller tag
func IsController(t *types.Type) bool {
for _, c := range t.CommentLines {
if strings.Contains(c, "+controller") || strings.Contains(c, "+kubebuilder:controller") {
return true
}
}
return false
}
// IsRBAC returns true if t has a +rbac or +kubebuilder:rbac tag
func IsRBAC(t *types.Type) bool {
for _, c := range t.CommentLines {
if strings.Contains(c, "+rbac") || strings.Contains(c, "+kubebuilder:rbac") {
return true
}
}
return false
}
// IsInformer returns true if t has a +informers or +kubebuilder:informers tag
func IsInformer(t *types.Type) bool {
for _, c := range t.CommentLines {
if strings.Contains(c, "+informers") || strings.Contains(c, "+kubebuilder:informers") {
return true
}
}
return false
}
// IsAPISubresource returns true if t has a +subresource-request comment tag
func IsAPISubresource(t *types.Type) bool {
for _, c := range t.CommentLines {
if strings.Contains(c, "+subresource-request") {
return true
}
}
return false
}
// HasSubresource returns true if t is an APIResource with one or more Subresources
func HasSubresource(t *types.Type) bool {
if !IsAPIResource(t) {
return false
}
for _, c := range t.CommentLines {
if strings.Contains(c, "+subresource") {
return true
}
}
return false
}
// HasStatusSubresource returns true if t is an APIResource annotated with
// +kubebuilder:subresource:status.
func HasStatusSubresource(t *types.Type) bool {
if !IsAPIResource(t) {
return false
}
for _, c := range t.CommentLines {
if strings.Contains(c, "+kubebuilder:subresource:status") {
return true
}
}
return false
}
// HasCategories returns true if t is an APIResource annotated with
// +kubebuilder:categories.
func HasCategories(t *types.Type) bool {
if !IsAPIResource(t) {
return false
}
for _, c := range t.CommentLines {
if strings.Contains(c, "+kubebuilder:categories") {
return true
}
}
return false
}
// HasDocAnnotation returns true if t is an APIResource with doc annotation
// +kubebuilder:doc
func HasDocAnnotation(t *types.Type) bool {
if !IsAPIResource(t) {
return false
}
for _, c := range t.CommentLines {
if strings.Contains(c, "+kubebuilder:doc") {
return true
}
}
return false
}
// IsUnversioned returns true if t is in given group, and not in versioned path.
func IsUnversioned(t *types.Type, group string) bool {
return IsApisDir(filepath.Base(filepath.Dir(t.Name.Package))) && GetGroup(t) == group
}
// IsVersioned returns true if t is in given group, and in versioned path.
func IsVersioned(t *types.Type, group string) bool {
dir := filepath.Base(filepath.Dir(filepath.Dir(t.Name.Package)))
return IsApisDir(dir) && GetGroup(t) == group
}
// GetVersion returns version of t.
func GetVersion(t *types.Type, group string) string {
if !IsVersioned(t, group) {
panic(errors.Errorf("Cannot get version for unversioned type %v", t.Name))
}
return filepath.Base(t.Name.Package)
}
// GetGroup returns group of t.
func GetGroup(t *types.Type) string {
return filepath.Base(GetGroupPackage(t))
}
// GetGroupPackage returns group package of t.
func GetGroupPackage(t *types.Type) string {
if IsApisDir(filepath.Base(filepath.Dir(t.Name.Package))) {
return t.Name.Package
}
return filepath.Dir(t.Name.Package)
}
// GetKind returns kind of t.
func GetKind(t *types.Type, group string) string {
if !IsVersioned(t, group) && !IsUnversioned(t, group) {
panic(errors.Errorf("Cannot get kind for type not in group %v", t.Name))
}
return t.Name.Name
}
// IsApisDir returns true if a directory path is a Kubernetes api directory
func IsApisDir(dir string) bool {
return dir == "apis" || dir == "api"
}
// Comments is a structure for using comment tags on go structs and fields
type Comments []string
// GetTags returns the value for the first comment with a prefix matching "+name="
// e.g. "+name=foo\n+name=bar" would return "foo"
func (c Comments) getTag(name, sep string) string {
for _, c := range c {
prefix := fmt.Sprintf("+%s%s", name, sep)
if strings.HasPrefix(c, prefix) {
return strings.Replace(c, prefix, "", 1)
}
}
return ""
}
// hasTag returns true if the Comments has a tag with the given name
func (c Comments) hasTag(name string) bool {
for _, c := range c {
prefix := fmt.Sprintf("+%s", name)
if strings.HasPrefix(c, prefix) {
return true
}
}
return false
}
// GetTags returns the value for all comments with a prefix and separator. E.g. for "name" and "="
// "+name=foo\n+name=bar" would return []string{"foo", "bar"}
func (c Comments) getTags(name, sep string) []string {
tags := []string{}
for _, c := range c {
prefix := fmt.Sprintf("+%s%s", name, sep)
if strings.HasPrefix(c, prefix) {
tags = append(tags, strings.Replace(c, prefix, "", 1))
}
}
return tags
}
// getDocAnnotation parse annotations of "+kubebuilder:doc:" with tags of "warning" or "doc" for control generating doc config.
// E.g. +kubebuilder:doc:warning=foo +kubebuilder:doc:note=bar
func getDocAnnotation(t *types.Type, tags ...string) map[string]string {
annotation := make(map[string]string)
for _, tag := range tags {
for _, c := range t.CommentLines {
prefix := fmt.Sprintf("+kubebuilder:doc:%s=", tag)
if strings.HasPrefix(c, prefix) {
annotation[tag] = strings.Replace(c, prefix, "", 1)
}
}
}
return annotation
}
// parseByteValue returns the literal digital number values from a byte array
func parseByteValue(b []byte) string {
elem := strings.Join(strings.Fields(fmt.Sprintln(b)), ",")
elem = strings.TrimPrefix(elem, "[")
elem = strings.TrimSuffix(elem, "]")
return elem
}
// parseEnumToString returns a representive validated go format string from JSONSchemaProps schema
func parseEnumToString(value []v1beta1.JSON) string {
res := "[]v1beta1.JSON{"
prefix := "v1beta1.JSON{[]byte{"
for _, v := range value {
res = res + prefix + parseByteValue(v.Raw) + "}},"
}
return strings.TrimSuffix(res, ",") + "}"
}
// check type of enum element value to match type of field
func checkType(props *v1beta1.JSONSchemaProps, s string, enums *[]v1beta1.JSON) {
// TODO support more types check
switch props.Type {
case "int", "int64", "uint64":
if _, err := strconv.ParseInt(s, 0, 64); err != nil {
log.Fatalf("Invalid integer value [%v] for a field of integer type", s)
}
*enums = append(*enums, v1beta1.JSON{Raw: []byte(fmt.Sprintf("%v", s))})
case "int32", "unit32":
if _, err := strconv.ParseInt(s, 0, 32); err != nil {
log.Fatalf("Invalid integer value [%v] for a field of integer32 type", s)
}
*enums = append(*enums, v1beta1.JSON{Raw: []byte(fmt.Sprintf("%v", s))})
case "float", "float32":
if _, err := strconv.ParseFloat(s, 32); err != nil {
log.Fatalf("Invalid float value [%v] for a field of float32 type", s)
}
*enums = append(*enums, v1beta1.JSON{Raw: []byte(fmt.Sprintf("%v", s))})
case "float64":
if _, err := strconv.ParseFloat(s, 64); err != nil {
log.Fatalf("Invalid float value [%v] for a field of float type", s)
}
*enums = append(*enums, v1beta1.JSON{Raw: []byte(fmt.Sprintf("%v", s))})
case "string":
*enums = append(*enums, v1beta1.JSON{Raw: []byte(`"` + s + `"`)})
}
}