diff --git a/pkg/cmd/label/label.go b/pkg/cmd/label/label.go index f6fa87e8..007f6284 100644 --- a/pkg/cmd/label/label.go +++ b/pkg/cmd/label/label.go @@ -307,7 +307,7 @@ func (o *LabelOptions) RunLabel() error { if err != nil { return err } - dataChangeMsg = updateDataChangeMsg(oldData, newObj) + dataChangeMsg = updateDataChangeMsg(oldData, newObj, o.overwrite) outputObj = info.Object } else { name, namespace := info.Name, info.Namespace @@ -334,7 +334,7 @@ func (o *LabelOptions) RunLabel() error { if err != nil { return err } - dataChangeMsg = updateDataChangeMsg(oldData, newObj) + dataChangeMsg = updateDataChangeMsg(oldData, newObj, o.overwrite) patchBytes, err := jsonpatch.CreateMergePatch(oldData, newObj) createdPatch := err == nil if err != nil { @@ -395,11 +395,11 @@ func (o *LabelOptions) RunLabel() error { }) } -func updateDataChangeMsg(oldObj []byte, newObj []byte) string { +func updateDataChangeMsg(oldObj []byte, newObj []byte, overwrite bool) string { msg := MsgNotLabeled if !reflect.DeepEqual(oldObj, newObj) { msg = MsgLabeled - if len(newObj) < len(oldObj) { + if !overwrite && len(newObj) < len(oldObj) { msg = MsgUnLabeled } } diff --git a/pkg/cmd/label/label_test.go b/pkg/cmd/label/label_test.go index a939e886..cf7526fa 100644 --- a/pkg/cmd/label/label_test.go +++ b/pkg/cmd/label/label_test.go @@ -678,6 +678,41 @@ func TestLabelMsg(t *testing.T) { }, expectMsg: MsgLabeled, }, + { + obj: &v1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Labels: map[string]string{"status": "unhealthy"}, + }, + }, + labels: map[string]string{"status": "healthy"}, + overwrite: true, + expectObj: &v1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Labels: map[string]string{ + "status": "healthy", + }, + }, + }, + expectMsg: MsgLabeled, + }, + { + obj: &v1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Labels: map[string]string{"status": "unhealthy"}, + }, + }, + labels: map[string]string{"status": "healthy"}, + overwrite: false, + expectObj: &v1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Labels: map[string]string{ + "status": "unhealthy", + }, + }, + }, + expectMsg: MsgNotLabeled, + expectErr: true, + }, } for _, test := range tests { @@ -700,7 +735,7 @@ func TestLabelMsg(t *testing.T) { t.Errorf("unexpected error: %v %v", err, test) } - dataChangeMsg := updateDataChangeMsg(oldData, newObj) + dataChangeMsg := updateDataChangeMsg(oldData, newObj, test.overwrite) if dataChangeMsg != test.expectMsg { t.Errorf("unexpected dataChangeMsg: %v != %v, %v", dataChangeMsg, test.expectMsg, test) }