Commit 135288e3 authored by Kyle Lemons's avatar Kyle Lemons

Add support for TextMarshalers

parent 21cb3784
......@@ -35,6 +35,7 @@ type Config struct {
// Field and value options
IncludeUnexported bool // Include unexported fields in output
PrintStringers bool // Call String on a fmt.Stringer
NoTextMarshalers bool // Don't automatically call MarshalText
SkipZeroFields bool // Skip struct fields that have a zero value.
// Output transforms
......
......@@ -15,6 +15,7 @@
package pretty
import (
"encoding"
"fmt"
"reflect"
"sort"
......@@ -31,10 +32,15 @@ func isZeroVal(val reflect.Value) bool {
func (c *Config) val2node(val reflect.Value) node {
// TODO(kevlar): pointer tracking?
if c.PrintStringers && val.CanInterface() {
stringer, ok := val.Interface().(fmt.Stringer)
if ok {
return stringVal(stringer.String())
if val.CanInterface() {
v := val.Interface()
if s, ok := v.(fmt.Stringer); ok && c.PrintStringers {
return stringVal(s.String())
}
if t, ok := v.(encoding.TextMarshaler); ok && !c.NoTextMarshalers {
if raw, err := t.MarshalText(); err == nil { // if NOT an error
return stringVal(string(raw))
}
}
}
......
......@@ -15,6 +15,7 @@
package pretty
import (
"net"
"reflect"
"testing"
"time"
......@@ -78,6 +79,11 @@ func TestVal2nodeDefault(t *testing.T) {
3,
rawVal("3"),
},
{
"TextMarshaler",
net.ParseIP("dead:beef::1"),
stringVal("dead:beef::1"),
},
}
for _, test := range tests {
......@@ -120,7 +126,17 @@ func TestVal2node(t *testing.T) {
struct{ Date time.Time }{time.Unix(1234567890, 0).UTC()},
DefaultConfig,
keyvals{
{"Date", keyvals{}}, // empty struct, it has unexported fields
{"Date", stringVal("2009-02-13T23:31:30Z")},
},
},
{
"time w/o TextMarshalers",
struct{ Date time.Time }{time.Unix(1234567890, 0).UTC()},
&Config{
NoTextMarshalers: true,
},
keyvals{
{"Date", keyvals{}},
},
},
{
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment