|
| 1 | +// Copyright 2017 The toolkit Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a MIT License |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package debugutil |
| 6 | + |
| 7 | +import ( |
| 8 | + "fmt" |
| 9 | + "reflect" |
| 10 | + "strings" |
| 11 | +) |
| 12 | + |
| 13 | +const ( |
| 14 | + bracketOpen string = "{\n" |
| 15 | + bracketClose string = "}" |
| 16 | + pointerSign string = "&" |
| 17 | + nilSign string = "nil" |
| 18 | +) |
| 19 | + |
| 20 | +// PrettyPrint generates a human readable representation of the value v. |
| 21 | +func PrettySprint(v interface{}) string { |
| 22 | + value := reflect.ValueOf(v) |
| 23 | + switch value.Kind() { |
| 24 | + case reflect.Struct: |
| 25 | + str := fullName(value.Type()) + bracketOpen |
| 26 | + for i := 0; i < value.NumField(); i++ { |
| 27 | + l := string(value.Type().Field(i).Name[0]) |
| 28 | + if strings.ToUpper(l) == l { |
| 29 | + str += fmt.Sprintf("%s: %s,\n", value.Type().Field(i).Name, PrettySprint(value.Field(i).Interface())) |
| 30 | + } |
| 31 | + } |
| 32 | + str += bracketClose |
| 33 | + return str |
| 34 | + case reflect.Map: |
| 35 | + str := "map[" + fullName(value.Type().Key()) + "]" + fullName(value.Type().Elem()) + bracketOpen |
| 36 | + for _, k := range value.MapKeys() { |
| 37 | + str += fmt.Sprintf(`"%s":%s,\n`, k.String(), PrettySprint(value.MapIndex(k).Interface())) |
| 38 | + } |
| 39 | + str += bracketClose |
| 40 | + return str |
| 41 | + case reflect.Ptr: |
| 42 | + if e := value.Elem(); e.IsValid() { |
| 43 | + return fmt.Sprintf("%s%s", pointerSign, PrettySprint(e.Interface())) |
| 44 | + } |
| 45 | + return nilSign |
| 46 | + case reflect.Slice: |
| 47 | + str := "[]" + fullName(value.Type().Elem()) + bracketOpen |
| 48 | + for i := 0; i < value.Len(); i++ { |
| 49 | + str += fmt.Sprintf("%s,\n", PrettySprint(value.Index(i).Interface())) |
| 50 | + } |
| 51 | + str += bracketClose |
| 52 | + return str |
| 53 | + default: |
| 54 | + return fmt.Sprintf("%#v", v) |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +func pkgName(t reflect.Type) string { |
| 59 | + pkg := t.PkgPath() |
| 60 | + c := strings.Split(pkg, "/") |
| 61 | + return c[len(c)-1] |
| 62 | +} |
| 63 | + |
| 64 | +func fullName(t reflect.Type) string { |
| 65 | + if pkg := pkgName(t); pkg != "" { |
| 66 | + return pkg + "." + t.Name() |
| 67 | + } |
| 68 | + return t.Name() |
| 69 | +} |
0 commit comments