Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions pkg/analysis/arrayofstruct/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"go/ast"

"golang.org/x/tools/go/analysis"

kalerrors "sigs.k8s.io/kube-api-linter/pkg/analysis/errors"
"sigs.k8s.io/kube-api-linter/pkg/analysis/helpers/extractjsontags"
"sigs.k8s.io/kube-api-linter/pkg/analysis/helpers/inspector"
Expand Down Expand Up @@ -74,6 +75,13 @@ func checkField(pass *analysis.Pass, field *ast.Field, markersAccess markershelp
return
}

// Check if the struct has union markers that satisfy the required constraint
if hasExactlyOneOfMarker(structType, markersAccess) {
// ExactlyOneOf marker enforces that exactly one field is set,
// so we don't need to report an error
return
}

// Check if at least one field in the struct has a required marker
if hasRequiredField(structType, markersAccess) {
return
Expand Down Expand Up @@ -208,3 +216,16 @@ func hasRequiredField(structType *ast.StructType, markersAccess markershelper.Ma

return false
}

// hasExactlyOneOfMarker checks if the struct has an ExactlyOneOf marker,
// which satisfies the required field constraint by ensuring exactly one field is set.
func hasExactlyOneOfMarker(structType *ast.StructType, markersAccess markershelper.Markers) bool {
if structType == nil {
return false
}

// Use StructMarkers to get the set of markers on the struct
markerSet := markersAccess.StructMarkers(structType)

return markerSet.Has("kubebuilder:validation:ExactlyOneOf")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add this to the markers package alongside all of the other constants

It will also need to be included in the init to register the marker with the marker registry

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added ExactlyOneOf to markers package and registered in init(),

}
11 changes: 11 additions & 0 deletions pkg/analysis/arrayofstruct/testdata/src/a/a.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,14 @@ type ValidStructWithCustomBasicType struct {
// This should not trigger the linter because CustomString is based on string, a basic type
Items []CustomString
}

// Valid case - struct with ExactlyOneOf marker
type ValidWithExactlyOneOf struct {
Items []ValidExactlyOneOfItem
}

// +kubebuilder:validation:ExactlyOneOf=FieldA;FieldB
type ValidExactlyOneOfItem struct {
FieldA *string `json:"fieldA,omitempty"`
FieldB *string `json:"fieldB,omitempty"`
}