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