Skip to content

Commit

Permalink
feat: add ScalarLiterals() to bypass string representations of scalar…
Browse files Browse the repository at this point in the history
… type aliases

The canonical example being `time.Duration`, which will display
`time.Second` as `time.Duration(1000000000)` with this option enabled.

Fixes #19
  • Loading branch information
alecthomas committed Aug 22, 2023
1 parent fba37ee commit cded7b9
Show file tree
Hide file tree
Showing 5 changed files with 20 additions and 4 deletions.
File renamed without changes.
2 changes: 1 addition & 1 deletion bin/go
2 changes: 1 addition & 1 deletion bin/gofmt
14 changes: 12 additions & 2 deletions repr.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ func IgnoreGoStringer() Option { return func(o *Printer) { o.ignoreGoStringer =
// IgnorePrivate disables private field members from output.
func IgnorePrivate() Option { return func(o *Printer) { o.ignorePrivate = true } }

// ScalarLiterals forces the use of literals for scalars, rather than a string representation if available.
//
// For example, `time.Hour` will be printed as `time.Duration(3600000000000)` rather than `time.Duration(1h0m0s)`.
func ScalarLiterals() Option { return func(o *Printer) { o.useLiterals = true } }

// Hide excludes the given types from representation, instead just printing the name of the type.
func Hide(ts ...any) Option {
return func(o *Printer) {
Expand All @@ -97,6 +102,7 @@ type Printer struct {
explicitTypes bool
exclude map[reflect.Type]bool
w io.Writer
useLiterals bool
}

// New creates a new Printer on w with the given Options.
Expand Down Expand Up @@ -322,10 +328,14 @@ func (p *Printer) reprValue(seen map[reflect.Value]bool, v reflect.Value, indent
fmt.Fprint(p.w, substAny(v.Type()))

default:
value := fmt.Sprintf("%v", v)
if p.useLiterals {
value = fmt.Sprintf("%#v", v)
}
if t.Name() != realKindName[t.Kind()] || p.alwaysIncludeType || isAnyValue {
fmt.Fprintf(p.w, "%s(%v)", t, v)
fmt.Fprintf(p.w, "%s(%s)", t, value)
} else {
fmt.Fprintf(p.w, "%v", v)
fmt.Fprintf(p.w, "%s", value)
}
}
}
Expand Down
6 changes: 6 additions & 0 deletions repr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"runtime"
"strings"
"testing"
"time"
)

func equal(t *testing.T, want, have string) {
Expand Down Expand Up @@ -231,3 +232,8 @@ func TestReprFunc(t *testing.T) {
inout := func(interface{}) (any, error) { panic("not implemented") }
equal(t, "func(any) (any, error)", String(inout))
}

func TestScalarLiterals(t *testing.T) {
d := time.Second
equal(t, "time.Duration(1000000000)", String(d, ScalarLiterals()))
}

0 comments on commit cded7b9

Please sign in to comment.