| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 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 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 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 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 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 |
|
| 126 |
|
| 127 |
|
| 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 |
|
| 135 |
|
| 136 |
|
| 137 |
} |
| 138 |
|
| 139 |
|
| 140 |
|
| 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 |
|
| 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 |
|
| 227 |
|
| 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 |
|
| 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 |
|
| 301 |
func (c commentTags) ValidateType(t *types.Type) error { |
| 302 |
var err error |
| 303 |
|
| 304 |
resolvedType := resolveAliasAndPtrType(t) |
| 305 |
typeString, _ := openapi.OpenAPITypeFormat(resolvedType.String()) |
| 306 |
|
| 307 |
|
| 308 |
|
| 309 |
if resolvedType.Kind == types.Interface || resolvedType.Kind == types.Struct { |
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
|
| 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 |
|
| 419 |
|
| 420 |
|
| 421 |
|
| 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 |
|
| 433 |
|
| 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 |
|
| 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 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
|
| 470 |
|
| 471 |
|
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
|
| 479 |
|
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
|
| 484 |
|
| 485 |
|
| 486 |
|
| 487 |
|
| 488 |
|
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
func extractCommentTags(marker string, lines []string) (map[string]string, error) { |
| 494 |
out := map[string]string{} |
| 495 |
|
| 496 |
|
| 497 |
|
| 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 |
|
| 508 |
|
| 509 |
previousKey := lastKey |
| 510 |
previousArrayKey := lastArrayKey |
| 511 |
previousIndex := lastIndex |
| 512 |
|
| 513 |
|
| 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 |
|
| 534 |
|
| 535 |
|
| 536 |
|
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
|
| 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 |
|
| 558 |
if existing, exists := out[key]; !exists { |
| 559 |
|
| 560 |
|
| 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 |
|
| 569 |
|
| 570 |
return nil, fmt.Errorf("concatenations to key '%s' must be consecutive with its assignment", key) |
| 571 |
} else { |
| 572 |
|
| 573 |
|
| 574 |
|
| 575 |
|
| 576 |
|
| 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 |
|
| 592 |
|
| 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 |
|
| 600 |
|
| 601 |
|
| 602 |
if arrayPath, index, hasSubscript, err := extractArraySubscript(key); hasSubscript { |
| 603 |
|
| 604 |
|
| 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 |
|
| 626 |
|
| 627 |
|
| 628 |
|
| 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 |
|
| 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 |
|
| 646 |
continue |
| 647 |
} else if len(value) == 0 { |
| 648 |
|
| 649 |
result[key] = true |
| 650 |
} else if err := json.Unmarshal([]byte(value), &unmarshalled); err != nil { |
| 651 |
|
| 652 |
return nil, fmt.Errorf("failed to parse value for key %v as JSON: %w", key, err) |
| 653 |
} else { |
| 654 |
|
| 655 |
result[key] = unmarshalled |
| 656 |
} |
| 657 |
} |
| 658 |
return result, nil |
| 659 |
} |
| 660 |
|
| 661 |
|
| 662 |
|
| 663 |
|
| 664 |
|
| 665 |
|
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
|
| 671 |
|
| 672 |
|
| 673 |
|
| 674 |
|
| 675 |
|
| 676 |
|
| 677 |
|
| 678 |
|
| 679 |
|
| 680 |
|
| 681 |
|
| 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 |
|
| 702 |
|
| 703 |
|
| 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 |
|
| 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 |
|
| 722 |
|
| 723 |
return fmt.Errorf("expected []any at key %v, got %T", key, existing) |
| 724 |
} else if index >= len(existing) { |
| 725 |
|
| 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 |
|
| 734 |
|
| 735 |
|
| 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 |
|
| 743 |
if putNestedValue(dst, rest, v); err != nil { |
| 744 |
return err |
| 745 |
} |
| 746 |
} else { |
| 747 |
|
| 748 |
|
| 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 |
|
| 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 |
|
| 767 |
|
| 768 |
return fmt.Errorf("expected map[string]any at key %v, got %T", key, existing) |
| 769 |
} |
| 770 |
} |
| 771 |
|
| 772 |
|
| 773 |
|
| 774 |
|
| 775 |
|
| 776 |
|
| 777 |
|
| 778 |
|
| 779 |
|
| 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 |
} |