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
23 changes: 16 additions & 7 deletions pkg/cmd/clustertriggerbinding/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const (

type listOptions struct {
NoHeaders bool
Fields []string
}

func listCommand(p cli.Params) *cobra.Command {
Expand All @@ -58,6 +59,15 @@ or
},
Example: eg,
RunE: func(cmd *cobra.Command, _ []string) error {
output, err := cmd.LocalFlags().GetString("output")
if err != nil {
return errors.New("output option not set properly")
}

if len(opts.Fields) > 0 && output != "ndjson" {
return fmt.Errorf("--fields is only supported with --output ndjson")
}

cs, err := p.Clients()
if err != nil {
return err
Expand All @@ -68,17 +78,15 @@ or
return fmt.Errorf("failed to list ClusterTriggerBindings: %v", err)
}

output, err := cmd.LocalFlags().GetString("output")
if err != nil {
return errors.New("output option not set properly")
}

stream := &cli.Stream{
Out: cmd.OutOrStdout(),
Err: cmd.OutOrStderr(),
}

if output == "name" && tbs != nil {
switch {
case output == "ndjson" && tbs != nil:
return formatted.PrintNDJSON(stream.Out, tbs, opts.Fields)
case output == "name" && tbs != nil:
w := cmd.OutOrStdout()
for _, pr := range tbs.Items {
_, err := fmt.Fprintf(w, "clustertriggerbinding.triggers.tekton.dev/%s\n", pr.Name)
Expand All @@ -87,7 +95,7 @@ or
}
}
return nil
} else if output != "" {
case output != "":
p, err := f.ToPrinter()
if err != nil {
return err
Expand All @@ -105,6 +113,7 @@ or

f.AddFlags(c)
c.Flags().BoolVar(&opts.NoHeaders, "no-headers", opts.NoHeaders, "do not print column headers with output (default print column headers with output)")
c.Flags().StringSliceVar(&opts.Fields, "fields", opts.Fields, "Comma-separated list of fields to include in output (e.g. metadata.name,status.startTime); only used with --output ndjson")
return c
}

Expand Down
23 changes: 16 additions & 7 deletions pkg/cmd/customrun/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ type ListOptions struct {
Reverse bool
AllNamespaces bool
NoHeaders bool
Fields []string
}

func listCommand(p cli.Params) *cobra.Command {
Expand All @@ -79,6 +80,15 @@ func listCommand(p cli.Params) *cobra.Command {
return fmt.Errorf("limit was %d but must be a positive number", opts.Limit)
}

output, err := cmd.LocalFlags().GetString("output")
if err != nil {
return fmt.Errorf("output option not set properly: %v", err)
}

if len(opts.Fields) > 0 && output != "ndjson" {
return fmt.Errorf("--fields is only supported with --output ndjson")
}

crs, err := list(p, opts.Limit, opts.LabelSelector, opts.AllNamespaces)
if err != nil {
return fmt.Errorf("failed to list CustomRuns from namespace %s: %v", p.Namespace(), err)
Expand All @@ -87,12 +97,10 @@ func listCommand(p cli.Params) *cobra.Command {
if crs != nil && opts.Reverse {
reverse(crs)
}

output, err := cmd.LocalFlags().GetString("output")
if err != nil {
return fmt.Errorf("output option not set properly: %v", err)
}
if output == "name" && crs != nil {
switch {
case output == "ndjson" && crs != nil:
return formatted.PrintNDJSON(cmd.OutOrStdout(), crs, opts.Fields)
case output == "name" && crs != nil:
w := cmd.OutOrStdout()
for _, tr := range crs.Items {
_, err := fmt.Fprintf(w, "customrun.tekton.dev/%s\n", tr.Name)
Expand All @@ -101,7 +109,7 @@ func listCommand(p cli.Params) *cobra.Command {
}
}
return nil
} else if output != "" && crs != nil {
case output != "" && crs != nil:
p, err := f.ToPrinter()
if err != nil {
return err
Expand Down Expand Up @@ -133,6 +141,7 @@ func listCommand(p cli.Params) *cobra.Command {
c.Flags().BoolVarP(&opts.Reverse, "reverse", "", opts.Reverse, "list CustomRuns in reverse order")
c.Flags().BoolVarP(&opts.AllNamespaces, "all-namespaces", "A", opts.AllNamespaces, "list CustomRuns from all namespaces")
c.Flags().BoolVarP(&opts.NoHeaders, "no-headers", "", opts.NoHeaders, "do not print column headers with output (default print column headers with output)")
c.Flags().StringSliceVar(&opts.Fields, "fields", opts.Fields, "Comma-separated list of fields to include in output (e.g. metadata.name,status.startTime); only used with --output ndjson")
return c
}

Expand Down
20 changes: 14 additions & 6 deletions pkg/cmd/eventlistener/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const (
type listOptions struct {
AllNamespaces bool
NoHeaders bool
Fields []string
}

func listCommand(p cli.Params) *cobra.Command {
Expand All @@ -60,6 +61,15 @@ or
},
Example: eg,
RunE: func(cmd *cobra.Command, _ []string) error {
output, err := cmd.LocalFlags().GetString("output")
if err != nil {
return errors.New(`output option not set properly \n`)
}

if len(opts.Fields) > 0 && output != "ndjson" {
return fmt.Errorf("--fields is only supported with --output ndjson")
}

cs, err := p.Clients()
if err != nil {
return err
Expand All @@ -78,17 +88,14 @@ or
return fmt.Errorf("failed to list EventListeners from %s namespace: %v", namespace, err)
}

output, err := cmd.LocalFlags().GetString("output")
if err != nil {
return errors.New(`output option not set properly \n`)
}

stream := &cli.Stream{
Out: cmd.OutOrStdout(),
Err: cmd.OutOrStderr(),
}

if output != "" {
if output == "ndjson" {
return formatted.PrintNDJSON(stream.Out, els, opts.Fields)
} else if output != "" {
p, err := f.ToPrinter()
if err != nil {
return err
Expand All @@ -106,6 +113,7 @@ or
f.AddFlags(c)
c.Flags().BoolVarP(&opts.AllNamespaces, "all-namespaces", "A", opts.AllNamespaces, "list EventListeners from all namespaces")
c.Flags().BoolVar(&opts.NoHeaders, "no-headers", opts.NoHeaders, "do not print column headers with output (default print column headers with output)")
c.Flags().StringSliceVar(&opts.Fields, "fields", opts.Fields, "Comma-separated list of fields to include in output (e.g. metadata.name,status.startTime); only used with --output ndjson")
return c
}

Expand Down
26 changes: 21 additions & 5 deletions pkg/cmd/pipeline/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ NAME AGE LAST RUN STARTED DURATION STATUS
type ListOptions struct {
AllNamespaces bool
NoHeaders bool
Fields []string
}

func listCommand(p cli.Params) *cobra.Command {
Expand All @@ -76,22 +77,36 @@ func listCommand(p cli.Params) *cobra.Command {
},
SilenceUsage: true,
RunE: func(cmd *cobra.Command, _ []string) error {
cs, err := p.Clients()
output, err := cmd.LocalFlags().GetString("output")
if err != nil {
return err
return fmt.Errorf("output option not set properly: %v", err)
}

output, err := cmd.LocalFlags().GetString("output")
if len(opts.Fields) > 0 && output != "ndjson" {
return fmt.Errorf("--fields is only supported with --output ndjson")
}

cs, err := p.Clients()
if err != nil {
return fmt.Errorf("output option not set properly: %v", err)
return err
}

ns := p.Namespace()
if opts.AllNamespaces {
ns = ""
}

if output != "" {
if output == "ndjson" {
var pl *v1.PipelineList
if err := actions.ListV1(pipelineGroupResource, cs, metav1.ListOptions{}, ns, &pl); err != nil {
scope := fmt.Sprintf("namespace %q", ns)
if ns == "" {
Comment on lines +99 to +103

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added TestListPipelineRuns_ndjson, TestListPipelines_ndjson, and TestListTasks_ndjson, each with three sub-tests: valid JSON lines output, --fields narrowing, and --fields without ndjson error

scope = "all namespaces"
}
return fmt.Errorf("failed to list Pipelines from %s: %w", scope, err)
}
return formatted.PrintNDJSON(cmd.OutOrStdout(), pl, opts.Fields)
} else if output != "" {
p, err := f.ToPrinter()
if err != nil {
return err
Expand All @@ -108,6 +123,7 @@ func listCommand(p cli.Params) *cobra.Command {
f.AddFlags(c)
c.Flags().BoolVarP(&opts.AllNamespaces, "all-namespaces", "A", opts.AllNamespaces, "list Pipelines from all namespaces")
c.Flags().BoolVarP(&opts.NoHeaders, "no-headers", "", opts.NoHeaders, "do not print column headers with output (default print column headers with output)")
c.Flags().StringSliceVar(&opts.Fields, "fields", opts.Fields, "Comma-separated list of fields to include in output (e.g. metadata.name,status.startTime); only used with --output ndjson")

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 --fields metadata.name without --output ndjson (or with --output json), the flag is silently ignored. This could lead to confusion. Can we add validation in the RunE function:

if len(opts.Fields) > 0 && output != "ndjson" {
    return fmt.Errorf("--fields is only supported with --output ndjson")
}

This should apply to all list commands.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added if len(opts.Fields) > 0 && output != "ndjson" { return error } to all 8 list commands: pipeline, task, pipelinerun, taskrun, customrun, clustertriggerbinding, triggerbinding, triggertemplate, eventlistener


return c
}
Expand Down
108 changes: 108 additions & 0 deletions pkg/cmd/pipeline/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
package pipeline

import (
"encoding/json"
"fmt"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -1167,3 +1169,109 @@ func TestPipelineList_in_all_namespaces_with_output_yaml_flag(t *testing.T) {

golden.Assert(t, output, fmt.Sprintf("%s.golden", t.Name()))
}

// TestListPipelines_ndjson verifies the --output ndjson path in the pipeline list command.
func TestListPipelines_ndjson(t *testing.T) {
version := "v1"
clock := test.FakeClock()

pdata := []*v1.Pipeline{
{
ObjectMeta: metav1.ObjectMeta{
Name: "pipe-a",
Namespace: "namespace",
CreationTimestamp: metav1.Time{Time: clock.Now().Add(-1 * time.Minute)},
},
},
{
ObjectMeta: metav1.ObjectMeta{
Name: "pipe-b",
Namespace: "namespace",
CreationTimestamp: metav1.Time{Time: clock.Now().Add(-2 * time.Minute)},
},
},
}

ns := []*corev1.Namespace{
{ObjectMeta: metav1.ObjectMeta{Name: "namespace"}},
}

tdc := testDynamic.Options{}
dynamic, err := tdc.Client(
cb.UnstructuredP(pdata[0], version),
cb.UnstructuredP(pdata[1], version),
)
if err != nil {
t.Fatalf("unable to create dynamic client: %v", err)
}

cs, _ := test.SeedTestData(t, pipelinetest.Data{Pipelines: pdata, Namespaces: ns})
cs.Pipeline.Resources = cb.APIResourceList(version, []string{"pipeline"})
p := &test.Params{Tekton: cs.Pipeline, Clock: clock, Kube: cs.Kube, Dynamic: dynamic}

t.Run("ndjson output produces valid JSON lines", func(t *testing.T) {
cmd := Command(p)
output, err := test.ExecuteCommand(cmd, "list", "-n", "namespace", "-o", "ndjson")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
lines := pipelineSplitNonEmpty(output)
if len(lines) != 2 {
t.Fatalf("expected 2 lines, got %d:\n%s", len(lines), output)
}
for i, line := range lines {
var m map[string]any
if err := json.Unmarshal([]byte(line), &m); err != nil {
t.Errorf("line %d is not valid JSON: %v", i, err)
}
}
})

t.Run("ndjson with --fields narrows output", func(t *testing.T) {
cmd := Command(p)
output, err := test.ExecuteCommand(cmd, "list", "-n", "namespace", "-o", "ndjson", "--fields", "metadata.name")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
lines := pipelineSplitNonEmpty(output)
if len(lines) != 2 {
t.Fatalf("expected 2 lines, got %d", len(lines))
}
for i, line := range lines {
var m map[string]any
if err := json.Unmarshal([]byte(line), &m); err != nil {
t.Errorf("line %d is not valid JSON: %v", i, err)
continue
}
meta, ok := m["metadata"].(map[string]any)
if !ok {
t.Errorf("line %d: expected metadata key", i)
continue
}
if _, ok := meta["name"]; !ok {
t.Errorf("line %d: expected metadata.name", i)
}
if len(m) != 1 {
t.Errorf("line %d: expected only metadata key, got %v", i, m)
}
}
})

t.Run("--fields without ndjson returns error", func(t *testing.T) {
cmd := Command(p)
_, err := test.ExecuteCommand(cmd, "list", "-n", "namespace", "--fields", "metadata.name")
if err == nil {
t.Error("expected error when --fields used without --output ndjson, got none")
}
})
}

func pipelineSplitNonEmpty(s string) []string {
var out []string
for _, line := range strings.Split(strings.TrimRight(s, "\n"), "\n") {
if line != "" {
out = append(out, line)
}
}
return out
}
Loading
Loading