public.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. // Copyright 2013 Google Inc. All rights reserved.
  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
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "net"
  20. "reflect"
  21. "time"
  22. "github.com/kylelemons/godebug/diff"
  23. )
  24. // A Config represents optional configuration parameters for formatting.
  25. //
  26. // Some options, notably ShortList, dramatically increase the overhead
  27. // of pretty-printing a value.
  28. type Config struct {
  29. // Verbosity options
  30. Compact bool // One-line output. Overrides Diffable.
  31. Diffable bool // Adds extra newlines for more easily diffable output.
  32. // Field and value options
  33. IncludeUnexported bool // Include unexported fields in output
  34. PrintStringers bool // Call String on a fmt.Stringer
  35. PrintTextMarshalers bool // Call MarshalText on an encoding.TextMarshaler
  36. SkipZeroFields bool // Skip struct fields that have a zero value.
  37. // Output transforms
  38. ShortList int // Maximum character length for short lists if nonzero.
  39. // Type-specific overrides
  40. //
  41. // Formatter maps a type to a function that will provide a one-line string
  42. // representation of the input value. Conceptually:
  43. // Formatter[reflect.TypeOf(v)](v) = "v as a string"
  44. //
  45. // Note that the first argument need not explicitly match the type, it must
  46. // merely be callable with it.
  47. //
  48. // When processing an input value, if its type exists as a key in Formatter:
  49. // 1) If the value is nil, no stringification is performed.
  50. // This allows overriding of PrintStringers and PrintTextMarshalers.
  51. // 2) The value will be called with the input as its only argument.
  52. // The function must return a string as its first return value.
  53. //
  54. // In addition to func literals, two common values for this will be:
  55. // fmt.Sprint (function) func Sprint(...interface{}) string
  56. // Type.String (method) func (Type) String() string
  57. //
  58. // Note that neither of these work if the String method is a pointer
  59. // method and the input will be provided as a value. In that case,
  60. // use a function that calls .String on the formal value parameter.
  61. Formatter map[reflect.Type]interface{}
  62. // If TrackCycles is enabled, pretty will detect and track
  63. // self-referential structures. If a self-referential structure (aka a
  64. // "recursive" value) is detected, numbered placeholders will be emitted.
  65. //
  66. // Pointer tracking is disabled by default for performance reasons.
  67. TrackCycles bool
  68. }
  69. // Default Config objects
  70. var (
  71. // DefaultFormatter is the default set of overrides for stringification.
  72. DefaultFormatter = map[reflect.Type]interface{}{
  73. reflect.TypeOf(time.Time{}): fmt.Sprint,
  74. reflect.TypeOf(net.IP{}): fmt.Sprint,
  75. reflect.TypeOf((*error)(nil)).Elem(): fmt.Sprint,
  76. }
  77. // CompareConfig is the default configuration used for Compare.
  78. CompareConfig = &Config{
  79. Diffable: true,
  80. IncludeUnexported: true,
  81. Formatter: DefaultFormatter,
  82. }
  83. // DefaultConfig is the default configuration used for all other top-level functions.
  84. DefaultConfig = &Config{
  85. Formatter: DefaultFormatter,
  86. }
  87. // CycleTracker is a convenience config for formatting and comparing recursive structures.
  88. CycleTracker = &Config{
  89. Diffable: true,
  90. Formatter: DefaultFormatter,
  91. TrackCycles: true,
  92. }
  93. )
  94. func (cfg *Config) fprint(buf *bytes.Buffer, vals ...interface{}) {
  95. ref := &reflector{
  96. Config: cfg,
  97. }
  98. if cfg.TrackCycles {
  99. ref.pointerTracker = new(pointerTracker)
  100. }
  101. for i, val := range vals {
  102. if i > 0 {
  103. buf.WriteByte('\n')
  104. }
  105. newFormatter(cfg, buf).write(ref.val2node(reflect.ValueOf(val)))
  106. }
  107. }
  108. // Print writes the DefaultConfig representation of the given values to standard output.
  109. func Print(vals ...interface{}) {
  110. DefaultConfig.Print(vals...)
  111. }
  112. // Print writes the configured presentation of the given values to standard output.
  113. func (cfg *Config) Print(vals ...interface{}) {
  114. fmt.Println(cfg.Sprint(vals...))
  115. }
  116. // Sprint returns a string representation of the given value according to the DefaultConfig.
  117. func Sprint(vals ...interface{}) string {
  118. return DefaultConfig.Sprint(vals...)
  119. }
  120. // Sprint returns a string representation of the given value according to cfg.
  121. func (cfg *Config) Sprint(vals ...interface{}) string {
  122. buf := new(bytes.Buffer)
  123. cfg.fprint(buf, vals...)
  124. return buf.String()
  125. }
  126. // Fprint writes the representation of the given value to the writer according to the DefaultConfig.
  127. func Fprint(w io.Writer, vals ...interface{}) (n int64, err error) {
  128. return DefaultConfig.Fprint(w, vals...)
  129. }
  130. // Fprint writes the representation of the given value to the writer according to the cfg.
  131. func (cfg *Config) Fprint(w io.Writer, vals ...interface{}) (n int64, err error) {
  132. buf := new(bytes.Buffer)
  133. cfg.fprint(buf, vals...)
  134. return buf.WriteTo(w)
  135. }
  136. // Compare returns a string containing a line-by-line unified diff of the
  137. // values in a and b, using the CompareConfig.
  138. //
  139. // Each line in the output is prefixed with '+', '-', or ' ' to indicate which
  140. // side it's from. Lines from the a side are marked with '-', lines from the
  141. // b side are marked with '+' and lines that are the same on both sides are
  142. // marked with ' '.
  143. //
  144. // The comparison is based on the intentionally-untyped output of Print, and as
  145. // such this comparison is pretty forviving. In particular, if the types of or
  146. // types within in a and b are different but have the same representation,
  147. // Compare will not indicate any differences between them.
  148. func Compare(a, b interface{}) string {
  149. return CompareConfig.Compare(a, b)
  150. }
  151. // Compare returns a string containing a line-by-line unified diff of the
  152. // values in got and want according to the cfg.
  153. //
  154. // Each line in the output is prefixed with '+', '-', or ' ' to indicate which
  155. // side it's from. Lines from the a side are marked with '-', lines from the
  156. // b side are marked with '+' and lines that are the same on both sides are
  157. // marked with ' '.
  158. //
  159. // The comparison is based on the intentionally-untyped output of Print, and as
  160. // such this comparison is pretty forviving. In particular, if the types of or
  161. // types within in a and b are different but have the same representation,
  162. // Compare will not indicate any differences between them.
  163. func (cfg *Config) Compare(a, b interface{}) string {
  164. diffCfg := *cfg
  165. diffCfg.Diffable = true
  166. return diff.Diff(cfg.Sprint(a), cfg.Sprint(b))
  167. }