object-names.go 2.0 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 cache
  14. import (
  15. "k8s.io/apimachinery/pkg/types"
  16. )
  17. // ObjectName is a reference to an object of some implicit kind
  18. type ObjectName struct {
  19. Namespace string
  20. Name string
  21. }
  22. // NewObjectName constructs a new one
  23. func NewObjectName(namespace, name string) ObjectName {
  24. return ObjectName{Namespace: namespace, Name: name}
  25. }
  26. // Parts is the inverse of the constructor
  27. func (objName ObjectName) Parts() (namespace, name string) {
  28. return objName.Namespace, objName.Name
  29. }
  30. // String returns the standard string encoding,
  31. // which is designed to match the historical behavior of MetaNamespaceKeyFunc.
  32. // Note this behavior is different from the String method of types.NamespacedName.
  33. func (objName ObjectName) String() string {
  34. if len(objName.Namespace) > 0 {
  35. return objName.Namespace + "/" + objName.Name
  36. }
  37. return objName.Name
  38. }
  39. // ParseObjectName tries to parse the standard encoding
  40. func ParseObjectName(str string) (ObjectName, error) {
  41. var objName ObjectName
  42. var err error
  43. objName.Namespace, objName.Name, err = SplitMetaNamespaceKey(str)
  44. return objName, err
  45. }
  46. // NamespacedNameAsObjectName rebrands the given NamespacedName as an ObjectName
  47. func NamespacedNameAsObjectName(nn types.NamespacedName) ObjectName {
  48. return NewObjectName(nn.Namespace, nn.Name)
  49. }
  50. // AsNamespacedName rebrands as a NamespacedName
  51. func (objName ObjectName) AsNamespacedName() types.NamespacedName {
  52. return types.NamespacedName{Namespace: objName.Namespace, Name: objName.Name}
  53. }