-
Notifications
You must be signed in to change notification settings - Fork 229
Add model name generator #563
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,177 @@ | ||
/* | ||
Copyright 2025 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 generators | ||
|
||
import ( | ||
"fmt" | ||
"io" | ||
"strings" | ||
|
||
"k8s.io/gengo/v2" | ||
"k8s.io/gengo/v2/generator" | ||
"k8s.io/gengo/v2/namer" | ||
"k8s.io/gengo/v2/types" | ||
"k8s.io/klog/v2" | ||
) | ||
|
||
const ( | ||
tagModelPackage = "k8s:openapi-model-package" | ||
) | ||
|
||
func extractOpenAPISchemaNamePackage(comments []string) (string, error) { | ||
v, err := singularTag(tagModelPackage, comments) | ||
if v == nil || err != nil { | ||
return "", err | ||
} | ||
return v.Value, nil | ||
} | ||
|
||
func singularTag(tagName string, comments []string) (*gengo.Tag, error) { | ||
tags, err := gengo.ExtractFunctionStyleCommentTags("+", []string{tagName}, comments) | ||
if err != nil { | ||
return nil, err | ||
} | ||
if len(tags) == 0 { | ||
return nil, nil | ||
} | ||
if len(tags) > 1 { | ||
return nil, fmt.Errorf("multiple %s tags found", tagName) | ||
} | ||
tag := tags[tagName] | ||
if len(tag) == 0 { | ||
return nil, nil | ||
} | ||
if len(tag) > 1 { | ||
klog.V(5).Infof("multiple %s tags found, using the first one", tagName) | ||
} | ||
value := tag[0] | ||
return &value, nil | ||
} | ||
|
||
// genSchemaName produces a file with autogenerated openapi schema name functions. | ||
type genSchemaName struct { | ||
generator.GoGenerator | ||
targetPackage string | ||
imports namer.ImportTracker | ||
typesForInit []*types.Type | ||
openAPISchemaNamePackage string | ||
} | ||
|
||
// NewSchemaNameGen creates a generator | ||
func NewSchemaNameGen(outputFilename, targetPackage string, openAPISchemaNamePackage string) generator.Generator { | ||
return &genSchemaName{ | ||
GoGenerator: generator.GoGenerator{ | ||
OutputFilename: outputFilename, | ||
}, | ||
targetPackage: targetPackage, | ||
imports: generator.NewImportTracker(), | ||
typesForInit: make([]*types.Type, 0), | ||
openAPISchemaNamePackage: openAPISchemaNamePackage, | ||
} | ||
} | ||
|
||
func (g *genSchemaName) Namers(c *generator.Context) namer.NameSystems { | ||
return namer.NameSystems{ | ||
"public": namer.NewPublicNamer(1), | ||
"local": namer.NewPublicNamer(0), | ||
"raw": namer.NewRawNamer("", nil), | ||
} | ||
} | ||
|
||
func (g *genSchemaName) Filter(c *generator.Context, t *types.Type) bool { | ||
// Filter out types not being processed or not copyable within the package. | ||
if !isSchemaNameType(t) { | ||
klog.V(2).Infof("Type %v is not a valid target for OpenAPI schema name", t) | ||
return false | ||
} | ||
g.typesForInit = append(g.typesForInit, t) | ||
return true | ||
} | ||
|
||
// isSchemaNameType indicates whether or not a type could be used to serve an API. | ||
func isSchemaNameType(t *types.Type) bool { | ||
// Filter out private types. | ||
if namer.IsPrivateGoName(t.Name.Name) { | ||
return false | ||
} | ||
|
||
for t.Kind == types.Alias { | ||
t = t.Underlying | ||
} | ||
|
||
if t.Kind != types.Struct { | ||
return false | ||
} | ||
return true | ||
} | ||
|
||
func (g *genSchemaName) isOtherPackage(pkg string) bool { | ||
if pkg == g.targetPackage { | ||
return false | ||
} | ||
if strings.HasSuffix(pkg, ""+g.targetPackage+"") { | ||
return false | ||
} | ||
return true | ||
} | ||
|
||
func (g *genSchemaName) Imports(c *generator.Context) (imports []string) { | ||
importLines := []string{} | ||
for _, singleImport := range g.imports.ImportLines() { | ||
if g.isOtherPackage(singleImport) { | ||
importLines = append(importLines, singleImport) | ||
} | ||
} | ||
return importLines | ||
} | ||
|
||
func (g *genSchemaName) Init(c *generator.Context, w io.Writer) error { | ||
return nil | ||
} | ||
|
||
func (g *genSchemaName) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error { | ||
klog.V(3).Infof("Generating openapi schema name for type %v", t) | ||
|
||
openAPISchemaNamePackage := g.openAPISchemaNamePackage | ||
v, err := singularTag(tagModelPackage, t.CommentLines) | ||
if err != nil { | ||
return fmt.Errorf("type %v: invalid %s:%v", t.Name, tagModelPackage, err) | ||
} | ||
if v != nil && v.Value != "" { | ||
openAPISchemaNamePackage = v.Value | ||
} | ||
|
||
if openAPISchemaNamePackage == "" { | ||
return nil | ||
} | ||
|
||
schemaName := openAPISchemaNamePackage + "." + t.Name.Name | ||
|
||
a := map[string]interface{}{ | ||
"type": t, | ||
"schemaName": schemaName, | ||
} | ||
|
||
sw := generator.NewSnippetWriter(w, c, "$", "$") | ||
|
||
sw.Do("// OpenAPIModelName returns the OpenAPI model name for this type.\n", a) | ||
sw.Do("func (in $.type|local$) OpenAPIModelName() string {\n", a) | ||
sw.Do("\treturn \"$.schemaName$\"\n", a) | ||
sw.Do("}\n\n", nil) | ||
|
||
return sw.Error() | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why not output to the same file?
EDIT: Oh I see. 1 Generator -> 1 file. Probably not worth changing, but IMO outputting to a single file would be cleaner, if we run across similar things in other generators. Unless there's a reason this is better that I am missing.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is one file for the generated openapi definition, and there are N files for all the zz_geneated.model_name.go files, one for each package containing types that need this function added. Those files are very similar to deep copy generated files.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
OH RIGHT. Nevermind me :)