Skip to content

Commit

Permalink
✨ enhanced: dump - support for parse alias type of time.Time. close #200
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Nov 2, 2024
1 parent 49bc6ed commit e959274
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 7 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@
*.cov
.DS_Store

*~
testdata/
vendor/
24 changes: 17 additions & 7 deletions dump/dumper.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,13 +279,13 @@ func (d *Dumper) printRValue(t reflect.Type, v reflect.Value) {

// up: special handel time.Time struct
if t == timeType {
var timeStr string
if v.CanInterface() {
timeStr = v.Interface().(time.Time).Format(time.RFC3339)
} else {
timeStr = v.String()
}
d.printf("time.Time(%s),\n", d.ColorTheme.string(timeStr))
d.printf("time.Time(%s),\n", d.ColorTheme.string(d.fmtTimeValue(v)))
break
}
// up: if is type alias of time.Time, use datetime format
if !isPtr && t.ConvertibleTo(timeType) {
tv := v.Convert(timeType)
d.printf("%s(%s),\n", t.String(), d.ColorTheme.string(d.fmtTimeValue(tv)))
break
}

Expand Down Expand Up @@ -416,6 +416,16 @@ func (d *Dumper) rvStringer(rt reflect.Type, rv reflect.Value) string {
return ""
}

func (d *Dumper) fmtTimeValue(v reflect.Value) string {
var timeStr string
if v.CanInterface() {
timeStr = v.Interface().(time.Time).Format(time.RFC3339)
} else {
timeStr = v.String()
}
return timeStr
}

func (d *Dumper) print(v ...any) {
if d.NoColor {
_, _ = fmt.Fprint(d.Output, v...)
Expand Down
43 changes: 43 additions & 0 deletions dump/issues_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package dump_test

import (
"fmt"
"reflect"
"testing"
"time"

"github.com/gookit/goutil/dump"
)

func isTimeType(v interface{}) bool {
return reflect.TypeOf(v).ConvertibleTo(reflect.TypeOf(time.Time{}))
}

// https://github.com/gookit/goutil/issues/200
func TestIssues_200(t *testing.T) {
var dateValue = "2024-10-02T19:02:46"
type RestorePointTimestamp time.Time
type NormalRestore struct {
TimeStamp time.Time
}
type CustomRestore struct {
TimeStamp RestorePointTimestamp
}

t.Run("normal time", func(t *testing.T) {
normal, _ := time.Parse("2006-01-02T15:04:05", dateValue)
normalRestore := NormalRestore{
TimeStamp: normal,
}
dump.Print(normalRestore)
})

t.Run("custom time", func(t *testing.T) {
custom, _ := time.Parse("2006-01-02T15:04:05", dateValue)
customRestore := CustomRestore{
TimeStamp: RestorePointTimestamp(custom),
}
fmt.Println(isTimeType(customRestore.TimeStamp))
dump.Print(customRestore)
})
}

0 comments on commit e959274

Please sign in to comment.