Skip to content
Open
Show file tree
Hide file tree
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
53 changes: 40 additions & 13 deletions pkg/cmd/taskrun/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package taskrun

import (
"encoding/json"
"errors"
"fmt"
"strings"
Expand Down Expand Up @@ -92,6 +93,11 @@ or
Err: cmd.OutOrStderr(),
}

output, err := cmd.LocalFlags().GetString("output")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

If a user passes -o yaml or -o table, the command silently falls through to human-readable text output with no error. Add validation:

if output != "" && output != "json" {
    return fmt.Errorf("unsupported output format %q; supported formats: json", output)
}

if err != nil {
return err
}

if deleteOpts.TaskName != "" {
opts.ParentResource = "Task"
opts.ParentResourceName = deleteOpts.TaskName
Expand Down Expand Up @@ -122,11 +128,15 @@ or
return errs
}

if err := opts.CheckOptions(s, availableTrs, p.Namespace()); err != nil {
return err
}
checkStreams := s
if output == "json" {
checkStreams = &cli.Stream{In: strings.NewReader("y\n"), Out: &strings.Builder{}, Err: s.Err}
}
if err := opts.CheckOptions(checkStreams, availableTrs, p.Namespace()); err != nil {
return err
}
Comment on lines +132 to +137

if err := deleteTaskRuns(s, p, availableTrs, opts); err != nil {
if err := deleteTaskRuns(s, p, availableTrs, opts, output); err != nil {
return err
}
return errs
Expand All @@ -144,7 +154,7 @@ or
return c
}

