選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 

250 行
6.5 KiB

  1. // Copyright 2016 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package pretty implements a simple pretty-printer. It is intended for
  15. // debugging the output of tests.
  16. //
  17. // It follows pointers and produces multi-line output for complex values like
  18. // slices, maps and structs.
  19. package pretty
  20. import (
  21. "fmt"
  22. "io"
  23. "reflect"
  24. "sort"
  25. "strings"
  26. "time"
  27. )
  28. // Indent is the string output at each level of indentation.
  29. var Indent = " "
  30. // Value returns a value that will print prettily when used as an
  31. // argument for the %v or %s format specifiers.
  32. // With no flags, struct fields and map keys with default values are omitted.
  33. // With the '+' or '#' flags, all values are displayed.
  34. //
  35. // This package does not detect cycles. Attempting to print a Value that
  36. // contains cycles will result in unbounded recursion.
  37. func Value(v interface{}) val { return val{v: v} }
  38. // val is a value.
  39. type val struct{ v interface{} }
  40. // Format implements the fmt.Formatter interface.
  41. func (v val) Format(s fmt.State, c rune) {
  42. if c == 'v' || c == 's' {
  43. fprint(s, reflect.ValueOf(v.v), state{
  44. defaults: s.Flag('+') || s.Flag('#'),
  45. })
  46. } else {
  47. fmt.Fprintf(s, "%%!%c(pretty.val)", c)
  48. }
  49. }
  50. type state struct {
  51. level int
  52. prefix, suffix string
  53. defaults bool
  54. }
  55. const maxLevel = 100
  56. var typeOfTime = reflect.TypeOf(time.Time{})
  57. func fprint(w io.Writer, v reflect.Value, s state) {
  58. if s.level > maxLevel {
  59. fmt.Fprintln(w, "pretty: max nested depth exceeded")
  60. return
  61. }
  62. indent := strings.Repeat(Indent, s.level)
  63. fmt.Fprintf(w, "%s%s", indent, s.prefix)
  64. if isNil(v) {
  65. fmt.Fprintf(w, "nil%s", s.suffix)
  66. return
  67. }
  68. if v.Type().Kind() == reflect.Interface {
  69. v = v.Elem()
  70. }
  71. if v.Type() == typeOfTime {
  72. fmt.Fprintf(w, "%s%s", v.Interface(), s.suffix)
  73. return
  74. }
  75. for v.Type().Kind() == reflect.Ptr {
  76. fmt.Fprintf(w, "&")
  77. v = v.Elem()
  78. }
  79. switch v.Type().Kind() {
  80. default:
  81. fmt.Fprintf(w, "%s%s", short(v), s.suffix)
  82. case reflect.Array:
  83. fmt.Fprintf(w, "%s{\n", v.Type())
  84. for i := 0; i < v.Len(); i++ {
  85. fprint(w, v.Index(i), state{
  86. level: s.level + 1,
  87. prefix: "",
  88. suffix: ",",
  89. defaults: s.defaults,
  90. })
  91. fmt.Fprintln(w)
  92. }
  93. fmt.Fprintf(w, "%s}", indent)
  94. case reflect.Slice:
  95. fmt.Fprintf(w, "%s{", v.Type())
  96. if v.Len() > 0 {
  97. fmt.Fprintln(w)
  98. for i := 0; i < v.Len(); i++ {
  99. fprint(w, v.Index(i), state{
  100. level: s.level + 1,
  101. prefix: "",
  102. suffix: ",",
  103. defaults: s.defaults,
  104. })
  105. fmt.Fprintln(w)
  106. }
  107. }
  108. fmt.Fprintf(w, "%s}%s", indent, s.suffix)
  109. case reflect.Map:
  110. fmt.Fprintf(w, "%s{", v.Type())
  111. if v.Len() > 0 {
  112. fmt.Fprintln(w)
  113. keys := v.MapKeys()
  114. maybeSort(keys, v.Type().Key())
  115. for _, key := range keys {
  116. val := v.MapIndex(key)
  117. if s.defaults || !isDefault(val) {
  118. fprint(w, val, state{
  119. level: s.level + 1,
  120. prefix: short(key) + ": ",
  121. suffix: ",",
  122. defaults: s.defaults,
  123. })
  124. fmt.Fprintln(w)
  125. }
  126. }
  127. }
  128. fmt.Fprintf(w, "%s}%s", indent, s.suffix)
  129. case reflect.Struct:
  130. t := v.Type()
  131. fmt.Fprintf(w, "%s{\n", t)
  132. for i := 0; i < t.NumField(); i++ {
  133. f := v.Field(i)
  134. if s.defaults || !isDefault(f) {
  135. fprint(w, f, state{
  136. level: s.level + 1,
  137. prefix: t.Field(i).Name + ": ",
  138. suffix: ",",
  139. defaults: s.defaults,
  140. })
  141. fmt.Fprintln(w)
  142. }
  143. }
  144. fmt.Fprintf(w, "%s}%s", indent, s.suffix)
  145. }
  146. }
  147. func isNil(v reflect.Value) bool {
  148. if !v.IsValid() {
  149. return true
  150. }
  151. switch v.Type().Kind() {
  152. case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
  153. return v.IsNil()
  154. default:
  155. return false
  156. }
  157. }
  158. func isDefault(v reflect.Value) bool {
  159. if !v.IsValid() {
  160. return true
  161. }
  162. t := v.Type()
  163. switch t.Kind() {
  164. case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
  165. return v.IsNil()
  166. default:
  167. if !v.CanInterface() {
  168. return false
  169. }
  170. return t.Comparable() && v.Interface() == reflect.Zero(t).Interface()
  171. }
  172. }
  173. // short returns a short, one-line string for v.
  174. func short(v reflect.Value) string {
  175. if !v.IsValid() {
  176. return "nil"
  177. }
  178. if v.Type().Kind() == reflect.String {
  179. return fmt.Sprintf("%q", v)
  180. }
  181. return fmt.Sprintf("%v", v)
  182. }
  183. func maybeSort(vs []reflect.Value, t reflect.Type) {
  184. if less := lessFunc(t); less != nil {
  185. sort.Sort(&sorter{vs, less})
  186. }
  187. }
  188. // lessFunc returns a function that implements the "<" operator
  189. // for the given type, or nil if the type doesn't support "<" .
  190. func lessFunc(t reflect.Type) func(v1, v2 interface{}) bool {
  191. switch t.Kind() {
  192. case reflect.String:
  193. return func(v1, v2 interface{}) bool { return v1.(string) < v2.(string) }
  194. case reflect.Int:
  195. return func(v1, v2 interface{}) bool { return v1.(int) < v2.(int) }
  196. case reflect.Int8:
  197. return func(v1, v2 interface{}) bool { return v1.(int8) < v2.(int8) }
  198. case reflect.Int16:
  199. return func(v1, v2 interface{}) bool { return v1.(int16) < v2.(int16) }
  200. case reflect.Int32:
  201. return func(v1, v2 interface{}) bool { return v1.(int32) < v2.(int32) }
  202. case reflect.Int64:
  203. return func(v1, v2 interface{}) bool { return v1.(int64) < v2.(int64) }
  204. case reflect.Uint:
  205. return func(v1, v2 interface{}) bool { return v1.(uint) < v2.(uint) }
  206. case reflect.Uint8:
  207. return func(v1, v2 interface{}) bool { return v1.(uint8) < v2.(uint8) }
  208. case reflect.Uint16:
  209. return func(v1, v2 interface{}) bool { return v1.(uint16) < v2.(uint16) }
  210. case reflect.Uint32:
  211. return func(v1, v2 interface{}) bool { return v1.(uint32) < v2.(uint32) }
  212. case reflect.Uint64:
  213. return func(v1, v2 interface{}) bool { return v1.(uint64) < v2.(uint64) }
  214. case reflect.Float32:
  215. return func(v1, v2 interface{}) bool { return v1.(float32) < v2.(float32) }
  216. case reflect.Float64:
  217. return func(v1, v2 interface{}) bool { return v1.(float64) < v2.(float64) }
  218. default:
  219. return nil
  220. }
  221. }
  222. type sorter struct {
  223. vs []reflect.Value
  224. less func(v1, v2 interface{}) bool
  225. }
  226. func (s *sorter) Len() int { return len(s.vs) }
  227. func (s *sorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
  228. func (s *sorter) Less(i, j int) bool { return s.less(s.vs[i].Interface(), s.vs[j].Interface()) }