Skip to content
This repository was archived by the owner on May 7, 2024. It is now read-only.

Commit 8a8fa01

Browse files
committed
feat: allow to return an error
Signed-off-by: Carlos A Becker <caarlos0@users.noreply.github.com>
1 parent b9f5623 commit 8a8fa01

2 files changed

Lines changed: 23 additions & 7 deletions

File tree

main.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,17 @@ import (
1313
var boldStyle = lipgloss.NewStyle().Bold(true)
1414

1515
// Liner takes an item and returns the values its columns should have.
16-
type Liner[T any] func(t T) []string
16+
type Liner[T any] func(t T) ([]string, error)
1717

1818
// Render renders the table to the given io.Writer.
1919
func Render[T any](w io.Writer, items []T, columns []string, liner Liner[T]) error {
2020
tw := newTabWriter(w, columns...)
2121
for _, item := range items {
22-
fmt.Fprintln(tw, strings.Join(liner(item), "\t"))
22+
line, err := liner(item)
23+
if err != nil {
24+
return err
25+
}
26+
fmt.Fprintln(tw, strings.Join(line, "\t"))
2327
}
2428
if len(items) == 0 {
2529
fmt.Fprintln(tw, "No items found")
@@ -39,4 +43,3 @@ func newTabWriter(w io.Writer, columns ...string) *tabwriter.Writer {
3943
}
4044
return tw
4145
}
42-

main_test.go

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
package tablewriter
22

33
import (
4+
"fmt"
45
"os"
56
"strconv"
67
"testing"
78
)
89

910
func TestRenderEmpty(t *testing.T) {
10-
if err := Render(os.Stderr, nil, []string{"Item"}, func(item string) []string {
11-
return []string{"doesnt matter"}
11+
if err := Render(os.Stderr, nil, []string{"Item"}, func(item string) ([]string, error) {
12+
return []string{"doesnt matter"}, nil
1213
}); err != nil {
1314
t.Fatal("render failed:", err)
1415
}
@@ -24,9 +25,21 @@ func TestRender(t *testing.T) {
2425
{"Carlos", 32},
2526
{"John", 41},
2627
{"Jose", 28},
27-
}, []string{"Name", "Age"}, func(item Person) []string {
28-
return []string{item.Name, strconv.Itoa(item.Age)}
28+
}, []string{"Name", "Age"}, func(item Person) ([]string, error) {
29+
return []string{item.Name, strconv.Itoa(item.Age)}, nil
2930
}); err != nil {
3031
t.Fatal("render failed:", err)
3132
}
3233
}
34+
35+
func TestRenderError(t *testing.T) {
36+
if err := Render(os.Stderr, []Person{
37+
{"Carlos", 32},
38+
{"John", 41},
39+
{"Jose", 28},
40+
}, []string{"Name", "Age"}, func(item Person) ([]string, error) {
41+
return nil, fmt.Errorf("foo bar")
42+
}); err == nil {
43+
t.Fatal("expected render to fail, got nil")
44+
}
45+
}

0 commit comments

Comments
 (0)