item.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. Copyright 2024 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 validate
  14. import (
  15. "context"
  16. "k8s.io/apimachinery/pkg/api/operation"
  17. "k8s.io/apimachinery/pkg/util/validation/field"
  18. )
  19. // MatchItemFn takes a pointer to an item and returns true if it matches the criteria.
  20. type MatchItemFn[T any] func(*T) bool
  21. // SliceItem finds the first item in newList that satisfies the match function,
  22. // and if found, also looks for a matching item in oldList. If the value of the
  23. // item is the same as the previous value, as per the equiv function, then no
  24. // validation is performed. Otherwise, it invokes 'itemValidator' on these items.
  25. //
  26. // This function processes only the *first* matching item found in newList. It
  27. // assumes that the match functions targets a unique identifier (primary key)
  28. // and will match at most one element per list. If this assumption is violated,
  29. // changes in list order can lead this function to have inconsistent behavior.
  30. //
  31. // The fldPath passed to itemValidator is indexed to the matched item's
  32. // position in newList.
  33. //
  34. // This function does not validate items that were removed (present in oldList
  35. // but not in newList).
  36. func SliceItem[TList ~[]TItem, TItem any](
  37. ctx context.Context, op operation.Operation, fldPath *field.Path,
  38. newList, oldList TList,
  39. matches MatchItemFn[TItem],
  40. equiv MatchFunc[TItem],
  41. itemValidator func(ctx context.Context, op operation.Operation, fldPath *field.Path, newObj, oldObj *TItem) field.ErrorList,
  42. ) field.ErrorList {
  43. var matchedNew, matchedOld *TItem
  44. var newIndex int
  45. for i := range newList {
  46. if matches(&newList[i]) {
  47. matchedNew = &newList[i]
  48. newIndex = i
  49. break
  50. }
  51. }
  52. if matchedNew == nil {
  53. return nil
  54. }
  55. for i := range oldList {
  56. if matches(&oldList[i]) {
  57. matchedOld = &oldList[i]
  58. break
  59. }
  60. }
  61. if op.Type == operation.Update && matchedOld != nil && equiv(*matchedNew, *matchedOld) {
  62. return nil
  63. }
  64. return itemValidator(ctx, op, fldPath.Index(newIndex), matchedNew, matchedOld)
  65. }