diff --git a/pkg/document/selectors.go b/pkg/document/selectors.go index e4367c49c..5f2029d6d 100644 --- a/pkg/document/selectors.go +++ b/pkg/document/selectors.go @@ -1,6 +1,7 @@ package document import ( + "fmt" "strings" "sigs.k8s.io/kustomize/v3/pkg/gvk" @@ -64,6 +65,39 @@ func (s Selector) ByAnnotation(annotationSelector string) Selector { return s } +// String is a convenience function which dumps all relevant information about a Selector in the following format: +// [Key1=Value1, Key2=Value2, ...] +func (s Selector) String() string { + var components []string + if s.Group != "" { + components = append(components, fmt.Sprintf("Group=%q", s.Group)) + } + if s.Version != "" { + components = append(components, fmt.Sprintf("Version=%q", s.Version)) + } + if s.Kind != "" { + components = append(components, fmt.Sprintf("Kind=%q", s.Kind)) + } + if s.Namespace != "" { + components = append(components, fmt.Sprintf("Namespace=%q", s.Namespace)) + } + if s.Name != "" { + components = append(components, fmt.Sprintf("Name=%q", s.Name)) + } + if s.AnnotationSelector != "" { + components = append(components, fmt.Sprintf("Annotations=%q", s.AnnotationSelector)) + } + if s.LabelSelector != "" { + components = append(components, fmt.Sprintf("Labels=%q", s.LabelSelector)) + } + + if len(components) == 0 { + return "No selection conditions specified" + } + + return fmt.Sprintf("[%s]", strings.Join(components, ", ")) +} + // NewEphemeralCloudDataSelector returns selector to get BaremetalHost for ephemeral node func NewEphemeralCloudDataSelector() Selector { return NewSelector().ByKind(SecretKind).ByLabel(EphemeralUserDataSelector) diff --git a/pkg/document/selectors_test.go b/pkg/document/selectors_test.go index 949221f94..5d7b81913 100644 --- a/pkg/document/selectors_test.go +++ b/pkg/document/selectors_test.go @@ -78,3 +78,41 @@ func TestSelectorsSkip(t *testing.T) { } }) } + +func TestSelectorString(t *testing.T) { + tests := []struct { + name string + selector document.Selector + expected string + }{ + { + name: "unconditional", + selector: document.Selector{}, + expected: "No selection conditions specified", + }, + { + name: "by-name", + selector: document.NewSelector().ByName("foo"), + expected: `[Name="foo"]`, + }, + { + name: "by-all", + selector: document.NewSelector(). + ByGvk("testGroup", "testVersion", "testKind"). + ByNamespace("testNamespace"). + ByName("testName"). + ByAnnotation("testAnnotation=true"). + ByLabel("testLabel=true"), + expected: `[Group="testGroup", Version="testVersion", Kind="testKind", ` + + `Namespace="testNamespace", Name="testName", ` + + `Annotations="testAnnotation=true", Labels="testLabel=true"]`, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expected, tt.selector.String()) + }) + } +}