-
Notifications
You must be signed in to change notification settings - Fork 16
feat: add GetX/SetX accessors to generated Go models #160
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
Open
erikmiller-gusto
wants to merge
1
commit into
crossplane:main
Choose a base branch
from
erikmiller-gusto:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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
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
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,161 @@ | ||
| /* | ||
| Copyright 2026 The Crossplane 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 generator | ||
|
|
||
| import ( | ||
| "go/ast" | ||
| "go/format" | ||
| "go/parser" | ||
| "go/token" | ||
| "strings" | ||
|
|
||
| "github.com/crossplane/crossplane-runtime/v2/pkg/errors" | ||
| ) | ||
|
|
||
| // accessorReceiver is the receiver variable name used by generated accessor | ||
| // methods. A single letter cannot collide with any generated package import | ||
| // alias, which are all multi-letter. | ||
| const accessorReceiver = "o" | ||
|
|
||
| // addAccessors generates GetX/SetX accessor methods for every field of every | ||
| // struct type declared in the given Go source. Getters return the field's | ||
| // (pointer) type as-is and setters take the same type, so the generated methods | ||
| // reference only types already present in the file and never require new | ||
| // imports. Type aliases are skipped: their Type is not a struct literal, so they | ||
| // share the underlying struct's method set for free. | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| func addAccessors(code string) (string, error) { | ||
| fset := token.NewFileSet() | ||
| f, err := parser.ParseFile(fset, "", code, parser.ParseComments) | ||
| if err != nil { | ||
| return "", errors.Wrap(err, "failed to parse Go code for accessors") | ||
| } | ||
|
|
||
| // Collect the methods that already exist on each type, so we never emit a | ||
| // GetX/SetX that collides with a method oapi-codegen already generated | ||
| // (e.g. GetAdditionalProperties, or union As/From/Merge helpers). A | ||
| // duplicate method would make the package fail to compile. | ||
| existing := collectExistingMethods(f) | ||
|
|
||
| var b strings.Builder | ||
| // Walk declarations in source order so the generated output is stable. | ||
| for _, decl := range f.Decls { | ||
| gen, ok := decl.(*ast.GenDecl) | ||
| if !ok || gen.Tok != token.TYPE { | ||
| continue | ||
| } | ||
| for _, spec := range gen.Specs { | ||
| ts, ok := spec.(*ast.TypeSpec) | ||
| if !ok { | ||
| continue | ||
| } | ||
| // Skip type aliases (`type Foo = Bar`); only generate accessors for | ||
| // struct type definitions. | ||
| if ts.Assign.IsValid() { | ||
| continue | ||
| } | ||
| st, ok := ts.Type.(*ast.StructType) | ||
| if !ok || st.Fields == nil { | ||
| continue | ||
| } | ||
| writeStructAccessors(&b, fset, ts.Name.Name, st, existing[ts.Name.Name]) | ||
| } | ||
| } | ||
|
|
||
| if b.Len() == 0 { | ||
| return code, nil | ||
| } | ||
|
|
||
| combined := code + "\n" + b.String() | ||
| formatted, err := format.Source([]byte(combined)) | ||
| if err != nil { | ||
| return "", errors.Wrap(err, "failed to format generated accessors") | ||
| } | ||
| return string(formatted), nil | ||
| } | ||
|
|
||
| // collectExistingMethods returns, per receiver type name, the set of method | ||
| // names already declared in the file. | ||
| func collectExistingMethods(f *ast.File) map[string]map[string]bool { | ||
| existing := map[string]map[string]bool{} | ||
| for _, decl := range f.Decls { | ||
| fn, ok := decl.(*ast.FuncDecl) | ||
| if !ok || fn.Recv == nil || len(fn.Recv.List) != 1 { | ||
| continue | ||
| } | ||
| recv := receiverTypeName(fn.Recv.List[0].Type) | ||
| if recv == "" { | ||
| continue | ||
| } | ||
| if existing[recv] == nil { | ||
| existing[recv] = map[string]bool{} | ||
| } | ||
| existing[recv][fn.Name.Name] = true | ||
| } | ||
| return existing | ||
| } | ||
|
|
||
| // receiverTypeName returns the bare type name of a method receiver, stripping a | ||
| // leading pointer if present (e.g. `*Foo` -> `Foo`). | ||
| func receiverTypeName(e ast.Expr) string { | ||
| if star, ok := e.(*ast.StarExpr); ok { | ||
| e = star.X | ||
| } | ||
| if id, ok := e.(*ast.Ident); ok { | ||
| return id.Name | ||
| } | ||
| return "" | ||
| } | ||
|
|
||
| // writeStructAccessors appends a getter and setter for each named field of the | ||
| // given struct to b. Any accessor whose name already exists in skip is omitted | ||
| // to avoid colliding with methods oapi-codegen already generated. | ||
| func writeStructAccessors(b *strings.Builder, fset *token.FileSet, typeName string, st *ast.StructType, skip map[string]bool) { | ||
| for _, field := range st.Fields.List { | ||
| // Skip embedded/anonymous fields; generated models don't use them. | ||
| if len(field.Names) == 0 { | ||
| continue | ||
| } | ||
|
|
||
| var typ strings.Builder | ||
| if err := format.Node(&typ, fset, field.Type); err != nil { | ||
| // format.Node only fails on malformed nodes, which cannot occur for | ||
| // a node we just parsed; skip defensively rather than panic. | ||
| continue | ||
| } | ||
| fieldType := typ.String() | ||
|
|
||
| for _, name := range field.Names { | ||
| fieldName := name.Name | ||
|
|
||
| // Getter. | ||
| if !skip["Get"+fieldName] { | ||
| b.WriteString("\n// Get" + fieldName + " returns the " + fieldName + " field.\n") | ||
| b.WriteString("func (" + accessorReceiver + " *" + typeName + ") Get" + fieldName + "() " + fieldType + " {\n") | ||
| b.WriteString("\treturn " + accessorReceiver + "." + fieldName + "\n") | ||
| b.WriteString("}\n") | ||
| } | ||
|
|
||
| // Setter. | ||
| if !skip["Set"+fieldName] { | ||
| b.WriteString("\n// Set" + fieldName + " sets the " + fieldName + " field.\n") | ||
| b.WriteString("func (" + accessorReceiver + " *" + typeName + ") Set" + fieldName + "(v " + fieldType + ") {\n") | ||
| b.WriteString("\t" + accessorReceiver + "." + fieldName + " = v\n") | ||
| b.WriteString("}\n") | ||
| } | ||
| } | ||
| } | ||
| } | ||
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.
🩺 Stability & Availability | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
Repository: crossplane/cli
Length of output: 152
Binding
cfgis correct, but adding a nil guard prevents future panicsThe search confirms
build,run, andgeneraterely on thekong.Bind(cfg)at line 130, and no direct.Run()calls were found in tests, so the current path is safe.However, to make these commands robust against future programmatic invocation or test changes where Kong might not inject
cfg:Runmethods incmd/crossplane/project/build.go,cmd/crossplane/project/run.go, andcmd/crossplane/function/generate.go.cfgis nil to avoid a panic oncfg.Featuresaccess.This defensive pattern ensures the command fails gracefully with a clear message rather than crashing silently if called outside the Kong pipeline.
🤖 Prompt for AI Agents