Skip to content

Commit

Permalink
Add munge func to output writer (#173)
Browse files Browse the repository at this point in the history
Some synthesizers may have their own internal structure (e.g. the helm
shim) while some logically separate code performs final
transformation(s) - adding annotations, etc.

Co-authored-by: Jordan Olshevski <[email protected]>
  • Loading branch information
jveski and Jordan Olshevski authored Jul 23, 2024
1 parent da0cbb9 commit 2de1d5a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
14 changes: 11 additions & 3 deletions pkg/function/outputs.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,21 @@ type OutputWriter struct {
outputs []*unstructured.Unstructured
io io.Writer
committed bool
munge MungeFunc
}

type MungeFunc func(*unstructured.Unstructured)

func NewDefaultOutputWriter() *OutputWriter {
return NewOutputWriter(os.Stdout)
return NewOutputWriter(os.Stdout, nil)
}

func NewOutputWriter(w io.Writer) *OutputWriter {
func NewOutputWriter(w io.Writer, munge MungeFunc) *OutputWriter {
return &OutputWriter{
outputs: []*unstructured.Unstructured{},
io: w,
committed: false,
munge: munge,
}
}

Expand All @@ -49,7 +53,11 @@ func (w *OutputWriter) Add(outs ...client.Object) error {
err,
)
}
w.outputs = append(w.outputs, &unstructured.Unstructured{Object: obj})
u := &unstructured.Unstructured{Object: obj}
if w.munge != nil {
w.munge(u)
}
w.outputs = append(w.outputs, u)
}
return nil
}
Expand Down
17 changes: 16 additions & 1 deletion pkg/function/outputs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)

func TestOutputWriter(t *testing.T) {
out := bytes.NewBuffer(nil)
w := NewOutputWriter(out)
w := NewOutputWriter(out, nil)

cm := &corev1.ConfigMap{}
cm.Name = "test-cm"
Expand All @@ -25,3 +26,17 @@ func TestOutputWriter(t *testing.T) {

require.Error(t, w.Add(nil))
}

func TestOutputWriterMunge(t *testing.T) {
out := bytes.NewBuffer(nil)
w := NewOutputWriter(out, func(u *unstructured.Unstructured) {
unstructured.SetNestedField(u.Object, "value from munge function", "data", "extra-val")
})

cm := &corev1.ConfigMap{}
cm.Name = "test-cm"

require.NoError(t, w.Add(cm))
require.NoError(t, w.Write())
assert.Equal(t, "{\"apiVersion\":\"config.kubernetes.io/v1\",\"kind\":\"ResourceList\",\"items\":[{\"data\":{\"extra-val\":\"value from munge function\"},\"metadata\":{\"creationTimestamp\":null,\"name\":\"test-cm\"}}]}\n", out.String())
}

0 comments on commit 2de1d5a

Please sign in to comment.