Debian Codegraph @

gopls/internal/test/compare/text.go

raw symbols SCIP
1 // Copyright 2022 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
5 package compare
6
7 import (
8 "bytes"
9
10 "golang.org/x/tools/internal/diff"
11 )
12
13 // Text returns a formatted unified diff of the edits to go from want to
14 // got, returning "" if and only if want == got.
15 //
16 // This function is intended for use in testing, and panics if any error occurs
17 // while computing the diff. It is not sufficiently tested for production use.
18 func Text(want, got string) string {
19 return NamedText("want", "got", want, got)
20 }
21
22 // NamedText is like text, but allows passing custom names of the 'want' and
23 // 'got' content.
24 func NamedText(wantName, gotName, want, got string) string {
25 if want == got {
26 return ""
27 }
28
29 // Add newlines to avoid verbose newline messages ("No newline at end of file").
30 unified := diff.Unified(wantName, gotName, want+"\n", got+"\n")
31
32 // Defensively assert that we get an actual diff, so that we guarantee the
33 // invariant that we return "" if and only if want == got.
34 //
35 // This is probably unnecessary, but convenient.
36 if unified == "" {
37 panic("empty diff for non-identical input")
38 }
39
40 return unified
41 }
42
43 // Bytes is like Text but using byte slices.
44 func Bytes(want, got []byte) string {
45 if bytes.Equal(want, got) {
46 return "" // common case
47 }
48 return Text(string(want), string(got))
49 }