Skip to content
Open
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
21 changes: 20 additions & 1 deletion pkg/karmadactl/interpret/edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,26 @@ func (o *Options) runEdit() error {
// not a syntax error as it turns out...
containsError = false

// TODO: add last-applied-configuration annotation
// Add last-applied-configuration annotation
// Create a copy without the annotation to serialize, avoiding recursion
tempCustomization := editedCustomization.DeepCopy()
tempAnnotations := tempCustomization.GetAnnotations()
if tempAnnotations != nil {
delete(tempAnnotations, corev1.LastAppliedConfigAnnotation)
tempCustomization.SetAnnotations(tempAnnotations)
}
Comment on lines +176 to +181

Choose a reason for hiding this comment

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

medium

The logic to prepare the object for the last-applied-configuration annotation can be made more robust and concise. The SetAnnotations call on line 180 is redundant as GetAnnotations returns a reference to the map which is modified in-place. Additionally, if the annotations map becomes empty after removing the last-applied-configuration key, it should be set to nil to avoid serializing an empty map in the annotation's value.

Suggested change
tempCustomization := editedCustomization.DeepCopy()
tempAnnotations := tempCustomization.GetAnnotations()
if tempAnnotations != nil {
delete(tempAnnotations, corev1.LastAppliedConfigAnnotation)
tempCustomization.SetAnnotations(tempAnnotations)
}
tempCustomization := editedCustomization.DeepCopy()
if tempAnnotations := tempCustomization.GetAnnotations(); tempAnnotations != nil {
delete(tempAnnotations, corev1.LastAppliedConfigAnnotation)
if len(tempAnnotations) == 0 {
tempCustomization.SetAnnotations(nil)
}
}

// Serialize the customization without the annotation
lastAppliedJSON, err := json.Marshal(tempCustomization)
if err != nil {
return fmt.Errorf("failed to marshal customization for last-applied-configuration annotation: %w", err)
}
// Add the serialized JSON as the annotation value (only one SetAnnotations call on the original object)
annotations := editedCustomization.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
annotations[corev1.LastAppliedConfigAnnotation] = string(lastAppliedJSON)
editedCustomization.SetAnnotations(annotations)

switch {
case info.Source != "":
Expand Down