-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
12d25a4
commit d35f167
Showing
3 changed files
with
85 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"io" | ||
"sort" | ||
) | ||
|
||
// RowRenderer render the row to a file descriptor. | ||
type RowRenderer interface { | ||
// AddRow adds a row to writer. | ||
AddRow(field, value string) | ||
// AddRowMap appends the row by map input. | ||
AddRowMap(values map[string]string) | ||
// Render the rows. | ||
Render() | ||
} | ||
|
||
// NewRowRender creates the printer. | ||
func NewRowRender(w io.Writer) RowRenderer { | ||
return &pw{w, make([][]string, 0)} | ||
} | ||
|
||
type pw struct { | ||
w io.Writer | ||
rows [][]string | ||
} | ||
|
||
// AddRow adds a row to writer. | ||
func (p *pw) AddRow(field, value string) { | ||
r := []string{field, value} | ||
p.rows = append(p.rows, r) | ||
} | ||
|
||
// AddRowMap appends the row from map. It sorts the map by default. | ||
func (p *pw) AddRowMap(values map[string]string) { | ||
keys := make([]string, 0, len(values)) | ||
for k := range values { | ||
keys = append(keys, k) | ||
} | ||
sort.Strings(keys) | ||
|
||
for _, name := range keys { | ||
r := []string{name, values[name]} | ||
p.rows = append(p.rows, r) | ||
} | ||
|
||
} | ||
|
||
// Render the rows to output | ||
func (p *pw) Render() { | ||
for _, l := range p.rows { | ||
fmt.Fprintf(p.w, "%s: %s\n", l[0], l[1]) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package main | ||
|
||
import ( | ||
"bytes" | ||
"testing" | ||
) | ||
|
||
func TestRowPrinter(t *testing.T) { | ||
buf := new(bytes.Buffer) | ||
pw := &pw{buf, make([][]string, 0)} | ||
pw.AddRow("foo", "bar") | ||
pw.Render() | ||
|
||
got := buf.String() | ||
want := "foo: bar\n" | ||
|
||
if got != want { | ||
t.Errorf("Got: %s - want: %s", buf, want) | ||
} | ||
|
||
} |