Skip to content

Commit ad98753

Browse files
committed
Add a way to modify the component objects
1 parent e34a6e8 commit ad98753

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

cmd/clusterctl/client/repository/components.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,25 @@ func (c *components) Yaml() ([]byte, error) {
144144
return utilyaml.FromUnstructured(c.objs)
145145
}
146146

147+
// ComponentsAlterFn defines the function that is used to alter the components.Objs().
148+
type ComponentsAlterFn func(objs []unstructured.Unstructured) ([]unstructured.Unstructured, error)
149+
150+
// AlterComponents provides a mechanism to alter the component.Objs from outside
151+
// the repository module.
152+
func AlterComponents(comps Components, alterFn ComponentsAlterFn) error {
153+
c, ok := comps.(*components)
154+
if !ok {
155+
return errors.New("could not alter components as Components is not of the correct type")
156+
}
157+
158+
alteredObjs, err := alterFn(c.Objs())
159+
if err != nil {
160+
return err
161+
}
162+
c.objs = alteredObjs
163+
return nil
164+
}
165+
147166
// ComponentsOptions represents specific inputs that are passed in to
148167
// clusterctl library. These are user specified inputs.
149168
type ComponentsOptions struct {

cmd/clusterctl/client/repository/components_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -948,3 +948,40 @@ func Test_addCommonLabels(t *testing.T) {
948948
})
949949
}
950950
}
951+
952+
func TestAlterComponents(t *testing.T) {
953+
c := &components{
954+
targetNamespace: "test-ns",
955+
objs: []unstructured.Unstructured{
956+
{
957+
Object: map[string]interface{}{
958+
"kind": "ClusterRole",
959+
},
960+
},
961+
},
962+
}
963+
want := []unstructured.Unstructured{
964+
{
965+
Object: map[string]interface{}{
966+
"kind": "ClusterRole",
967+
"metadata": map[string]interface{}{
968+
"labels": map[string]interface{}{
969+
clusterctlv1.ClusterctlLabelName: "",
970+
clusterv1.ProviderLabelName: "infrastructure-provider",
971+
},
972+
},
973+
},
974+
},
975+
}
976+
977+
alterFn := func(objs []unstructured.Unstructured) ([]unstructured.Unstructured, error) {
978+
// reusing addCommonLabels to do an example modification.
979+
return addCommonLabels(objs, config.NewProvider("provider", "", clusterctlv1.InfrastructureProviderType)), nil
980+
}
981+
982+
g := NewWithT(t)
983+
if err := AlterComponents(c, alterFn); err != nil {
984+
t.Errorf("AlterComponents() error = %v", err)
985+
}
986+
g.Expect(c.objs).To(Equal(want))
987+
}

0 commit comments

Comments
 (0)