Debian Codegraph @

pkg/generators/model_names.go

raw
1 /*
2 Copyright 2025 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package generators
18
19 import (
20 "fmt"
21 "io"
22 "strings"
23
24 "k8s.io/gengo/v2"
25 "k8s.io/gengo/v2/generator"
26 "k8s.io/gengo/v2/namer"
27 "k8s.io/gengo/v2/types"
28 "k8s.io/klog/v2"
29 )
30
31 const (
32 tagModelPackage = "k8s:openapi-model-package"
33 )
34
35 func extractOpenAPISchemaNamePackage(comments []string) (string, error) {
36 v, err := singularTag(tagModelPackage, comments)
37 if v == nil || err != nil {
38 return "", err
39 }
40 return v.Value, nil
41 }
42
43 func singularTag(tagName string, comments []string) (*gengo.Tag, error) {
44 tags, err := gengo.ExtractFunctionStyleCommentTags("+", []string{tagName}, comments)
45 if err != nil {
46 return nil, err
47 }
48 if len(tags) == 0 {
49 return nil, nil
50 }
51 if len(tags) > 1 {
52 return nil, fmt.Errorf("multiple %s tags found", tagName)
53 }
54 tag := tags[tagName]
55 if len(tag) == 0 {
56 return nil, nil
57 }
58 if len(tag) > 1 {
59 klog.V(5).Infof("multiple %s tags found, using the first one", tagName)
60 }
61 value := tag[0]
62 return &value, nil
63 }
64
65 // genSchemaName produces a file with autogenerated openapi schema name functions.
66 type genSchemaName struct {
67 generator.GoGenerator
68 targetPackage string
69 imports namer.ImportTracker
70 typesForInit []*types.Type
71 openAPISchemaNamePackage string
72 }
73
74 // NewSchemaNameGen creates a generator
75 func NewSchemaNameGen(outputFilename, targetPackage string, openAPISchemaNamePackage string) generator.Generator {
76 return &genSchemaName{
77 GoGenerator: generator.GoGenerator{
78 OutputFilename: outputFilename,
79 },
80 targetPackage: targetPackage,
81 imports: generator.NewImportTracker(),
82 typesForInit: make([]*types.Type, 0),
83 openAPISchemaNamePackage: openAPISchemaNamePackage,
84 }
85 }
86
87 func (g *genSchemaName) Namers(c *generator.Context) namer.NameSystems {
88 return namer.NameSystems{
89 "public": namer.NewPublicNamer(1),
90 "local": namer.NewPublicNamer(0),
91 "raw": namer.NewRawNamer("", nil),
92 }
93 }
94
95 func (g *genSchemaName) Filter(c *generator.Context, t *types.Type) bool {
96 // Filter out types not being processed or not copyable within the package.
97 if !isSchemaNameType(t) {
98 klog.V(2).Infof("Type %v is not a valid target for OpenAPI schema name", t)
99 return false
100 }
101 g.typesForInit = append(g.typesForInit, t)
102 return true
103 }
104
105 // isSchemaNameType indicates whether or not a type could be used to serve an API.
106 func isSchemaNameType(t *types.Type) bool {
107 // Filter out private types.
108 if namer.IsPrivateGoName(t.Name.Name) {
109 return false
110 }
111
112 for t.Kind == types.Alias {
113 t = t.Underlying
114 }
115
116 if t.Kind != types.Struct {
117 return false
118 }
119 return true
120 }
121
122 func (g *genSchemaName) isOtherPackage(pkg string) bool {
123 if pkg == g.targetPackage {
124 return false
125 }
126 if strings.HasSuffix(pkg, ""+g.targetPackage+"") {
127 return false
128 }
129 return true
130 }
131
132 func (g *genSchemaName) Imports(c *generator.Context) (imports []string) {
133 importLines := []string{}
134 for _, singleImport := range g.imports.ImportLines() {
135 if g.isOtherPackage(singleImport) {
136 importLines = append(importLines, singleImport)
137 }
138 }
139 return importLines
140 }
141
142 func (g *genSchemaName) Init(c *generator.Context, w io.Writer) error {
143 return nil
144 }
145
146 func (g *genSchemaName) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
147 klog.V(3).Infof("Generating openapi schema name for type %v", t)
148
149 openAPISchemaNamePackage := g.openAPISchemaNamePackage
150 v, err := singularTag(tagModelPackage, t.CommentLines)
151 if err != nil {
152 return fmt.Errorf("type %v: invalid %s:%v", t.Name, tagModelPackage, err)
153 }
154 if v != nil && v.Value != "" {
155 openAPISchemaNamePackage = v.Value
156 }
157
158 if openAPISchemaNamePackage == "" {
159 return nil
160 }
161
162 schemaName := openAPISchemaNamePackage + "." + t.Name.Name
163
164 a := map[string]interface{}{
165 "type": t,
166 "schemaName": schemaName,
167 }
168
169 sw := generator.NewSnippetWriter(w, c, "$", "$")
170
171 sw.Do("// OpenAPIModelName returns the OpenAPI model name for this type.\n", a)
172 sw.Do("func (in $.type|local$) OpenAPIModelName() string {\n", a)
173 sw.Do("\treturn \"$.schemaName$\"\n", a)
174 sw.Do("}\n\n", nil)
175
176 return sw.Error()
177 }