util.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. Copyright 2022 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package util
  14. import (
  15. "reflect"
  16. "k8s.io/kube-openapi/pkg/schemamutation"
  17. "k8s.io/kube-openapi/pkg/validation/spec"
  18. )
  19. // wrapRefs wraps OpenAPI V3 Schema refs that contain sibling elements.
  20. // AllOf is used to wrap the Ref to prevent references from having sibling elements
  21. // Please see https://github.com/kubernetes/kubernetes/issues/106387#issuecomment-967640388
  22. func WrapRefs(schema *spec.Schema) *spec.Schema {
  23. walker := schemamutation.Walker{
  24. SchemaCallback: func(schema *spec.Schema) *spec.Schema {
  25. orig := schema
  26. clone := func() {
  27. if orig == schema {
  28. schema = new(spec.Schema)
  29. *schema = *orig
  30. }
  31. }
  32. if schema.Ref.String() != "" && !reflect.DeepEqual(*schema, spec.Schema{SchemaProps: spec.SchemaProps{Ref: schema.Ref}}) {
  33. clone()
  34. refSchema := new(spec.Schema)
  35. refSchema.Ref = schema.Ref
  36. schema.Ref = spec.Ref{}
  37. schema.AllOf = []spec.Schema{*refSchema}
  38. }
  39. return schema
  40. },
  41. RefCallback: schemamutation.RefCallbackNoop,
  42. }
  43. return walker.WalkSchema(schema)
  44. }