config.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /*
  2. * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. package spew
  17. import (
  18. "bytes"
  19. "fmt"
  20. "io"
  21. "os"
  22. )
  23. // ConfigState houses the configuration options used by spew to format and
  24. // display values. There is a global instance, Config, that is used to control
  25. // all top-level Formatter and Dump functionality. Each ConfigState instance
  26. // provides methods equivalent to the top-level functions.
  27. //
  28. // The zero value for ConfigState provides no indentation. You would typically
  29. // want to set it to a space or a tab.
  30. //
  31. // Alternatively, you can use NewDefaultConfig to get a ConfigState instance
  32. // with default settings. See the documentation of NewDefaultConfig for default
  33. // values.
  34. type ConfigState struct {
  35. // Indent specifies the string to use for each indentation level. The
  36. // global config instance that all top-level functions use set this to a
  37. // single space by default. If you would like more indentation, you might
  38. // set this to a tab with "\t" or perhaps two spaces with " ".
  39. Indent string
  40. // MaxDepth controls the maximum number of levels to descend into nested
  41. // data structures. The default, 0, means there is no limit.
  42. //
  43. // NOTE: Circular data structures are properly detected, so it is not
  44. // necessary to set this value unless you specifically want to limit deeply
  45. // nested data structures.
  46. MaxDepth int
  47. // DisableMethods specifies whether or not error and Stringer interfaces are
  48. // invoked for types that implement them.
  49. DisableMethods bool
  50. // DisablePointerMethods specifies whether or not to check for and invoke
  51. // error and Stringer interfaces on types which only accept a pointer
  52. // receiver when the current type is not a pointer.
  53. //
  54. // NOTE: This might be an unsafe action since calling one of these methods
  55. // with a pointer receiver could technically mutate the value, however,
  56. // in practice, types which choose to satisify an error or Stringer
  57. // interface with a pointer receiver should not be mutating their state
  58. // inside these interface methods. As a result, this option relies on
  59. // access to the unsafe package, so it will not have any effect when
  60. // running in environments without access to the unsafe package such as
  61. // Google App Engine or with the "safe" build tag specified.
  62. DisablePointerMethods bool
  63. // DisablePointerAddresses specifies whether to disable the printing of
  64. // pointer addresses. This is useful when diffing data structures in tests.
  65. DisablePointerAddresses bool
  66. // DisableCapacities specifies whether to disable the printing of capacities
  67. // for arrays, slices, maps and channels. This is useful when diffing
  68. // data structures in tests.
  69. DisableCapacities bool
  70. // ContinueOnMethod specifies whether or not recursion should continue once
  71. // a custom error or Stringer interface is invoked. The default, false,
  72. // means it will print the results of invoking the custom error or Stringer
  73. // interface and return immediately instead of continuing to recurse into
  74. // the internals of the data type.
  75. //
  76. // NOTE: This flag does not have any effect if method invocation is disabled
  77. // via the DisableMethods or DisablePointerMethods options.
  78. ContinueOnMethod bool
  79. // SortKeys specifies map keys should be sorted before being printed. Use
  80. // this to have a more deterministic, diffable output. Note that only
  81. // native types (bool, int, uint, floats, uintptr and string) and types
  82. // that support the error or Stringer interfaces (if methods are
  83. // enabled) are supported, with other types sorted according to the
  84. // reflect.Value.String() output which guarantees display stability.
  85. SortKeys bool
  86. // SpewKeys specifies that, as a last resort attempt, map keys should
  87. // be spewed to strings and sorted by those strings. This is only
  88. // considered if SortKeys is true.
  89. SpewKeys bool
  90. }
  91. // Config is the active configuration of the top-level functions.
  92. // The configuration can be changed by modifying the contents of spew.Config.
  93. var Config = ConfigState{Indent: " "}
  94. // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were
  95. // passed with a Formatter interface returned by c.NewFormatter. It returns
  96. // the formatted string as a value that satisfies error. See NewFormatter
  97. // for formatting details.
  98. //
  99. // This function is shorthand for the following syntax:
  100. //
  101. // fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b))
  102. func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) {
  103. return fmt.Errorf(format, c.convertArgs(a)...)
  104. }
  105. // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were
  106. // passed with a Formatter interface returned by c.NewFormatter. It returns
  107. // the number of bytes written and any write error encountered. See
  108. // NewFormatter for formatting details.
  109. //
  110. // This function is shorthand for the following syntax:
  111. //
  112. // fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b))
  113. func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) {
  114. return fmt.Fprint(w, c.convertArgs(a)...)
  115. }
  116. // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were
  117. // passed with a Formatter interface returned by c.NewFormatter. It returns
  118. // the number of bytes written and any write error encountered. See
  119. // NewFormatter for formatting details.
  120. //
  121. // This function is shorthand for the following syntax:
  122. //
  123. // fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b))
  124. func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
  125. return fmt.Fprintf(w, format, c.convertArgs(a)...)
  126. }
  127. // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it
  128. // passed with a Formatter interface returned by c.NewFormatter. See
  129. // NewFormatter for formatting details.
  130. //
  131. // This function is shorthand for the following syntax:
  132. //
  133. // fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b))
  134. func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
  135. return fmt.Fprintln(w, c.convertArgs(a)...)
  136. }
  137. // Print is a wrapper for fmt.Print that treats each argument as if it were
  138. // passed with a Formatter interface returned by c.NewFormatter. It returns
  139. // the number of bytes written and any write error encountered. See
  140. // NewFormatter for formatting details.
  141. //
  142. // This function is shorthand for the following syntax:
  143. //
  144. // fmt.Print(c.NewFormatter(a), c.NewFormatter(b))
  145. func (c *ConfigState) Print(a ...interface{}) (n int, err error) {
  146. return fmt.Print(c.convertArgs(a)...)
  147. }
  148. // Printf is a wrapper for fmt.Printf that treats each argument as if it were
  149. // passed with a Formatter interface returned by c.NewFormatter. It returns
  150. // the number of bytes written and any write error encountered. See
  151. // NewFormatter for formatting details.
  152. //
  153. // This function is shorthand for the following syntax:
  154. //
  155. // fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b))
  156. func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) {
  157. return fmt.Printf(format, c.convertArgs(a)...)
  158. }
  159. // Println is a wrapper for fmt.Println that treats each argument as if it were
  160. // passed with a Formatter interface returned by c.NewFormatter. It returns
  161. // the number of bytes written and any write error encountered. See
  162. // NewFormatter for formatting details.
  163. //
  164. // This function is shorthand for the following syntax:
  165. //
  166. // fmt.Println(c.NewFormatter(a), c.NewFormatter(b))
  167. func (c *ConfigState) Println(a ...interface{}) (n int, err error) {
  168. return fmt.Println(c.convertArgs(a)...)
  169. }
  170. // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were
  171. // passed with a Formatter interface returned by c.NewFormatter. It returns
  172. // the resulting string. See NewFormatter for formatting details.
  173. //
  174. // This function is shorthand for the following syntax:
  175. //
  176. // fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b))
  177. func (c *ConfigState) Sprint(a ...interface{}) string {
  178. return fmt.Sprint(c.convertArgs(a)...)
  179. }
  180. // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were
  181. // passed with a Formatter interface returned by c.NewFormatter. It returns
  182. // the resulting string. See NewFormatter for formatting details.
  183. //
  184. // This function is shorthand for the following syntax:
  185. //
  186. // fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b))
  187. func (c *ConfigState) Sprintf(format string, a ...interface{}) string {
  188. return fmt.Sprintf(format, c.convertArgs(a)...)
  189. }
  190. // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it
  191. // were passed with a Formatter interface returned by c.NewFormatter. It
  192. // returns the resulting string. See NewFormatter for formatting details.
  193. //
  194. // This function is shorthand for the following syntax:
  195. //
  196. // fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b))
  197. func (c *ConfigState) Sprintln(a ...interface{}) string {
  198. return fmt.Sprintln(c.convertArgs(a)...)
  199. }
  200. /*
  201. NewFormatter returns a custom formatter that satisfies the fmt.Formatter
  202. interface. As a result, it integrates cleanly with standard fmt package
  203. printing functions. The formatter is useful for inline printing of smaller data
  204. types similar to the standard %v format specifier.
  205. The custom formatter only responds to the %v (most compact), %+v (adds pointer
  206. addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb
  207. combinations. Any other verbs such as %x and %q will be sent to the the
  208. standard fmt package for formatting. In addition, the custom formatter ignores
  209. the width and precision arguments (however they will still work on the format
  210. specifiers not handled by the custom formatter).
  211. Typically this function shouldn't be called directly. It is much easier to make
  212. use of the custom formatter by calling one of the convenience functions such as
  213. c.Printf, c.Println, or c.Printf.
  214. */
  215. func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter {
  216. return newFormatter(c, v)
  217. }
  218. // Fdump formats and displays the passed arguments to io.Writer w. It formats
  219. // exactly the same as Dump.
  220. func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) {
  221. fdump(c, w, a...)
  222. }
  223. /*
  224. Dump displays the passed parameters to standard out with newlines, customizable
  225. indentation, and additional debug information such as complete types and all
  226. pointer addresses used to indirect to the final value. It provides the
  227. following features over the built-in printing facilities provided by the fmt
  228. package:
  229. * Pointers are dereferenced and followed
  230. * Circular data structures are detected and handled properly
  231. * Custom Stringer/error interfaces are optionally invoked, including
  232. on unexported types
  233. * Custom types which only implement the Stringer/error interfaces via
  234. a pointer receiver are optionally invoked when passing non-pointer
  235. variables
  236. * Byte arrays and slices are dumped like the hexdump -C command which
  237. includes offsets, byte values in hex, and ASCII output
  238. The configuration options are controlled by modifying the public members
  239. of c. See ConfigState for options documentation.
  240. See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to
  241. get the formatted result as a string.
  242. */
  243. func (c *ConfigState) Dump(a ...interface{}) {
  244. fdump(c, os.Stdout, a...)
  245. }
  246. // Sdump returns a string with the passed arguments formatted exactly the same
  247. // as Dump.
  248. func (c *ConfigState) Sdump(a ...interface{}) string {
  249. var buf bytes.Buffer
  250. fdump(c, &buf, a...)
  251. return buf.String()
  252. }
  253. // convertArgs accepts a slice of arguments and returns a slice of the same
  254. // length with each argument converted to a spew Formatter interface using
  255. // the ConfigState associated with s.
  256. func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) {
  257. formatters = make([]interface{}, len(args))
  258. for index, arg := range args {
  259. formatters[index] = newFormatter(c, arg)
  260. }
  261. return formatters
  262. }
  263. // NewDefaultConfig returns a ConfigState with the following default settings.
  264. //
  265. // Indent: " "
  266. // MaxDepth: 0
  267. // DisableMethods: false
  268. // DisablePointerMethods: false
  269. // ContinueOnMethod: false
  270. // SortKeys: false
  271. func NewDefaultConfig() *ConfigState {
  272. return &ConfigState{Indent: " "}
  273. }