Debian Codegraph @

format.go

raw
1 // Licensed under the MIT license, see LICENSE file for details.
2
3 package qt
4
5 import (
6 "fmt"
7 "reflect"
8 "strconv"
9 "strings"
10 "unicode/utf8"
11
12 "github.com/kr/pretty"
13 )
14
15 // Format formats the given value as a string. It is used to print values in
16 // test failures.
17 func Format(v any) string {
18 switch v := v.(type) {
19 case error:
20 s, ok := checkStringCall(v, v.Error)
21 if !ok {
22 return "e<nil>"
23 }
24 if msg := fmt.Sprintf("%+v", v); msg != s {
25 // The error has formatted itself with additional information.
26 // Leave that as is.
27 return msg
28 }
29 return "e" + quoteString(s)
30 case fmt.Stringer:
31 s, ok := checkStringCall(v, v.String)
32 if !ok {
33 return "s<nil>"
34 }
35 return "s" + quoteString(s)
36 case string:
37 return quoteString(v)
38 case uintptr, uint, uint8, uint16, uint32, uint64:
39 // Use decimal base (rather than hexadecimal) for representing uint types.
40 return fmt.Sprintf("%T(%d)", v, v)
41 }
42 if bytes, ok := byteSlice(v); ok && bytes != nil && utf8.Valid(bytes) {
43 // It's a top level slice of bytes that's also valid UTF-8.
44 // Ideally, this would happen at deeper levels too,
45 // but this is sufficient for some significant cases
46 // (json.RawMessage for example).
47 return fmt.Sprintf("%T(%s)", v, quoteString(string(bytes)))
48 }
49 // The pretty.Sprint equivalent does not quote string values.
50 return fmt.Sprintf("%# v", pretty.Formatter(v))
51 }
52
53 func byteSlice(x any) ([]byte, bool) {
54 v := reflect.ValueOf(x)
55 if !v.IsValid() {
56 return nil, false
57 }
58 t := v.Type()
59 if t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 {
60 return v.Bytes(), true
61 }
62 return nil, false
63 }
64
65 func quoteString(s string) string {
66 // TODO think more about what to do about multi-line strings.
67 if strings.Contains(s, `"`) && !strings.Contains(s, "\n") && strconv.CanBackquote(s) {
68 return "`" + s + "`"
69 }
70 return strconv.Quote(s)
71 }
72
73 // checkStringCall calls f and returns its result, and reports if the call
74 // succeeded without panicking due to a nil pointer.
75 // If f panics and v is a nil pointer, it returns false.
76 func checkStringCall(v any, f func() string) (s string, ok bool) {
77 defer func() {
78 err := recover()
79 if err == nil {
80 return
81 }
82 if val := reflect.ValueOf(v); val.Kind() == reflect.Pointer && val.IsNil() {
83 ok = false
84 return
85 }
86 panic(err)
87 }()
88 return f(), true
89 }