diff --git a/pkg/genericcli/printers/template.go b/pkg/genericcli/printers/template.go index c88d46f..74d09c9 100644 --- a/pkg/genericcli/printers/template.go +++ b/pkg/genericcli/printers/template.go @@ -9,20 +9,22 @@ import ( "reflect" "text/template" - "github.com/go-task/slim-sprig/v3" + sprig "github.com/go-task/slim-sprig/v3" ) // TemplatePrinter prints data with a given template type TemplatePrinter struct { - out io.Writer - text string - t *template.Template + out io.Writer + text string + t *template.Template + omitEmpty bool } func NewTemplatePrinter(template string) *TemplatePrinter { return &TemplatePrinter{ - out: os.Stdout, - text: template, + out: os.Stdout, + text: template, + omitEmpty: true, } } @@ -36,6 +38,11 @@ func (p *TemplatePrinter) WithTemplate(t *template.Template) *TemplatePrinter { return p } +func (p *TemplatePrinter) WithoutOmitEmptyLines() *TemplatePrinter { + p.omitEmpty = false + return p +} + func (p *TemplatePrinter) Print(data any) error { if p.t == nil { var err error @@ -91,7 +98,9 @@ func (p *TemplatePrinter) print(data any) error { return fmt.Errorf("unable to render template: %w", err) } - fmt.Fprintf(p.out, "%s\n", buf.String()) + if !p.omitEmpty || buf.Len() > 0 { + fmt.Fprintf(p.out, "%s\n", buf.String()) + } return nil } diff --git a/pkg/genericcli/printers/template_test.go b/pkg/genericcli/printers/template_test.go index c54c211..cfd827f 100644 --- a/pkg/genericcli/printers/template_test.go +++ b/pkg/genericcli/printers/template_test.go @@ -91,5 +91,41 @@ func TestTemplatePrinter_WithTemplate(t *testing.T) { if diff := cmp.Diff(want, got); diff != "" { t.Errorf("diff (+got -want):\n %s", diff) } +} + +func TestTemplatePrinter_OmitEmptyRowsInSliceResponses(t *testing.T) { + type obj struct { + Name string `json:"name"` + } + + var ( + out bytes.Buffer + out2 bytes.Buffer + tpl = `{{ if eq .name "test" }}{{ .name }}{{ end }}` + testObjs = []obj{{Name: "a"}, {Name: "test"}} + ) + + p := NewTemplatePrinter(tpl).WithOut(&out) + err := p.Print(testObjs) + if err != nil { + t.Error(err) + } + + want := "test\n" + got := out.String() + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("diff (+got -want):\n %s", diff) + } + + p = NewTemplatePrinter(tpl).WithOut(&out2).WithoutOmitEmptyLines() + err = p.Print(testObjs) + if err != nil { + t.Error(err) + } + want = "\ntest\n" + got = out2.String() + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("diff (+got -want):\n %s", diff) + } }