Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions pkg/crd/markers/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ var FieldOnlyMarkers = []*definitionWithHelp{
must(markers.MakeDefinition("optional", markers.DescribesField, struct{}{})).
WithHelp(markers.SimpleHelp("CRD validation", "specifies that this field is optional, if fields are required by default.")),

must(markers.MakeDefinition("kubebuilder:validation:OneOf", markers.DescribesField, struct{}{})).
WithHelp(markers.SimpleHelp("CRD validation", "specifies that this field is part of a oneOf group")),

must(markers.MakeDefinition("nullable", markers.DescribesField, Nullable{})).
WithHelp(Nullable{}.Help()),

Expand Down
20 changes: 16 additions & 4 deletions pkg/crd/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -378,22 +378,34 @@ func structToSchema(ctx *schemaContext, structType *ast.StructType) *apiext.JSON
defaultMode = "optional"
}

fieldMarkedOptional := (field.Markers.Get("kubebuilder:validation:Optional") != nil || field.Markers.Get("optional") != nil)
fieldMarkedRequired := (field.Markers.Get("kubebuilder:validation:Required") != nil)
fieldMarkedOneOf := (field.Markers.Get("kubebuilder:validation:OneOf") != nil)

switch defaultMode {
// if this package isn't set to optional default...
case "required":
// ...everything that's not inline, omitempty, or explicitly optional is required
if !inline && !omitEmpty && field.Markers.Get("kubebuilder:validation:Optional") == nil && field.Markers.Get("optional") == nil {
// ...everything that's not inline, not omitempty, not part of a oneOf group, and not explicitly optional is required
if !inline && !omitEmpty && !fieldMarkedOneOf && !fieldMarkedOptional {
props.Required = append(props.Required, fieldName)
}

// if this package isn't set to required default...
case "optional":
// ...everything that isn't explicitly required is optional
if field.Markers.Get("kubebuilder:validation:Required") != nil {
// ...everything that's part of a oneOf group, or not explicitly required is optional
if !fieldMarkedOneOf && fieldMarkedRequired {
props.Required = append(props.Required, fieldName)
}
}

// process oneOf groups
if field.Markers.Get("kubebuilder:validation:OneOf") != nil {
props.OneOf = append(props.OneOf, apiext.JSONSchemaProps{
Properties: map[string]apiext.JSONSchemaProps{fieldName: {}},
Required: []string{fieldName},
})
}

var propSchema *apiext.JSONSchemaProps
if field.Markers.Get(crdmarkers.SchemalessName) != nil {
propSchema = &apiext.JSONSchemaProps{}
Expand Down