Debian Codegraph @

stringers.go

raw symbols SCIP
1 package jl
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "strings"
8 )
9
10 // Stringer transforms a field returned by the FieldFinder into a string.
11 type Stringer func(ctx *Context, v interface{}) string
12
13 var _ = Stringer(DefaultStringer)
14 var _ = Stringer(ErrorStringer)
15
16 // DefaultStringer attempts to turn a field into string by attempting the following in order
17 // 1. casting it to a string
18 // 2. unmarshalling it as a json.RawMessage
19 // 3. using fmt.Sprintf("%v", input)
20 func DefaultStringer(ctx *Context, v interface{}) string {
21 var s string
22 if tmp, ok := v.(string); ok {
23 s = tmp
24 } else if rawMsg, ok := v.(json.RawMessage); ok {
25 var unmarshaled interface{}
26 if err := json.Unmarshal(rawMsg, &unmarshaled); err != nil {
27 s = string(rawMsg)
28 } else {
29 s = fmt.Sprintf("%v", unmarshaled)
30 }
31 } else {
32 s = fmt.Sprintf("%v", v)
33 }
34 return s
35 }
36
37 // ErrorStringer stringifies LogrusError to a multiline string. If the field is not a LogrusError, it falls back
38 // to the DefaultStringer.
39 func ErrorStringer(ctx *Context, v interface{}) string {
40 w := &bytes.Buffer{}
41 if logrusErr, ok := v.(LogrusError); ok {
42 w.WriteString("\n ")
43 w.WriteString(logrusErr.Error)
44 w.WriteRune('\n')
45 // left pad with a tab
46 lines := strings.Split(logrusErr.Stack, "\n")
47 stackStr := "\t" + strings.Join(lines, "\n\t")
48 w.WriteString(stackStr)
49 return w.String()
50 } else {
51 return DefaultStringer(ctx, v)
52 }
53 }