report.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2017, The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package cmp
  5. // defaultReporter implements the reporter interface.
  6. //
  7. // As Equal serially calls the PushStep, Report, and PopStep methods, the
  8. // defaultReporter constructs a tree-based representation of the compared value
  9. // and the result of each comparison (see valueNode).
  10. //
  11. // When the String method is called, the FormatDiff method transforms the
  12. // valueNode tree into a textNode tree, which is a tree-based representation
  13. // of the textual output (see textNode).
  14. //
  15. // Lastly, the textNode.String method produces the final report as a string.
  16. type defaultReporter struct {
  17. root *valueNode
  18. curr *valueNode
  19. }
  20. func (r *defaultReporter) PushStep(ps PathStep) {
  21. r.curr = r.curr.PushStep(ps)
  22. if r.root == nil {
  23. r.root = r.curr
  24. }
  25. }
  26. func (r *defaultReporter) Report(rs Result) {
  27. r.curr.Report(rs)
  28. }
  29. func (r *defaultReporter) PopStep() {
  30. r.curr = r.curr.PopStep()
  31. }
  32. // String provides a full report of the differences detected as a structured
  33. // literal in pseudo-Go syntax. String may only be called after the entire tree
  34. // has been traversed.
  35. func (r *defaultReporter) String() string {
  36. assert(r.root != nil && r.curr == nil)
  37. if r.root.NumDiff == 0 {
  38. return ""
  39. }
  40. ptrs := new(pointerReferences)
  41. text := formatOptions{}.FormatDiff(r.root, ptrs)
  42. resolveReferences(text)
  43. return text.String()
  44. }
  45. func assert(ok bool) {
  46. if !ok {
  47. panic("assertion failure")
  48. }
  49. }