Skip to content

Commit

Permalink
implement TrackableFilter with labels
Browse files Browse the repository at this point in the history
This updates the labels filter to implement the TrackableFilter
interface by reusing the TrackableSetter abstraction provided by
filtersutil.

This is done to provide a generic and consistent experience across the
filters
  • Loading branch information
sdowell committed Jan 20, 2022
1 parent 3fcec5f commit e939be6
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 14 deletions.
19 changes: 6 additions & 13 deletions api/filters/labels/labels.go
Expand Up @@ -21,22 +21,15 @@ type Filter struct {
// FsSlice identifies the label fields.
FsSlice types.FsSlice

// SetEntryCallback is invoked each time a label is applied
// Example use cases:
// - Tracking all paths where labels have been applied
SetEntryCallback func(key, value, tag string, node *yaml.RNode)
setter filtersutil.TrackableSetter
}

var _ kio.Filter = Filter{}
var _ kio.TrackableFilter = &Filter{}

func (f Filter) setEntry(key, value, tag string) filtersutil.SetFn {
baseSetEntryFunc := filtersutil.SetEntry(key, value, tag)
return func(node *yaml.RNode) error {
if f.SetEntryCallback != nil {
f.SetEntryCallback(key, value, tag, node)
}
return baseSetEntryFunc(node)
}
// WithMutationTracker registers a callback which will be invoked each time a field is mutated
func (f *Filter) WithMutationTracker(callback func(key, value, tag string, node *yaml.RNode)) {
f.setter.WithMutationTracker(callback)
}

func (f Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
Expand All @@ -46,7 +39,7 @@ func (f Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
for _, k := range keys {
if err := node.PipeE(fsslice.Filter{
FsSlice: f.FsSlice,
SetValue: f.setEntry(
SetValue: f.setter.SetEntry(
k, f.Labels[k], yaml.NodeTagString),
CreateKind: yaml.MappingNode, // Labels are MappingNodes.
CreateTag: yaml.NodeTagMap,
Expand Down
4 changes: 3 additions & 1 deletion api/filters/labels/labels_test.go
Expand Up @@ -37,6 +37,7 @@ func TestLabels_Filter(t *testing.T) {
input string
expectedOutput string
filter Filter
setEntryCallback func(key, value, tag string, node *yaml.RNode)
expectedSetEntryArgs []setEntryArg
}{
"add": {
Expand Down Expand Up @@ -456,8 +457,8 @@ a:
CreateIfNotPresent: true,
},
},
SetEntryCallback: setEntryCallbackStub,
},
setEntryCallback: setEntryCallbackStub,
expectedSetEntryArgs: []setEntryArg{
{
Key: "mage",
Expand All @@ -478,6 +479,7 @@ a:
for tn, tc := range testCases {
setEntryArgs = nil
t.Run(tn, func(t *testing.T) {
tc.filter.WithMutationTracker(tc.setEntryCallback)
if !assert.Equal(t,
strings.TrimSpace(tc.expectedOutput),
strings.TrimSpace(filtertest_test.RunFilter(t, tc.input, tc.filter))) {
Expand Down

0 comments on commit e939be6

Please sign in to comment.