Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion templates/pkg/resource/resource.go.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@
package {{ .CRD.Names.Snake }}

import (
"reflect"
"strings"

ackv1alpha1 "github.com/aws-controllers-k8s/runtime/apis/core/v1alpha1"
acktypes "github.com/aws-controllers-k8s/runtime/pkg/types"
{{- if $idField := .CRD.SpecIdentifierField }}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can remove this now that #61 is merged.

ackerrors "github.com/aws-controllers-k8s/runtime/pkg/errors"
{{- end }}
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8srt "k8s.io/apimachinery/pkg/runtime"

Expand Down Expand Up @@ -67,15 +72,38 @@ func (r *resource) SetObjectMeta(meta metav1.ObjectMeta) {
}

// SetIdentifiers sets the Spec or Status field that is referenced as the unique
// resource identifier
// resource identifier and any additional spec fields that may be required for
// describing the resource.
func (r *resource) SetIdentifiers(identifier *ackv1alpha1.AWSIdentifiers) error {
{{- if $idField := .CRD.SpecIdentifierField }}
if identifier.NameOrID == nil {
return ackerrors.MissingNameIdentifier
}
r.ko.Spec.{{ $idField }} = identifier.NameOrID
{{- else }}
if r.ko.Status.ACKResourceMetadata == nil {
r.ko.Status.ACKResourceMetadata = &ackv1alpha1.ResourceMetadata{}
}
r.ko.Status.ACKResourceMetadata.ARN = identifier.ARN
{{- end }}

if len(identifier.AdditionalKeys) == 0 {
return nil
}

specRef := reflect.Indirect(reflect.ValueOf(&r.ko.Spec))
specType := specRef.Type()

// Iterate over spec fields and associate corresponding json tags
for i := 0; i < specRef.NumField(); i++ {
// Get only the first field in the json tag (the field name)
jsonTag := strings.Split(specType.Field(i).Tag.Get("json"), ",")[0]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm OK with using the reflect package (even though it's incredibly ugly to work with, IMHO) here.

In the future, we may want to take an approach similar to how we handle TerminalConditions and simply generate a switch case lookup here...

val, ok := identifier.AdditionalKeys[jsonTag]
if ok {
// Set the corresponding field with the value from the mapping
specRef.FieldByName(specType.Field(i).Name).Set(reflect.ValueOf(val))
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what if the jsonTag isn't found in the identifier.AdditionalKeys? should we error out?

}

return nil
}