func deleteTaskRuns(s *cli.Stream, p cli.Params, trNames []string, opts *options.DeleteOptions) error {
func deleteTaskRuns(s *cli.Stream, p cli.Params, trNames []string, opts *options.DeleteOptions, output string) error {
var numberOfDeletedTr, numberOfKeptTr int
cs, err := p.Clients()
if err != nil {
Expand Down Expand Up @@ -177,9 +187,13 @@ func deleteTaskRuns(s *cli.Stream, p cli.Params, trNames []string, opts *options
prFinished := ownerPrFinished(cs, *tr)

if !prFinished && opts.ForceDelete {
fmt.Fprintf(s.Out, "warning: Taskrun %s related pipelinerun still running.\n", tr.Name)
if output == "json" {
fmt.Fprintf(s.Err, "warning: Taskrun %s related pipelinerun still running.\n", tr.Name)
} else {
fmt.Fprintf(s.Out, "warning: Taskrun %s related pipelinerun still running.\n", tr.Name)
}
}
if !prFinished && !opts.ForceDelete {
if !prFinished && !opts.ForceDelete && output != "json" {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

When -o json is used without --force, the confirmation prompt is suppressed but the TaskRun is unconditionally appended to processedTrNames and deleted. This is an implicit force-delete semantic — a running PipelineRun's TaskRun is deleted without consent or any signal in the JSON output. Deleting such a TaskRun causes the PipelineRun controller to restart it, which is a destructive side-effect that scripts/agents can't anticipate.

Since -o json is a new feature targeting machine consumers (issue #2850), the behavior should be strict by default. Require --force when the TaskRun is owned by a running PipelineRun:

if !prFinished && !opts.ForceDelete && output == "json" {
    return fmt.Errorf("taskrun %s is owned by a running PipelineRun; use --force to delete", tr.Name)
}

fmt.Fprintf(s.Out, "TaskRun(s): %s attached to PipelineRun is still running deleting will restart the completed taskrun. Proceed (y/n): ", tr.Name)
if err := opts.TakeInput(s, ""); err != nil {
continue
Expand Down Expand Up @@ -212,16 +226,29 @@ func deleteTaskRuns(s *cli.Stream, p cli.Params, trNames []string, opts *options
})

if opts.Keep > 0 && opts.Keep == len(trToKeep) && len(trToDelete) == 0 {
fmt.Fprintf(s.Out, "Associated %s (%d) for Task:%s is/are equal to keep (%d) \n", opts.Resource, len(trToKeep), opts.ParentResourceName, opts.Keep)
return nil
}
if opts.Keep > len(trToKeep) {
fmt.Fprintf(s.Out, "There is/are only %d %s(s) associated for %s: %s \n", len(trToKeep), opts.Resource, opts.ParentResource, opts.ParentResourceName)
return nil
if output != "json" {
fmt.Fprintf(s.Out, "Associated %s (%d) for Task:%s is/are equal to keep (%d) \n", opts.Resource, len(trToKeep), opts.ParentResourceName, opts.Keep)
return nil
}
} else if opts.Keep > len(trToKeep) {
if output != "json" {
fmt.Fprintf(s.Out, "There is/are only %d %s(s) associated for %s: %s \n", len(trToKeep), opts.Resource, opts.ParentResource, opts.ParentResourceName)
return nil
}
Comment on lines +233 to +237
}
d.DeleteRelated([]string{opts.ParentResourceName})
}

if output == "json" {
Comment thread
Debashich marked this conversation as resolved.
result := struct {
Deleted []string `json:"deleted"`
}{
Deleted: append(append([]string(nil), d.SuccessfulRelatedDeletes()...), d.SuccessfulDeletes()...),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Even outside the --task --keep no-op case above, whenever both SuccessfulRelatedDeletes() and SuccessfulDeletes() return nil (via append([]string(nil), nil...)), the result is a nil slice and json.Encoder serializes it as null, not []. For consistent machine-readable output, guard against nil:

deleted := append(d.SuccessfulRelatedDeletes(), d.SuccessfulDeletes()...)
if deleted == nil {
    deleted = []string{}
}

}
encodeErr := json.NewEncoder(s.Out).Encode(result)
return multierr.Append(encodeErr, d.Errors())
}

if !opts.DeleteAllNs {
if d.Errors() == nil {
switch {
Expand Down
40 changes: 40 additions & 0 deletions pkg/cmd/taskrun/delete_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,46 @@ func TestTaskRunDelete_v1beta1(t *testing.T) {
wantError: false,
want: "All 6 TaskRuns associated with Task \"random\" deleted in namespace \"ns\"\n",
},
{
name: "With JSON output",
command: []string{"rm", "tr0-1", "-n", "ns", "-o", "json"},
dynamic: seeds[15].dynamicClient,
Comment thread
Debashich marked this conversation as resolved.
input: seeds[15].pipelineClient,
inputStream: nil,
wantError: false,
want: `{"deleted":["tr0-1"]}
`,
},
{
name: "With JSON output for multiple TaskRuns",
command: []string{"rm", "tr0-1", "tr0-2", "-n", "ns", "-o", "json"},
dynamic: seeds[16].dynamicClient,
input: seeds[16].pipelineClient,
inputStream: strings.NewReader("y\n"),
wantError: false,
want: `{"deleted":["tr0-1","tr0-2"]}
`,
},
{
name: "Delete with JSON output for --task but keep meets or exceeds existing (no-op)",
command: []string{"rm", "--task", "random", "-n", "ns", "--keep", "10", "-o", "json"},
dynamic: seeds[15].dynamicClient,
input: seeds[15].pipelineClient,
inputStream: nil,
wantError: false,
want: `{"deleted":[]}
`,
},
{
name: "Delete with JSON output for --task",
command: []string{"rm", "--task", "random", "-n", "ns", "-o", "json"},
dynamic: seeds[15].dynamicClient,
input: seeds[15].pipelineClient,
inputStream: nil,
wantError: false,
want: `{"deleted":["tr0-1","tr0-2","tr0-3","tr0-4"]}
`,
},
}

for _, tp := range testParams {
Expand Down
8 changes: 8 additions & 0 deletions pkg/deleter/deleter.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,14 @@ func (d *Deleter) PrintSuccesses(streams *cli.Stream) {
}
}

func (d *Deleter) SuccessfulDeletes() []string {
return append([]string(nil), d.successfulDeletes...)
}

func (d *Deleter) SuccessfulRelatedDeletes() []string {
return append([]string(nil), d.successfulRelatedDeletes...)
}

// appendError adds that error to the list of accumulated errors that
// have occurred during execution.
func (d *Deleter) appendError(err error) {
Expand Down
24 changes: 24 additions & 0 deletions pkg/deleter/deleter_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package deleter

import (
"reflect"
"strings"
"testing"

Expand Down Expand Up @@ -50,6 +51,29 @@ func TestDelete(t *testing.T) {
}
}

func TestSuccessfulDeletes(t *testing.T) {
d := New("FooBar", successfulDeleteFunc())
d.Delete([]string{"foo", "bar"})

expected := []string{"foo", "bar"}
if got := d.SuccessfulDeletes(); !reflect.DeepEqual(got, expected) {
t.Errorf("expected %v, received %v", expected, got)
}
}

func TestSuccessfulRelatedDeletes(t *testing.T) {
d := New("FooBar", successfulDeleteFunc())
d.WithRelated("FooBarRun", successfulListFunc("fbr1", "fbr2"), successfulDeleteFunc())

deletedNames := d.Delete([]string{"foo"})
d.DeleteRelated(deletedNames)

expected := []string{"fbr1", "fbr2"}
if got := d.SuccessfulRelatedDeletes(); !reflect.DeepEqual(got, expected) {
t.Errorf("expected %v, received %v", expected, got)
}
}

func TestDeleteRelated(t *testing.T) {
for _, tc := range []struct {
description string
Expand Down
Loading