1 // Copyright 2019, 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.md file.
15 "github.com/google/go-cmp/cmp/internal/flags"
18 var randBool = rand.New(rand.NewSource(time.Now().Unix())).Intn(2) == 0
20 const maxColumnLength = 80
24 func (n indentMode) appendIndent(b []byte, d diffMode) []byte {
25 // The output of Diff is documented as being unstable to provide future
26 // flexibility in changing the output for more humanly readable reports.
27 // This logic intentionally introduces instability to the exact output
28 // so that users can detect accidental reliance on stability early on,
29 // rather than much later when an actual change to the format occurs.
30 if flags.Deterministic || randBool {
31 // Use regular spaces (U+0020).
33 case diffUnknown, diffIdentical:
36 b = append(b, "- "...)
38 b = append(b, "+ "...)
41 // Use non-breaking spaces (U+00a0).
43 case diffUnknown, diffIdentical:
46 b = append(b, "- "...)
48 b = append(b, "+ "...)
51 return repeatCount(n).appendChar(b, '\t')
56 func (n repeatCount) appendChar(b []byte, c byte) []byte {
63 // textNode is a simplified tree-based representation of structured text.
64 // Possible node types are textWrap, textList, or textLine.
65 type textNode interface {
66 // Len reports the length in bytes of a single-line version of the tree.
67 // Nested textRecord.Diff and textRecord.Comment fields are ignored.
69 // Equal reports whether the two trees are structurally identical.
70 // Nested textRecord.Diff and textRecord.Comment fields are compared.
72 // String returns the string representation of the text tree.
73 // It is not guaranteed that len(x.String()) == x.Len(),
74 // nor that x.String() == y.String() implies that x.Equal(y).
77 // formatCompactTo formats the contents of the tree as a single-line string
78 // to the provided buffer. Any nested textRecord.Diff and textRecord.Comment
79 // fields are ignored.
81 // However, not all nodes in the tree should be collapsed as a single-line.
82 // If a node can be collapsed as a single-line, it is replaced by a textLine
83 // node. Since the top-level node cannot replace itself, this also returns
84 // the current node itself.
86 // This does not mutate the receiver.
87 formatCompactTo([]byte, diffMode) ([]byte, textNode)
88 // formatExpandedTo formats the contents of the tree as a multi-line string
89 // to the provided buffer. In order for column alignment to operate well,
90 // formatCompactTo must be called before calling formatExpandedTo.
91 formatExpandedTo([]byte, diffMode, indentMode) []byte
94 // textWrap is a wrapper that concatenates a prefix and/or a suffix
95 // to the underlying node.
96 type textWrap struct {
97 Prefix string // e.g., "bytes.Buffer{"
98 Value textNode // textWrap | textList | textLine
99 Suffix string // e.g., "}"
100 Metadata interface{} // arbitrary metadata; has no effect on formatting
103 func (s *textWrap) Len() int {
104 return len(s.Prefix) + s.Value.Len() + len(s.Suffix)
106 func (s1 *textWrap) Equal(s2 textNode) bool {
107 if s2, ok := s2.(*textWrap); ok {
108 return s1.Prefix == s2.Prefix && s1.Value.Equal(s2.Value) && s1.Suffix == s2.Suffix
112 func (s *textWrap) String() string {
115 _, s2 := s.formatCompactTo(nil, d)
116 b := n.appendIndent(nil, d) // Leading indent
117 b = s2.formatExpandedTo(b, d, n) // Main body
118 b = append(b, '\n') // Trailing newline
121 func (s *textWrap) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) {
122 n0 := len(b) // Original buffer length
123 b = append(b, s.Prefix...)
124 b, s.Value = s.Value.formatCompactTo(b, d)
125 b = append(b, s.Suffix...)
126 if _, ok := s.Value.(textLine); ok {
127 return b, textLine(b[n0:])
131 func (s *textWrap) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte {
132 b = append(b, s.Prefix...)
133 b = s.Value.formatExpandedTo(b, d, n)
134 b = append(b, s.Suffix...)
138 // textList is a comma-separated list of textWrap or textLine nodes.
139 // The list may be formatted as multi-lines or single-line at the discretion
140 // of the textList.formatCompactTo method.
141 type textList []textRecord
142 type textRecord struct {
143 Diff diffMode // e.g., 0 or '-' or '+'
144 Key string // e.g., "MyField"
145 Value textNode // textWrap | textLine
146 ElideComma bool // avoid trailing comma
147 Comment fmt.Stringer // e.g., "6 identical fields"
150 // AppendEllipsis appends a new ellipsis node to the list if none already
151 // exists at the end. If cs is non-zero it coalesces the statistics with the
152 // previous diffStats.
153 func (s *textList) AppendEllipsis(ds diffStats) {
154 hasStats := !ds.IsZero()
155 if len(*s) == 0 || !(*s)[len(*s)-1].Value.Equal(textEllipsis) {
157 *s = append(*s, textRecord{Value: textEllipsis, ElideComma: true, Comment: ds})
159 *s = append(*s, textRecord{Value: textEllipsis, ElideComma: true})
164 (*s)[len(*s)-1].Comment = (*s)[len(*s)-1].Comment.(diffStats).Append(ds)
168 func (s textList) Len() (n int) {
169 for i, r := range s {
182 func (s1 textList) Equal(s2 textNode) bool {
183 if s2, ok := s2.(textList); ok {
184 if len(s1) != len(s2) {
188 r1, r2 := s1[i], s2[i]
189 if !(r1.Diff == r2.Diff && r1.Key == r2.Key && r1.Value.Equal(r2.Value) && r1.Comment == r2.Comment) {
198 func (s textList) String() string {
199 return (&textWrap{Prefix: "{", Value: s, Suffix: "}"}).String()
202 func (s textList) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) {
203 s = append(textList(nil), s...) // Avoid mutating original
205 // Determine whether we can collapse this list as a single line.
206 n0 := len(b) // Original buffer length
208 for i, r := range s {
209 if r.Diff == diffInserted || r.Diff == diffRemoved {
212 b = append(b, r.Key...)
214 b = append(b, ": "...)
216 b, s[i].Value = r.Value.formatCompactTo(b, d|r.Diff)
217 if _, ok := s[i].Value.(textLine); !ok {
220 if r.Comment != nil {
224 b = append(b, ", "...)
227 // Force multi-lined output when printing a removed/inserted node that
228 // is sufficiently long.
229 if (d == diffInserted || d == diffRemoved) && len(b[n0:]) > maxColumnLength {
233 return b, textLine(b[n0:])
238 func (s textList) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte {
239 alignKeyLens := s.alignLens(
240 func(r textRecord) bool {
241 _, isLine := r.Value.(textLine)
242 return r.Key == "" || !isLine
244 func(r textRecord) int { return utf8.RuneCountInString(r.Key) },
246 alignValueLens := s.alignLens(
247 func(r textRecord) bool {
248 _, isLine := r.Value.(textLine)
249 return !isLine || r.Value.Equal(textEllipsis) || r.Comment == nil
251 func(r textRecord) int { return utf8.RuneCount(r.Value.(textLine)) },
254 // Format lists of simple lists in a batched form.
255 // If the list is sequence of only textLine values,
256 // then batch multiple values on a single line.
258 for _, r := range s {
259 _, isLine := r.Value.(textLine)
260 isSimple = r.Diff == 0 && r.Key == "" && isLine && r.Comment == nil
268 emitBatch := func() {
270 b = n.appendIndent(append(b, '\n'), d)
271 b = append(b, bytes.TrimRight(batch, " ")...)
275 for _, r := range s {
276 line := r.Value.(textLine)
277 if len(batch)+len(line)+len(", ") > maxColumnLength {
280 batch = append(batch, line...)
281 batch = append(batch, ", "...)
285 return n.appendIndent(append(b, '\n'), d)
288 // Format the list as a multi-lined output.
290 for i, r := range s {
291 b = n.appendIndent(append(b, '\n'), d|r.Diff)
293 b = append(b, r.Key+": "...)
295 b = alignKeyLens[i].appendChar(b, ' ')
297 b = r.Value.formatExpandedTo(b, d|r.Diff, n)
301 b = alignValueLens[i].appendChar(b, ' ')
303 if r.Comment != nil {
304 b = append(b, " // "+r.Comment.String()...)
309 return n.appendIndent(append(b, '\n'), d)
312 func (s textList) alignLens(
313 skipFunc func(textRecord) bool,
314 lenFunc func(textRecord) int,
316 var startIdx, endIdx, maxLen int
317 lens := make([]repeatCount, len(s))
318 for i, r := range s {
320 for j := startIdx; j < endIdx && j < len(s); j++ {
321 lens[j] = repeatCount(maxLen - lenFunc(s[j]))
323 startIdx, endIdx, maxLen = i+1, i+1, 0
325 if maxLen < lenFunc(r) {
331 for j := startIdx; j < endIdx && j < len(s); j++ {
332 lens[j] = repeatCount(maxLen - lenFunc(s[j]))
337 // textLine is a single-line segment of text and is always a leaf node
338 // in the textNode tree.
342 textNil = textLine("nil")
343 textEllipsis = textLine("...")
346 func (s textLine) Len() int {
349 func (s1 textLine) Equal(s2 textNode) bool {
350 if s2, ok := s2.(textLine); ok {
351 return bytes.Equal([]byte(s1), []byte(s2))
355 func (s textLine) String() string {
358 func (s textLine) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) {
359 return append(b, s...), s
361 func (s textLine) formatExpandedTo(b []byte, _ diffMode, _ indentMode) []byte {
362 return append(b, s...)
365 type diffStats struct {
374 func (s diffStats) IsZero() bool {
376 return s == diffStats{}
379 func (s diffStats) NumDiff() int {
380 return s.NumRemoved + s.NumInserted + s.NumModified
383 func (s diffStats) Append(ds diffStats) diffStats {
384 assert(s.Name == ds.Name)
385 s.NumIgnored += ds.NumIgnored
386 s.NumIdentical += ds.NumIdentical
387 s.NumRemoved += ds.NumRemoved
388 s.NumInserted += ds.NumInserted
389 s.NumModified += ds.NumModified
393 // String prints a humanly-readable summary of coalesced records.
396 // diffStats{Name: "Field", NumIgnored: 5}.String() => "5 ignored fields"
397 func (s diffStats) String() string {
400 labels := [...]string{"ignored", "identical", "removed", "inserted", "modified"}
401 counts := [...]int{s.NumIgnored, s.NumIdentical, s.NumRemoved, s.NumInserted, s.NumModified}
402 for i, n := range counts {
404 ss = append(ss, fmt.Sprintf("%d %v", n, labels[i]))
409 // Pluralize the name (adjusting for some obscure English grammar rules).
413 if strings.HasSuffix(name, "ys") {
414 name = name[:len(name)-2] + "ies" // e.g., "entrys" => "entries"
418 // Format the list according to English grammar (with Oxford comma).
419 switch n := len(ss); n {
423 return strings.Join(ss, " and ") + " " + name
425 return strings.Join(ss[:n-1], ", ") + ", and " + ss[n-1] + " " + name
429 type commentString string
431 func (s commentString) String() string { return string(s) }