| 1 |
/* |
| 2 |
Copyright 2022 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 |
"encoding/json" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"reflect" |
| 24 |
"regexp" |
| 25 |
"strconv" |
| 26 |
"strings" |
| 27 |
"sync" |
| 28 |
|
| 29 |
"k8s.io/gengo/v2/types" |
| 30 |
openapi "k8s.io/kube-openapi/pkg/common" |
| 31 |
"k8s.io/kube-openapi/pkg/validation/spec" |
| 32 |
) |
| 33 |
|
| 34 |
type CELTag struct { |
| 35 |
Rule string `json:"rule,omitempty"` |
| 36 |
Message string `json:"message,omitempty"` |
| 37 |
MessageExpression string `json:"messageExpression,omitempty"` |
| 38 |
OptionalOldSelf *bool `json:"optionalOldSelf,omitempty"` |
| 39 |
Reason string `json:"reason,omitempty"` |
| 40 |
FieldPath string `json:"fieldPath,omitempty"` |
| 41 |
} |
| 42 |
|
| 43 |
func (c *CELTag) Validate() error { |
| 44 |
if c == nil || *c == (CELTag{}) { |
| 45 |
return fmt.Errorf("empty CEL tag is not allowed") |
| 46 |
} |
| 47 |
|
| 48 |
var errs []error |
| 49 |
if c.Rule == "" { |
| 50 |
errs = append(errs, fmt.Errorf("rule cannot be empty")) |
| 51 |
} |
| 52 |
if c.Message == "" && c.MessageExpression == "" { |
| 53 |
errs = append(errs, fmt.Errorf("message or messageExpression must be set")) |
| 54 |
} |
| 55 |
if c.Message != "" && c.MessageExpression != "" { |
| 56 |
errs = append(errs, fmt.Errorf("message and messageExpression cannot be set at the same time")) |
| 57 |
} |
| 58 |
|
| 59 |
if len(errs) > 0 { |
| 60 |
return errors.Join(errs...) |
| 61 |
} |
| 62 |
|
| 63 |
return nil |
| 64 |
} |
| 65 |
|
| 66 |
// isKnownTagCommentKey returns true if the given key is a known comment tag key. |
| 67 |
// Known keys are identified by the json field tags in the commentTags struct. |
| 68 |
// If the key is a composite key, only the first key part is checked, and is |
| 69 |
// expected to be separated by the remainder of the key by a ':' or '[' delimiter. |
| 70 |
func isKnownTagCommentKey(key string) bool { |
| 71 |
split := func(r rune) bool { return r == ':' || r == '[' } |
| 72 |
commentTags := strings.FieldsFunc(key, split) |
| 73 |
if len(commentTags) == 0 { |
| 74 |
return false |
| 75 |
} |
| 76 |
_, ok := tagKeys()[commentTags[0]] |
| 77 |
return ok |
| 78 |
} |
| 79 |
|
| 80 |
var tagKeys = sync.OnceValue(func() map[string]struct{} { |
| 81 |
result := map[string]struct{}{} |
| 82 |
t := reflect.TypeOf(commentTags{}) |
| 83 |
for i := 0; i < t.NumField(); i++ { |
| 84 |
field := t.Field(i) |
| 85 |
if jsonTag := field.Tag.Get("json"); jsonTag != "" { |
| 86 |
if key, _, _ := strings.Cut(jsonTag, ","); key != "" { |
| 87 |
result[key] = struct{}{} |
| 88 |
} |
| 89 |
} |
| 90 |
} |
| 91 |
return result |
| 92 |
}) |
| 93 |
|
| 94 |
// commentTags represents the parsed comment tags for a given type. These types are then used to generate schema validations. |
| 95 |
// These only include the newer prefixed tags. The older tags are still supported, |
| 96 |
// but are not included in this struct. Comment Tags are transformed into a |
| 97 |
// *spec.Schema, which is then combined with the older marker comments to produce |
| 98 |
// the generated OpenAPI spec. |
| 99 |
// |
| 100 |
// List of tags not included in this struct: |
| 101 |
// |
| 102 |
// - +optional |
| 103 |
// - +default |
| 104 |
// - +listType |
| 105 |
// - +listMapKeys |
| 106 |
// - +mapType |
| 107 |
type commentTags struct { |
| 108 |
Nullable *bool `json:"nullable,omitempty"` |
| 109 |
Format *string `json:"format,omitempty"` |
| 110 |
Maximum *float64 `json:"maximum,omitempty"` |
| 111 |
ExclusiveMaximum *bool `json:"exclusiveMaximum,omitempty"` |
| 112 |
Minimum *float64 `json:"minimum,omitempty"` |
| 113 |
ExclusiveMinimum *bool `json:"exclusiveMinimum,omitempty"` |
| 114 |
MaxLength *int64 `json:"maxLength,omitempty"` |
| 115 |
MinLength *int64 `json:"minLength,omitempty"` |
| 116 |
Pattern *string `json:"pattern,omitempty"` |
| 117 |
MaxItems *int64 `json:"maxItems,omitempty"` |
| 118 |
MinItems *int64 `json:"minItems,omitempty"` |
| 119 |
UniqueItems *bool `json:"uniqueItems,omitempty"` |
| 120 |
MultipleOf *float64 `json:"multipleOf,omitempty"` |
| 121 |
Enum []interface{} `json:"enum,omitempty"` |
| 122 |
MaxProperties *int64 `json:"maxProperties,omitempty"` |
| 123 |
MinProperties *int64 `json:"minProperties,omitempty"` |
| 124 |
|
| 125 |
// Nested commentTags for extending the schemas of subfields at point-of-use |
| 126 |
// when you cant annotate them directly. Cannot be used to add properties |
| 127 |
// or remove validations on the overridden schema. |
| 128 |
Items *commentTags `json:"items,omitempty"` |
| 129 |
Properties map[string]*commentTags `json:"properties,omitempty"` |
| 130 |
AdditionalProperties *commentTags `json:"additionalProperties,omitempty"` |
| 131 |
|
| 132 |
CEL []CELTag `json:"cel,omitempty"` |
| 133 |
|
| 134 |
// Future markers can all be parsed into this centralized struct... |
| 135 |
// Optional bool `json:"optional,omitempty"` |
| 136 |
// Default any `json:"default,omitempty"` |
| 137 |
} |
| 138 |
|
| 139 |
// Returns the schema for the given CommentTags instance. |
| 140 |
// This is the final authoritative schema for the comment tags |
| 141 |
func (c *commentTags) ValidationSchema() (*spec.Schema, error) { |
| 142 |
if c == nil { |
| 143 |
return nil, nil |
| 144 |
} |
| 145 |
|
| 146 |
isNullable := c.Nullable != nil && *c.Nullable |
| 147 |
format := "" |
| 148 |
if c.Format != nil { |
| 149 |
format = *c.Format |
| 150 |
} |
| 151 |
isExclusiveMaximum := c.ExclusiveMaximum != nil && *c.ExclusiveMaximum |
| 152 |
isExclusiveMinimum := c.ExclusiveMinimum != nil && *c.ExclusiveMinimum |
| 153 |
isUniqueItems := c.UniqueItems != nil && *c.UniqueItems |
| 154 |
pattern := "" |
| 155 |
if c.Pattern != nil { |
| 156 |
pattern = *c.Pattern |
| 157 |
} |
| 158 |
|
| 159 |
var transformedItems *spec.SchemaOrArray |
| 160 |
var transformedProperties map[string]spec.Schema |
| 161 |
var transformedAdditionalProperties *spec.SchemaOrBool |
| 162 |
|
| 163 |
if c.Items != nil { |
| 164 |
items, err := c.Items.ValidationSchema() |
| 165 |
if err != nil { |
| 166 |
return nil, fmt.Errorf("failed to transform items: %w", err) |
| 167 |
} |
| 168 |
transformedItems = &spec.SchemaOrArray{Schema: items} |
| 169 |
} |
| 170 |
|
| 171 |
if c.Properties != nil { |
| 172 |
properties := make(map[string]spec.Schema) |
| 173 |
for key, value := range c.Properties { |
| 174 |
property, err := value.ValidationSchema() |
| 175 |
if err != nil { |
| 176 |
return nil, fmt.Errorf("failed to transform property %q: %w", key, err) |
| 177 |
} |
| 178 |
properties[key] = *property |
| 179 |
} |
| 180 |
transformedProperties = properties |
| 181 |
} |
| 182 |
|
| 183 |
if c.AdditionalProperties != nil { |
| 184 |
additionalProperties, err := c.AdditionalProperties.ValidationSchema() |
| 185 |
if err != nil { |
| 186 |
return nil, fmt.Errorf("failed to transform additionalProperties: %w", err) |
| 187 |
} |
| 188 |
transformedAdditionalProperties = &spec.SchemaOrBool{Schema: additionalProperties, Allows: true} |
| 189 |
} |
| 190 |
|
| 191 |
res := spec.Schema{ |
| 192 |
SchemaProps: spec.SchemaProps{ |
| 193 |
Nullable: isNullable, |
| 194 |
Format: format, |
| 195 |
Maximum: c.Maximum, |
| 196 |
ExclusiveMaximum: isExclusiveMaximum, |
| 197 |
Minimum: c.Minimum, |
| 198 |
ExclusiveMinimum: isExclusiveMinimum, |
| 199 |
MaxLength: c.MaxLength, |
| 200 |
MinLength: c.MinLength, |
| 201 |
Pattern: pattern, |
| 202 |
MaxItems: c.MaxItems, |
| 203 |
MinItems: c.MinItems, |
| 204 |
UniqueItems: isUniqueItems, |
| 205 |
MultipleOf: c.MultipleOf, |
| 206 |
Enum: c.Enum, |
| 207 |
MaxProperties: c.MaxProperties, |
| 208 |
MinProperties: c.MinProperties, |
| 209 |
}, |
| 210 |
} |
| 211 |
|
| 212 |
if len(c.CEL) > 0 { |
| 213 |
// Convert the CELTag to a map[string]interface{} via JSON |
| 214 |
celTagJSON, err := json.Marshal(c.CEL) |
| 215 |
if err != nil { |
| 216 |
return nil, fmt.Errorf("failed to marshal CEL tag: %w", err) |
| 217 |
} |
| 218 |
var celTagMap []interface{} |
| 219 |
if err := json.Unmarshal(celTagJSON, &celTagMap); err != nil { |
| 220 |
return nil, fmt.Errorf("failed to unmarshal CEL tag: %w", err) |
| 221 |
} |
| 222 |
|
| 223 |
res.VendorExtensible.AddExtension("x-kubernetes-validations", celTagMap) |
| 224 |
} |
| 225 |
|
| 226 |
// Dont add structural properties directly to this schema. This schema |
| 227 |
// is used only for validation. |
| 228 |
if transformedItems != nil || len(transformedProperties) > 0 || transformedAdditionalProperties != nil { |
| 229 |
res.AllOf = append(res.AllOf, spec.Schema{ |
| 230 |
SchemaProps: spec.SchemaProps{ |
| 231 |
Items: transformedItems, |
| 232 |
Properties: transformedProperties, |
| 233 |
AdditionalProperties: transformedAdditionalProperties, |
| 234 |
}, |
| 235 |
}) |
| 236 |
} |
| 237 |
|
| 238 |
return &res, nil |
| 239 |
} |
| 240 |
|
| 241 |
// validates the parameters in a CommentTags instance. Returns any errors encountered. |
| 242 |
func (c commentTags) Validate() error { |
| 243 |
|
| 244 |
var err error |
| 245 |
|
| 246 |
if c.MinLength != nil && *c.MinLength < 0 { |
| 247 |
err = errors.Join(err, fmt.Errorf("minLength cannot be negative")) |
| 248 |
} |
| 249 |
if c.MaxLength != nil && *c.MaxLength < 0 { |
| 250 |
err = errors.Join(err, fmt.Errorf("maxLength cannot be negative")) |
| 251 |
} |
| 252 |
if c.MinItems != nil && *c.MinItems < 0 { |
| 253 |
err = errors.Join(err, fmt.Errorf("minItems cannot be negative")) |
| 254 |
} |
| 255 |
if c.MaxItems != nil && *c.MaxItems < 0 { |
| 256 |
err = errors.Join(err, fmt.Errorf("maxItems cannot be negative")) |
| 257 |
} |
| 258 |
if c.MinProperties != nil && *c.MinProperties < 0 { |
| 259 |
err = errors.Join(err, fmt.Errorf("minProperties cannot be negative")) |
| 260 |
} |
| 261 |
if c.MaxProperties != nil && *c.MaxProperties < 0 { |
| 262 |
err = errors.Join(err, fmt.Errorf("maxProperties cannot be negative")) |
| 263 |
} |
| 264 |
if c.Minimum != nil && c.Maximum != nil && *c.Minimum > *c.Maximum { |
| 265 |
err = errors.Join(err, fmt.Errorf("minimum %f is greater than maximum %f", *c.Minimum, *c.Maximum)) |
| 266 |
} |
| 267 |
if (c.ExclusiveMinimum != nil || c.ExclusiveMaximum != nil) && c.Minimum != nil && c.Maximum != nil && *c.Minimum == *c.Maximum { |
| 268 |
err = errors.Join(err, fmt.Errorf("exclusiveMinimum/Maximum cannot be set when minimum == maximum")) |
| 269 |
} |
| 270 |
if c.MinLength != nil && c.MaxLength != nil && *c.MinLength > *c.MaxLength { |
| 271 |
err = errors.Join(err, fmt.Errorf("minLength %d is greater than maxLength %d", *c.MinLength, *c.MaxLength)) |
| 272 |
} |
| 273 |
if c.MinItems != nil && c.MaxItems != nil && *c.MinItems > *c.MaxItems { |
| 274 |
err = errors.Join(err, fmt.Errorf("minItems %d is greater than maxItems %d", *c.MinItems, *c.MaxItems)) |
| 275 |
} |
| 276 |
if c.MinProperties != nil && c.MaxProperties != nil && *c.MinProperties > *c.MaxProperties { |
| 277 |
err = errors.Join(err, fmt.Errorf("minProperties %d is greater than maxProperties %d", *c.MinProperties, *c.MaxProperties)) |
| 278 |
} |
| 279 |
if c.Pattern != nil { |
| 280 |
_, e := regexp.Compile(*c.Pattern) |
| 281 |
if e != nil { |
| 282 |
err = errors.Join(err, fmt.Errorf("invalid pattern %q: %v", *c.Pattern, e)) |
| 283 |
} |
| 284 |
} |
| 285 |
if c.MultipleOf != nil && *c.MultipleOf == 0 { |
| 286 |
err = errors.Join(err, fmt.Errorf("multipleOf cannot be 0")) |
| 287 |
} |
| 288 |
|
| 289 |
for i, celTag := range c.CEL { |
| 290 |
celError := celTag.Validate() |
| 291 |
if celError == nil { |
| 292 |
continue |
| 293 |
} |
| 294 |
err = errors.Join(err, fmt.Errorf("invalid CEL tag at index %d: %w", i, celError)) |
| 295 |
} |
| 296 |
|
| 297 |
return err |
| 298 |
} |
| 299 |
|
| 300 |
// Performs type-specific validation for CommentTags porameters. Accepts a Type instance and returns any errors encountered during validation. |
| 301 |
func (c commentTags) ValidateType(t *types.Type) error { |
| 302 |
var err error |
| 303 |
|
| 304 |
resolvedType := resolveAliasAndPtrType(t) |
| 305 |
typeString, _ := openapi.OpenAPITypeFormat(resolvedType.String()) // will be empty for complicated types |
| 306 |
|
| 307 |
// Structs and interfaces may dynamically be any type, so we cant validate them |
| 308 |
// easily. |
| 309 |
if resolvedType.Kind == types.Interface || resolvedType.Kind == types.Struct { |
| 310 |
// Skip validation for structs and interfaces which implement custom |
| 311 |
// overrides |
| 312 |
// |
| 313 |
// Only check top-level t type without resolving alias to mirror generator |
| 314 |
// behavior. Generator only checks the top level type without resolving |
| 315 |
// alias. The `has*Method` functions can be changed to add this behavior in the |
| 316 |
// future if needed. |
| 317 |
elemT := resolvePtrType(t) |
| 318 |
if hasOpenAPIDefinitionMethod(elemT) || |
| 319 |
hasOpenAPIDefinitionMethods(elemT) || |
| 320 |
hasOpenAPIV3DefinitionMethod(elemT) || |
| 321 |
hasOpenAPIV3OneOfMethod(elemT) { |
| 322 |
|
| 323 |
return nil |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
isArray := resolvedType.Kind == types.Slice || resolvedType.Kind == types.Array |
| 328 |
isMap := resolvedType.Kind == types.Map |
| 329 |
isString := typeString == "string" |
| 330 |
isInt := typeString == "integer" |
| 331 |
isFloat := typeString == "number" |
| 332 |
isStruct := resolvedType.Kind == types.Struct |
| 333 |
|
| 334 |
if c.MaxItems != nil && !isArray { |
| 335 |
err = errors.Join(err, fmt.Errorf("maxItems can only be used on array types")) |
| 336 |
} |
| 337 |
if c.MinItems != nil && !isArray { |
| 338 |
err = errors.Join(err, fmt.Errorf("minItems can only be used on array types")) |
| 339 |
} |
| 340 |
if c.UniqueItems != nil && !isArray { |
| 341 |
err = errors.Join(err, fmt.Errorf("uniqueItems can only be used on array types")) |
| 342 |
} |
| 343 |
if c.MaxProperties != nil && !(isMap || isStruct) { |
| 344 |
err = errors.Join(err, fmt.Errorf("maxProperties can only be used on map types")) |
| 345 |
} |
| 346 |
if c.MinProperties != nil && !(isMap || isStruct) { |
| 347 |
err = errors.Join(err, fmt.Errorf("minProperties can only be used on map types")) |
| 348 |
} |
| 349 |
if c.MinLength != nil && !isString { |
| 350 |
err = errors.Join(err, fmt.Errorf("minLength can only be used on string types")) |
| 351 |
} |
| 352 |
if c.MaxLength != nil && !isString { |
| 353 |
err = errors.Join(err, fmt.Errorf("maxLength can only be used on string types")) |
| 354 |
} |
| 355 |
if c.Pattern != nil && !isString { |
| 356 |
err = errors.Join(err, fmt.Errorf("pattern can only be used on string types")) |
| 357 |
} |
| 358 |
if c.Minimum != nil && !isInt && !isFloat { |
| 359 |
err = errors.Join(err, fmt.Errorf("minimum can only be used on numeric types")) |
| 360 |
} |
| 361 |
if c.Maximum != nil && !isInt && !isFloat { |
| 362 |
err = errors.Join(err, fmt.Errorf("maximum can only be used on numeric types")) |
| 363 |
} |
| 364 |
if c.MultipleOf != nil && !isInt && !isFloat { |
| 365 |
err = errors.Join(err, fmt.Errorf("multipleOf can only be used on numeric types")) |
| 366 |
} |
| 367 |
if c.ExclusiveMinimum != nil && !isInt && !isFloat { |
| 368 |
err = errors.Join(err, fmt.Errorf("exclusiveMinimum can only be used on numeric types")) |
| 369 |
} |
| 370 |
if c.ExclusiveMaximum != nil && !isInt && !isFloat { |
| 371 |
err = errors.Join(err, fmt.Errorf("exclusiveMaximum can only be used on numeric types")) |
| 372 |
} |
| 373 |
if c.AdditionalProperties != nil && !isMap { |
| 374 |
err = errors.Join(err, fmt.Errorf("additionalProperties can only be used on map types")) |
| 375 |
|
| 376 |
if err == nil { |
| 377 |
err = errors.Join(err, c.AdditionalProperties.ValidateType(t)) |
| 378 |
} |
| 379 |
} |
| 380 |
if c.Items != nil && !isArray { |
| 381 |
err = errors.Join(err, fmt.Errorf("items can only be used on array types")) |
| 382 |
|
| 383 |
if err == nil { |
| 384 |
err = errors.Join(err, c.Items.ValidateType(t)) |
| 385 |
} |
| 386 |
} |
| 387 |
if c.Properties != nil { |
| 388 |
if !isStruct && !isMap { |
| 389 |
err = errors.Join(err, fmt.Errorf("properties can only be used on struct types")) |
| 390 |
} else if isStruct && err == nil { |
| 391 |
for key, tags := range c.Properties { |
| 392 |
if member := memberWithJSONName(resolvedType, key); member == nil { |
| 393 |
err = errors.Join(err, fmt.Errorf("property used in comment tag %q not found in struct %s", key, resolvedType.String())) |
| 394 |
} else if nestedErr := tags.ValidateType(member.Type); nestedErr != nil { |
| 395 |
err = errors.Join(err, fmt.Errorf("failed to validate property %q: %w", key, nestedErr)) |
| 396 |
} |
| 397 |
} |
| 398 |
} |
| 399 |
} |
| 400 |
|
| 401 |
return err |
| 402 |
} |
| 403 |
|
| 404 |
func memberWithJSONName(t *types.Type, key string) *types.Member { |
| 405 |
for _, member := range t.Members { |
| 406 |
tags := getJsonTags(&member) |
| 407 |
if len(tags) > 0 && tags[0] == key { |
| 408 |
return &member |
| 409 |
} else if member.Embedded { |
| 410 |
if embeddedMember := memberWithJSONName(member.Type, key); embeddedMember != nil { |
| 411 |
return embeddedMember |
| 412 |
} |
| 413 |
} |
| 414 |
} |
| 415 |
return nil |
| 416 |
} |
| 417 |
|
| 418 |
// ParseCommentTags parses the given comments into a CommentTags type. Validates the parsed comment tags, and returns the result. |
| 419 |
// Accepts an optional type to validate against, and a prefix to filter out markers not related to validation. |
| 420 |
// Accepts a prefix to filter out markers not related to validation. |
| 421 |
// Returns any errors encountered while parsing or validating the comment tags. |
| 422 |
func ParseCommentTags(t *types.Type, comments []string, prefix string) (*spec.Schema, error) { |
| 423 |
markers, err := parseMarkers(comments, prefix) |
| 424 |
if err != nil { |
| 425 |
return nil, fmt.Errorf("failed to parse marker comments: %w", err) |
| 426 |
} |
| 427 |
nested, err := nestMarkers(markers) |
| 428 |
if err != nil { |
| 429 |
return nil, fmt.Errorf("invalid marker comments: %w", err) |
| 430 |
} |
| 431 |
|
| 432 |
// Parse the map into a CommentTags type by marshalling and unmarshalling |
| 433 |
// as JSON in leiu of an unstructured converter. |
| 434 |
out, err := json.Marshal(nested) |
| 435 |
if err != nil { |
| 436 |
return nil, fmt.Errorf("failed to marshal marker comments: %w", err) |
| 437 |
} |
| 438 |
|
| 439 |
var commentTags commentTags |
| 440 |
if err = json.Unmarshal(out, &commentTags); err != nil { |
| 441 |
return nil, fmt.Errorf("failed to unmarshal marker comments: %w", err) |
| 442 |
} |
| 443 |
|
| 444 |
// Validate the parsed comment tags |
| 445 |
validationErrors := commentTags.Validate() |
| 446 |
|
| 447 |
if t != nil { |
| 448 |
validationErrors = errors.Join(validationErrors, commentTags.ValidateType(t)) |
| 449 |
} |
| 450 |
|
| 451 |
if validationErrors != nil { |
| 452 |
return nil, fmt.Errorf("invalid marker comments: %w", validationErrors) |
| 453 |
} |
| 454 |
|
| 455 |
return commentTags.ValidationSchema() |
| 456 |
} |
| 457 |
|
| 458 |
var ( |
| 459 |
allowedKeyCharacterSet = `[:_a-zA-Z0-9\[\]\-]` |
| 460 |
valueEmpty = regexp.MustCompile(fmt.Sprintf(`^(%s*)$`, allowedKeyCharacterSet)) |
| 461 |
valueAssign = regexp.MustCompile(fmt.Sprintf(`^(%s*)=(.*)$`, allowedKeyCharacterSet)) |
| 462 |
valueRawString = regexp.MustCompile(fmt.Sprintf(`^(%s*)>(.*)$`, allowedKeyCharacterSet)) |
| 463 |
) |
| 464 |
|
| 465 |
// extractCommentTags parses comments for lines of the form: |
| 466 |
// |
| 467 |
// 'marker' + "key=value" |
| 468 |
// |
| 469 |
// or to specify truthy boolean keys: |
| 470 |
// |
| 471 |
// 'marker' + "key" |
| 472 |
// |
| 473 |
// Values are optional; "" is the default. A tag can be specified more than |
| 474 |
// one time and all values are returned. Returns a map with an entry for |
| 475 |
// for each key and a value. |
| 476 |
// |
| 477 |
// Similar to version from gengo, but this version support only allows one |
| 478 |
// value per key (preferring explicit array indices), supports raw strings |
| 479 |
// with concatenation, and limits the usable characters allowed in a key |
| 480 |
// (for simpler parsing). |
| 481 |
// |
| 482 |
// Assignments and empty values have the same syntax as from gengo. Raw strings |
| 483 |
// have the syntax: |
| 484 |
// |
| 485 |
// 'marker' + "key>value" |
| 486 |
// 'marker' + "key>value" |
| 487 |
// |
| 488 |
// Successive usages of the same raw string key results in concatenating each |
| 489 |
// line with `\n` in between. It is an error to use `=` to assing to a previously |
| 490 |
// assigned key |
| 491 |
// (in contrast to types.ExtractCommentTags which allows array-typed |
| 492 |
// values to be specified using `=`). |
| 493 |
func extractCommentTags(marker string, lines []string) (map[string]string, error) { |
| 494 |
out := map[string]string{} |
| 495 |
|
| 496 |
// Used to track the the line immediately prior to the one being iterated. |
| 497 |
// If there was an invalid or ignored line, these values get reset. |
| 498 |
lastKey := "" |
| 499 |
lastIndex := -1 |
| 500 |
lastArrayKey := "" |
| 501 |
|
| 502 |
var lintErrors []error |
| 503 |
|
| 504 |
for _, line := range lines { |
| 505 |
line = strings.Trim(line, " ") |
| 506 |
|
| 507 |
// Track the current value of the last vars to use in this loop iteration |
| 508 |
// before they are reset for the next iteration. |
| 509 |
previousKey := lastKey |
| 510 |
previousArrayKey := lastArrayKey |
| 511 |
previousIndex := lastIndex |
| 512 |
|
| 513 |
// Make sure last vars gets reset if we `continue` |
| 514 |
lastIndex = -1 |
| 515 |
lastArrayKey = "" |
| 516 |
lastKey = "" |
| 517 |
|
| 518 |
if len(line) == 0 { |
| 519 |
continue |
| 520 |
} else if !strings.HasPrefix(line, marker) { |
| 521 |
continue |
| 522 |
} |
| 523 |
|
| 524 |
line = strings.TrimPrefix(line, marker) |
| 525 |
|
| 526 |
key := "" |
| 527 |
value := "" |
| 528 |
|
| 529 |
if matches := valueAssign.FindStringSubmatch(line); matches != nil { |
| 530 |
key = matches[1] |
| 531 |
value = matches[2] |
| 532 |
|
| 533 |
// If key exists, throw error. |
| 534 |
// Some of the old kube open-api gen marker comments like |
| 535 |
// `+listMapKeys` allowed a list to be specified by writing key=value |
| 536 |
// multiple times. |
| 537 |
// |
| 538 |
// This is not longer supported for the prefixed marker comments. |
| 539 |
// This is to prevent confusion with the new array syntax which |
| 540 |
// supports lists of objects. |
| 541 |
// |
| 542 |
// The old marker comments like +listMapKeys will remain functional, |
| 543 |
// but new markers will not support it. |
| 544 |
if _, ok := out[key]; ok { |
| 545 |
return nil, fmt.Errorf("cannot have multiple values for key '%v'", key) |
| 546 |
} |
| 547 |
|
| 548 |
} else if matches := valueEmpty.FindStringSubmatch(line); matches != nil { |
| 549 |
key = matches[1] |
| 550 |
value = "" |
| 551 |
|
| 552 |
} else if matches := valueRawString.FindStringSubmatch(line); matches != nil { |
| 553 |
toAdd := strings.Trim(string(matches[2]), " ") |
| 554 |
|
| 555 |
key = matches[1] |
| 556 |
|
| 557 |
// First usage as a raw string. |
| 558 |
if existing, exists := out[key]; !exists { |
| 559 |
|
| 560 |
// Encode the raw string as JSON to ensure that it is properly escaped. |
| 561 |
valueBytes, err := json.Marshal(toAdd) |
| 562 |
if err != nil { |
| 563 |
return nil, fmt.Errorf("invalid value for key %v: %w", key, err) |
| 564 |
} |
| 565 |
|
| 566 |
value = string(valueBytes) |
| 567 |
} else if key != previousKey { |
| 568 |
// Successive usages of the same key of a raw string must be |
| 569 |
// consecutive |
| 570 |
return nil, fmt.Errorf("concatenations to key '%s' must be consecutive with its assignment", key) |
| 571 |
} else { |
| 572 |
// If it is a consecutive repeat usage, concatenate to the |
| 573 |
// existing value. |
| 574 |
// |
| 575 |
// Decode JSON string, append to it, re-encode JSON string. |
| 576 |
// Kinda janky but this is a code-generator... |
| 577 |
var unmarshalled string |
| 578 |
if err := json.Unmarshal([]byte(existing), &unmarshalled); err != nil { |
| 579 |
return nil, fmt.Errorf("invalid value for key %v: %w", key, err) |
| 580 |
} else { |
| 581 |
unmarshalled += "\n" + toAdd |
| 582 |
valueBytes, err := json.Marshal(unmarshalled) |
| 583 |
if err != nil { |
| 584 |
return nil, fmt.Errorf("invalid value for key %v: %w", key, err) |
| 585 |
} |
| 586 |
|
| 587 |
value = string(valueBytes) |
| 588 |
} |
| 589 |
} |
| 590 |
} else { |
| 591 |
// Comment has the correct prefix, but incorrect syntax, so it is an |
| 592 |
// error |
| 593 |
return nil, fmt.Errorf("invalid marker comment does not match expected `+key=<json formatted value>` pattern: %v", line) |
| 594 |
} |
| 595 |
|
| 596 |
out[key] = value |
| 597 |
lastKey = key |
| 598 |
|
| 599 |
// Lint the array subscript for common mistakes. This only lints the last |
| 600 |
// array index used, (since we do not have a need for nested arrays yet |
| 601 |
// in markers) |
| 602 |
if arrayPath, index, hasSubscript, err := extractArraySubscript(key); hasSubscript { |
| 603 |
// If index is non-zero, check that that previous line was for the same |
| 604 |
// key and either the same or previous index |
| 605 |
if err != nil { |
| 606 |
lintErrors = append(lintErrors, fmt.Errorf("error parsing %v: expected integer index in key '%v'", line, key)) |
| 607 |
} else if previousArrayKey != arrayPath && index != 0 { |
| 608 |
lintErrors = append(lintErrors, fmt.Errorf("error parsing %v: non-consecutive index %v for key '%v'", line, index, arrayPath)) |
| 609 |
} else if index != previousIndex+1 && index != previousIndex { |
| 610 |
lintErrors = append(lintErrors, fmt.Errorf("error parsing %v: non-consecutive index %v for key '%v'", line, index, arrayPath)) |
| 611 |
} |
| 612 |
|
| 613 |
lastIndex = index |
| 614 |
lastArrayKey = arrayPath |
| 615 |
} |
| 616 |
} |
| 617 |
|
| 618 |
if len(lintErrors) > 0 { |
| 619 |
return nil, errors.Join(lintErrors...) |
| 620 |
} |
| 621 |
|
| 622 |
return out, nil |
| 623 |
} |
| 624 |
|
| 625 |
// Extracts and parses the given marker comments into a map of key -> value. |
| 626 |
// Accepts a prefix to filter out markers not related to validation. |
| 627 |
// The prefix is removed from the key in the returned map. |
| 628 |
// Empty keys and invalid values will return errors, refs are currently unsupported and will be skipped. |
| 629 |
func parseMarkers(markerComments []string, prefix string) (map[string]any, error) { |
| 630 |
markers, err := extractCommentTags(prefix, markerComments) |
| 631 |
if err != nil { |
| 632 |
return nil, err |
| 633 |
} |
| 634 |
|
| 635 |
// Parse the values as JSON |
| 636 |
result := map[string]any{} |
| 637 |
for key, value := range markers { |
| 638 |
var unmarshalled interface{} |
| 639 |
|
| 640 |
if len(key) == 0 { |
| 641 |
return nil, fmt.Errorf("cannot have empty key for marker comment") |
| 642 |
} else if !isKnownTagCommentKey(key) { |
| 643 |
continue |
| 644 |
} else if _, ok := parseSymbolReference(value, ""); ok { |
| 645 |
// Skip ref markers |
| 646 |
continue |
| 647 |
} else if len(value) == 0 { |
| 648 |
// Empty value means key is implicitly a bool |
| 649 |
result[key] = true |
| 650 |
} else if err := json.Unmarshal([]byte(value), &unmarshalled); err != nil { |
| 651 |
// Not valid JSON, throw error |
| 652 |
return nil, fmt.Errorf("failed to parse value for key %v as JSON: %w", key, err) |
| 653 |
} else { |
| 654 |
// Is is valid JSON, use as a JSON value |
| 655 |
result[key] = unmarshalled |
| 656 |
} |
| 657 |
} |
| 658 |
return result, nil |
| 659 |
} |
| 660 |
|
| 661 |
// Converts a map of: |
| 662 |
// |
| 663 |
// "a:b:c": 1 |
| 664 |
// "a:b:d": 2 |
| 665 |
// "a:e": 3 |
| 666 |
// "f": 4 |
| 667 |
// |
| 668 |
// Into: |
| 669 |
// |
| 670 |
// map[string]any{ |
| 671 |
// "a": map[string]any{ |
| 672 |
// "b": map[string]any{ |
| 673 |
// "c": 1, |
| 674 |
// "d": 2, |
| 675 |
// }, |
| 676 |
// "e": 3, |
| 677 |
// }, |
| 678 |
// "f": 4, |
| 679 |
// } |
| 680 |
// |
| 681 |
// Returns a list of joined errors for any invalid keys. See putNestedValue for more details. |
| 682 |
func nestMarkers(markers map[string]any) (map[string]any, error) { |
| 683 |
nested := make(map[string]any) |
| 684 |
var errs []error |
| 685 |
for key, value := range markers { |
| 686 |
var err error |
| 687 |
keys := strings.Split(key, ":") |
| 688 |
|
| 689 |
if err = putNestedValue(nested, keys, value); err != nil { |
| 690 |
errs = append(errs, err) |
| 691 |
} |
| 692 |
} |
| 693 |
|
| 694 |
if len(errs) > 0 { |
| 695 |
return nil, errors.Join(errs...) |
| 696 |
} |
| 697 |
|
| 698 |
return nested, nil |
| 699 |
} |
| 700 |
|
| 701 |
// Recursively puts a value into the given keypath, creating intermediate maps |
| 702 |
// and slices as needed. If a key is of the form `foo[bar]`, then bar will be |
| 703 |
// treated as an index into the array foo. If bar is not a valid integer, putNestedValue returns an error. |
| 704 |
func putNestedValue(m map[string]any, k []string, v any) error { |
| 705 |
if len(k) == 0 { |
| 706 |
return nil |
| 707 |
} |
| 708 |
|
| 709 |
key := k[0] |
| 710 |
rest := k[1:] |
| 711 |
|
| 712 |
// Array case |
| 713 |
if arrayKeyWithoutSubscript, index, hasSubscript, err := extractArraySubscript(key); err != nil { |
| 714 |
return fmt.Errorf("error parsing subscript for key %v: %w", key, err) |
| 715 |
} else if hasSubscript { |
| 716 |
key = arrayKeyWithoutSubscript |
| 717 |
var arrayDestination []any |
| 718 |
if existing, ok := m[key]; !ok { |
| 719 |
arrayDestination = make([]any, index+1) |
| 720 |
} else if existing, ok := existing.([]any); !ok { |
| 721 |
// Error case. Existing isn't of correct type. Can happen if |
| 722 |
// someone is subscripting a field that was previously not an array |
| 723 |
return fmt.Errorf("expected []any at key %v, got %T", key, existing) |
| 724 |
} else if index >= len(existing) { |
| 725 |
// Ensure array is big enough |
| 726 |
arrayDestination = append(existing, make([]any, index-len(existing)+1)...) |
| 727 |
} else { |
| 728 |
arrayDestination = existing |
| 729 |
} |
| 730 |
|
| 731 |
m[key] = arrayDestination |
| 732 |
if arrayDestination[index] == nil { |
| 733 |
// Doesn't exist case, create the destination. |
| 734 |
// Assumes the destination is a map for now. Theoretically could be |
| 735 |
// extended to support arrays of arrays, but that's not needed yet. |
| 736 |
destination := make(map[string]any) |
| 737 |
arrayDestination[index] = destination |
| 738 |
if err = putNestedValue(destination, rest, v); err != nil { |
| 739 |
return err |
| 740 |
} |
| 741 |
} else if dst, ok := arrayDestination[index].(map[string]any); ok { |
| 742 |
// Already exists case, correct type |
| 743 |
if putNestedValue(dst, rest, v); err != nil { |
| 744 |
return err |
| 745 |
} |
| 746 |
} else { |
| 747 |
// Already exists, incorrect type. Error |
| 748 |
// This shouldn't be possible. |
| 749 |
return fmt.Errorf("expected map at %v[%v], got %T", key, index, arrayDestination[index]) |
| 750 |
} |
| 751 |
|
| 752 |
return nil |
| 753 |
} else if len(rest) == 0 { |
| 754 |
// Base case. Single key. Just set into destination |
| 755 |
m[key] = v |
| 756 |
return nil |
| 757 |
} |
| 758 |
|
| 759 |
if existing, ok := m[key]; !ok { |
| 760 |
destination := make(map[string]any) |
| 761 |
m[key] = destination |
| 762 |
return putNestedValue(destination, rest, v) |
| 763 |
} else if destination, ok := existing.(map[string]any); ok { |
| 764 |
return putNestedValue(destination, rest, v) |
| 765 |
} else { |
| 766 |
// Error case. Existing isn't of correct type. Can happen if prior comment |
| 767 |
// referred to value as an error |
| 768 |
return fmt.Errorf("expected map[string]any at key %v, got %T", key, existing) |
| 769 |
} |
| 770 |
} |
| 771 |
|
| 772 |
// extractArraySubscript extracts the left array subscript from a key of |
| 773 |
// the form `foo[bar][baz]` -> "bar". |
| 774 |
// Returns the key without the subscript, the index, and a bool indicating if |
| 775 |
// the key had a subscript. |
| 776 |
// If the key has a subscript, but the subscript is not a valid integer, returns an error. |
| 777 |
// |
| 778 |
// This can be adapted to support multidimensional subscripts probably fairly |
| 779 |
// easily by retuning a list of ints |
| 780 |
func extractArraySubscript(str string) (string, int, bool, error) { |
| 781 |
subscriptIdx := strings.Index(str, "[") |
| 782 |
if subscriptIdx == -1 { |
| 783 |
return "", -1, false, nil |
| 784 |
} |
| 785 |
|
| 786 |
subscript := strings.Split(str[subscriptIdx+1:], "]")[0] |
| 787 |
if len(subscript) == 0 { |
| 788 |
return "", -1, false, fmt.Errorf("empty subscript not allowed") |
| 789 |
} |
| 790 |
|
| 791 |
index, err := strconv.Atoi(subscript) |
| 792 |
if err != nil { |
| 793 |
return "", -1, false, fmt.Errorf("expected integer index in key %v", str) |
| 794 |
} else if index < 0 { |
| 795 |
return "", -1, false, fmt.Errorf("subscript '%v' is invalid. index must be positive", subscript) |
| 796 |
} |
| 797 |
|
| 798 |
return str[:subscriptIdx], index, true, nil |
| 799 |
} |