lastapplied.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 internal
  14. import (
  15. "fmt"
  16. "k8s.io/apimachinery/pkg/api/meta"
  17. apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation"
  18. "k8s.io/apimachinery/pkg/runtime"
  19. )
  20. // LastAppliedConfigAnnotation is the annotation used to store the previous
  21. // configuration of a resource for use in a three way diff by UpdateApplyAnnotation.
  22. //
  23. // This is a copy of the corev1 annotation since we don't want to depend on the whole package.
  24. const LastAppliedConfigAnnotation = "kubectl.kubernetes.io/last-applied-configuration"
  25. // SetLastApplied sets the last-applied annotation the given value in
  26. // the object.
  27. func SetLastApplied(obj runtime.Object, value string) error {
  28. accessor, err := meta.Accessor(obj)
  29. if err != nil {
  30. panic(fmt.Sprintf("couldn't get accessor: %v", err))
  31. }
  32. var annotations = accessor.GetAnnotations()
  33. if annotations == nil {
  34. annotations = map[string]string{}
  35. }
  36. annotations[LastAppliedConfigAnnotation] = value
  37. if err := apimachineryvalidation.ValidateAnnotationsSize(annotations); err != nil {
  38. delete(annotations, LastAppliedConfigAnnotation)
  39. }
  40. accessor.SetAnnotations(annotations)
  41. return nil
  42. }