Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion formatter.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package pretty

import (
"encoding"
"fmt"
"io"
"reflect"
Expand Down Expand Up @@ -166,7 +167,20 @@ func (p *printer) printValue(v reflect.Value, showType, quote bool) {
io.WriteString(p, t.String())
}
writeByte(p, '{')
if nonzero(v) {
printed := false
if v.CanInterface() {
switch vv := v.Interface().(type) {
case fmt.Stringer:
p.fmtString(vv.String(), true)
printed = true
case encoding.TextMarshaler:
if b, err := vv.MarshalText(); err == nil {
p.fmtString(string(b), true)
printed = true
}
}
}
if !printed && nonzero(v) {
expand := !canInline(v.Type())
pp := p
if expand {
Expand Down
44 changes: 44 additions & 0 deletions formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"io"
"strings"
"testing"
"time"
"unsafe"
)

Expand Down Expand Up @@ -259,3 +260,46 @@ func TestCycle(t *testing.T) {
*iv = *i
t.Logf("Example long interface cycle:\n%# v", Formatter(i))
}

func Test(t *testing.T) {
date := time.Date(2006, 1, 2, 3, 4, 5, .678901e9, time.Local)

s := fmt.Sprintf("%s", Formatter(date))

if date.String() != s {
t.Errorf("expected %s, got %s", date.String(), s)
}
}

type StringerStruct struct{}

func (t StringerStruct) String() string {
return "StringerStruct"
}

func TestStringer(t *testing.T) {
s := new(StringerStruct)

str := fmt.Sprintf("%s", Formatter(s))

if s.String() != str {
t.Errorf("expected %s, got %s", s.String(), str)
}
}

type MarshalTextStruct struct{}

func (t MarshalTextStruct) MarshalText() ([]byte, error) {
return []byte("MarshalTextStruct"), nil
}

func TestMarshalTextStruct(t *testing.T) {
s := new(MarshalTextStruct)

m, _ := s.MarshalText()
str := fmt.Sprintf("%s", Formatter(m))

if string(m) != str {
t.Errorf("expected %s, got %s", m, str)
}
}