serialization.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. Copyright 2023 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 internal
  14. import (
  15. "github.com/go-openapi/jsonreference"
  16. jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json"
  17. )
  18. // DeterministicMarshal calls the jsonv2 library with the deterministic
  19. // flag in order to have stable marshaling.
  20. func DeterministicMarshal(in any) ([]byte, error) {
  21. return jsonv2.MarshalOptions{Deterministic: true}.Marshal(jsonv2.EncodeOptions{}, in)
  22. }
  23. // JSONRefFromMap populates a json reference object if the map v contains a $ref key.
  24. func JSONRefFromMap(jsonRef *jsonreference.Ref, v map[string]interface{}) error {
  25. if v == nil {
  26. return nil
  27. }
  28. if vv, ok := v["$ref"]; ok {
  29. if str, ok := vv.(string); ok {
  30. ref, err := jsonreference.New(str)
  31. if err != nil {
  32. return err
  33. }
  34. *jsonRef = ref
  35. }
  36. }
  37. return nil
  38. }
  39. // SanitizeExtensions sanitizes the input map such that non extension
  40. // keys (non x-*, X-*) keys are dropped from the map. Returns the new
  41. // modified map, or nil if the map is now empty.
  42. func SanitizeExtensions(e map[string]interface{}) map[string]interface{} {
  43. for k := range e {
  44. if !IsExtensionKey(k) {
  45. delete(e, k)
  46. }
  47. }
  48. if len(e) == 0 {
  49. e = nil
  50. }
  51. return e
  52. }
  53. // IsExtensionKey returns true if the input string is of format x-* or X-*
  54. func IsExtensionKey(k string) bool {
  55. return len(k) > 1 && (k[0] == 'x' || k[0] == 'X') && k[1] == '-'
  56. }