-
Notifications
You must be signed in to change notification settings - Fork 400
/
gen.go
419 lines (349 loc) · 11.4 KB
/
gen.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*
Copyright 2021 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 applyconfigurations
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/types"
"io"
"path/filepath"
"sort"
"strings"
"golang.org/x/tools/go/packages"
"sigs.k8s.io/controller-tools/pkg/genall"
"sigs.k8s.io/controller-tools/pkg/loader"
"sigs.k8s.io/controller-tools/pkg/markers"
)
// Based on deepcopy gen but with legacy marker support removed.
var (
enablePkgMarker = markers.Must(markers.MakeDefinition("kubebuilder:ac:generate", markers.DescribesPackage, false))
enableTypeMarker = markers.Must(markers.MakeDefinition("kubebuilder:ac:generate", markers.DescribesType, false))
isObjectMarker = markers.Must(markers.MakeDefinition("kubebuilder:ac:root", markers.DescribesType, false))
)
var importMapping = map[string]string{"k8s.io/apimachinery/pkg/apis/": "k8s.io/client-go/applyconfigurations/", "k8s.io/api/": "k8s.io/client-go/applyconfigurations/"}
const importPathSuffix = "ac"
const packageFileName = "zz_generated.applyconfigurations.go"
// +controllertools:marker:generateHelp
// Generator generates code containing apply configuration type implementations.
type Generator struct {
// HeaderFile specifies the header text (e.g. license) to prepend to generated files.
HeaderFile string `marker:",optional"`
// Year specifies the year to substitute for " YEAR" in the header file.
Year string `marker:",optional"`
}
func (Generator) CheckFilter() loader.NodeFilter {
return func(node ast.Node) bool {
// ignore interfaces
_, isIface := node.(*ast.InterfaceType)
return !isIface
}
}
func (Generator) RegisterMarkers(into *markers.Registry) error {
if err := markers.RegisterAll(into,
enablePkgMarker, enableTypeMarker, isObjectMarker); err != nil {
return err
}
into.AddHelp(enablePkgMarker,
markers.SimpleHelp("apply", "enables or disables object apply configuration generation for this package"))
into.AddHelp(
enableTypeMarker, markers.SimpleHelp("apply", "overrides enabling or disabling apply configuration generation for this type"))
into.AddHelp(isObjectMarker,
markers.SimpleHelp("apply", "enables apply configuration generation for this type"))
return nil
}
func enabledOnPackage(col *markers.Collector, pkg *loader.Package) (bool, error) {
pkgMarkers, err := markers.PackageMarkers(col, pkg)
if err != nil {
return false, err
}
pkgMarker := pkgMarkers.Get(enablePkgMarker.Name)
if pkgMarker != nil {
return pkgMarker.(bool), nil
}
return false, nil
}
func enabledOnType(allTypes bool, info *markers.TypeInfo) bool {
if typeMarker := info.Markers.Get(enableTypeMarker.Name); typeMarker != nil {
return typeMarker.(bool)
}
return allTypes || genObjectInterface(info)
}
func genObjectInterface(info *markers.TypeInfo) bool {
objectEnabled := info.Markers.Get(isObjectMarker.Name)
if objectEnabled != nil {
return objectEnabled.(bool)
}
return false
}
func groupAndPackageVersion(pkg string) string {
parts := strings.Split(pkg, "/")
return parts[len(parts)-2] + "/" + parts[len(parts)-1]
}
func createApplyConfigPackage(universe *Universe, pkg *loader.Package) *loader.Package {
newPkg := &loader.Package{Package: &packages.Package{}}
if filepath.Dir(pkg.CompiledGoFiles[0]) == universe.baseFilePath {
newPkg.CompiledGoFiles = append(newPkg.CompiledGoFiles, universe.baseFilePath+"/"+importPathSuffix+"/")
} else {
desiredPath := universe.baseFilePath + "/" + importPathSuffix + "/" + groupAndPackageVersion(pkg.PkgPath) + "/"
newPkg.CompiledGoFiles = append(newPkg.CompiledGoFiles, desiredPath)
}
return newPkg
}
type PkgInfo struct {
objGenCtx *ObjectGenCtx
pkg *loader.Package
used bool
typeInfo []types.Type
}
func (p *PkgInfo) GenerateTypes() {
p.typeInfo = p.objGenCtx.generateEligibleTypes(p.pkg)
}
func (d Generator) Generate(ctx *genall.GenerationContext) error {
var headerText string
if d.HeaderFile != "" {
headerBytes, err := ctx.ReadFile(d.HeaderFile)
if err != nil {
return err
}
headerText = string(headerBytes)
}
headerText = strings.ReplaceAll(headerText, " YEAR", " "+d.Year)
objGenCtx := ObjectGenCtx{
Collector: ctx.Collector,
Checker: ctx.Checker,
HeaderText: headerText,
}
var pkgList []*loader.Package
var generatedList []*loader.Package
//TODO|jefftree: This might cause problems if multiple packages are provided
crdRoot := ctx.Roots[0]
for _, root := range ctx.Roots {
pkgList = append(pkgList, root)
generatedList = append(generatedList, root)
}
visited := make(map[string]*PkgInfo)
for len(pkgList) != 0 {
pkg := pkgList[0]
pkgList = pkgList[1:]
if _, ok := visited[pkg.PkgPath]; ok {
continue
}
importPkgInfo := &PkgInfo{
objGenCtx: &objGenCtx,
pkg: pkg,
used: false,
}
visited[pkg.PkgPath] = importPkgInfo
for _, imp := range pkg.Imports() {
pkgList = append(pkgList, imp)
}
}
var eligibleTypes []types.Type
for _, pkg := range visited {
eligibleTypes = append(eligibleTypes, objGenCtx.generateEligibleTypes(pkg.pkg)...)
}
universe := &Universe{
eligibleTypes: eligibleTypes,
baseImportPath: crdRoot.PkgPath,
baseFilePath: filepath.Dir(crdRoot.CompiledGoFiles[0]),
importMapping: importMapping,
visited: visited,
crawlPaths: generatedList,
}
for len(universe.crawlPaths) != 0 {
pkg := universe.crawlPaths[0]
universe.crawlPaths = universe.crawlPaths[1:]
outContents := objGenCtx.generateForPackage(universe, pkg)
if outContents == nil {
continue
}
newPkg := createApplyConfigPackage(universe, pkg)
writeOut(ctx, newPkg, outContents)
}
return nil
}
// ObjectGenCtx contains the common info for generating apply configuration implementations.
// It mostly exists so that generating for a package can be easily tested without
// requiring a full set of output rules, etc.
type ObjectGenCtx struct {
Collector *markers.Collector
Checker *loader.TypeChecker
HeaderText string
}
// writeHeader writes out the build tag, package declaration, and imports
func writeHeader(pkg *loader.Package, out io.Writer, packageName string, imports *importsList, headerText string) {
// NB(directxman12): blank line after build tags to distinguish them from comments
_, err := fmt.Fprintf(out, `// +build !ignore_autogenerated
%[3]s
// Code generated by controller-gen. DO NOT EDIT.
package %[1]s
import (
%[2]s
)
`, packageName, strings.Join(imports.ImportSpecs(), "\n"), headerText)
if err != nil {
pkg.AddError(err)
}
}
func (ctx *ObjectGenCtx) generateEligibleTypes(root *loader.Package) []types.Type {
ctx.Checker.Check(root)
root.NeedTypesInfo()
var eligibleTypes []types.Type
if err := markers.EachType(ctx.Collector, root, func(info *markers.TypeInfo) {
if shouldBeApplyConfiguration(root, info) {
typeInfo := root.TypesInfo.TypeOf(info.RawSpec.Name)
eligibleTypes = append(eligibleTypes, typeInfo)
}
}); err != nil {
root.AddError(err)
return nil
}
return eligibleTypes
}
type Universe struct {
eligibleTypes []types.Type
baseImportPath string
importPathSuffix string
baseFilePath string
importMapping map[string]string
visited map[string]*PkgInfo
crawlPaths []*loader.Package
}
func (u *Universe) existingApplyConfig(typeInfo *types.Named, pkgPath string) (string, bool) {
for prefix, replacePath := range u.importMapping {
if strings.HasPrefix(pkgPath, prefix) {
path := replacePath + strings.TrimPrefix(pkgPath, prefix)
return path, true
}
}
return "", false
}
func (u *Universe) IsApplyConfigGenerated(typeInfo *types.Named, pkgPath string) bool {
exists := false
for _, b := range u.eligibleTypes {
if b == typeInfo {
exists = true
if _, ok := u.visited[pkgPath]; ok {
if u.visited[pkgPath].used == false {
u.visited[pkgPath].used = true
u.crawlPaths = append(u.crawlPaths, u.visited[pkgPath].pkg)
}
}
break
}
}
return exists
}
func (u *Universe) GetApplyConfigPath(typeInfo *types.Named, pkgPath string) (string, bool) {
if path, ok := u.existingApplyConfig(typeInfo, pkgPath); ok {
return path, ok
}
if !u.IsApplyConfigGenerated(typeInfo, pkgPath) {
return pkgPath, false
}
path := loader.NonVendorPath(pkgPath)
path = groupAndPackageVersion(path)
return u.baseImportPath + "/" + u.importPathSuffix + "/" + path, true
}
// generateForPackage generates apply configuration implementations for
// types in the given package, writing the formatted result to given writer.
// May return nil if source could not be generated.
func (ctx *ObjectGenCtx) generateForPackage(universe *Universe, root *loader.Package) []byte {
byType := make(map[string][]byte)
imports := &importsList{
byPath: make(map[string]string),
byAlias: make(map[string]string),
pkg: root,
}
// avoid confusing aliases by "reserving" the root package's name as an alias
imports.byAlias[root.Name] = ""
if err := markers.EachType(ctx.Collector, root, func(info *markers.TypeInfo) {
outContent := new(bytes.Buffer)
// not all types required a generate apply configuration. For example, no apply configuration
// type is needed for Quantity, IntOrString, RawExtension or Unknown.
if !shouldBeApplyConfiguration(root, info) {
return
}
copyCtx := &applyConfigurationMaker{
pkg: root,
importsList: imports,
codeWriter: &codeWriter{out: outContent},
}
copyCtx.GenerateTypesFor(universe, root, info)
for _, field := range info.Fields {
if field.Name != "" {
copyCtx.GenerateMemberSet(universe, field, root, info)
}
}
copyCtx.GenerateStructConstructor(root, info)
if isRootType(info) {
copyCtx.GenerateRootFunctions(universe, root, info)
}
outBytes := outContent.Bytes()
if len(outBytes) > 0 {
byType[info.Name] = outBytes
}
}); err != nil {
root.AddError(err)
return nil
}
if len(byType) == 0 {
return nil
}
outContent := new(bytes.Buffer)
writeHeader(root, outContent, root.Name, imports, ctx.HeaderText)
writeTypes(root, outContent, byType)
outBytes := outContent.Bytes()
formattedBytes, err := format.Source(outBytes)
if err != nil {
root.AddError(err)
// we still write the invalid source to disk to figure out what went wrong
} else {
outBytes = formattedBytes
}
return outBytes
}
// writeTypes writes each method to the file, sorted by type name.
func writeTypes(pkg *loader.Package, out io.Writer, byType map[string][]byte) {
sortedNames := make([]string, 0, len(byType))
for name := range byType {
sortedNames = append(sortedNames, name)
}
sort.Strings(sortedNames)
for _, name := range sortedNames {
_, err := out.Write(byType[name])
if err != nil {
pkg.AddError(err)
}
}
}
// writeFormatted outputs the given code, after gofmt-ing it. If we couldn't gofmt,
// we write the unformatted code for debugging purposes.
func writeOut(ctx *genall.GenerationContext, root *loader.Package, outBytes []byte) {
outputFile, err := ctx.Open(root, packageFileName)
if err != nil {
root.AddError(err)
return
}
defer outputFile.Close()
n, err := outputFile.Write(outBytes)
if err != nil {
root.AddError(err)
return
}
if n < len(outBytes) {
root.AddError(io.ErrShortWrite)
}
}