Skip to content

Commit

Permalink
Omit empty lines on template printer slice objects. (#142)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gerrit91 authored May 31, 2024
1 parent 2322a38 commit a8fb25d
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 7 deletions.
23 changes: 16 additions & 7 deletions pkg/genericcli/printers/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}

Expand All @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
36 changes: 36 additions & 0 deletions pkg/genericcli/printers/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit a8fb25d

Please sign in to comment.