Debian Codegraph @

errors/fmt/errors.go

raw symbols SCIP
1 // Copyright 2018 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 fmt
6
7 import (
8 "bytes"
9 "strings"
10
11 "golang.org/x/exp/errors"
12 "golang.org/x/exp/errors/internal"
13 )
14
15 // Errorf formats according to a format specifier and returns the string as a
16 // value that satisfies error.
17 //
18 // The returned error includes the file and line number of the caller when
19 // formatted with additional detail enabled. If the last argument is an error
20 // the returned error's Format method will return it if the format string ends
21 // with ": %s", ": %v", or ": %w". If the last argument is an error and the
22 // format string ends with ": %w", the returned error implements errors.Wrapper
23 // with an Unwrap method returning it.
24 func Errorf(format string, a ...interface{}) error {
25 err, wrap := lastError(format, a)
26 if err == nil {
27 return &noWrapError{Sprintf(format, a...), nil, errors.Caller(1)}
28 }
29
30 // TODO: this is not entirely correct. The error value could be
31 // printed elsewhere in format if it mixes numbered with unnumbered
32 // substitutions. With relatively small changes to doPrintf we can
33 // have it optionally ignore extra arguments and pass the argument
34 // list in its entirety.
35 msg := Sprintf(format[:len(format)-len(": %s")], a[:len(a)-1]...)
36 frame := errors.Frame{}
37 if internal.EnableTrace {
38 frame = errors.Caller(1)
39 }
40 if wrap {
41 return &wrapError{msg, err, frame}
42 }
43 return &noWrapError{msg, err, frame}
44 }
45
46 func lastError(format string, a []interface{}) (err error, wrap bool) {
47 wrap = strings.HasSuffix(format, ": %w")
48 if !wrap &&
49 !strings.HasSuffix(format, ": %s") &&
50 !strings.HasSuffix(format, ": %v") {
51 return nil, false
52 }
53
54 if len(a) == 0 {
55 return nil, false
56 }
57
58 err, ok := a[len(a)-1].(error)
59 if !ok {
60 return nil, false
61 }
62
63 return err, wrap
64 }
65
66 type noWrapError struct {
67 msg string
68 err error
69 frame errors.Frame
70 }
71
72 func (e *noWrapError) Error() string {
73 return Sprint(e)
74 }
75
76 func (e *noWrapError) FormatError(p errors.Printer) (next error) {
77 p.Print(e.msg)
78 e.frame.Format(p)
79 return e.err
80 }
81
82 type wrapError struct {
83 msg string
84 err error
85 frame errors.Frame
86 }
87
88 func (e *wrapError) Error() string {
89 return Sprint(e)
90 }
91
92 func (e *wrapError) FormatError(p errors.Printer) (next error) {
93 p.Print(e.msg)
94 e.frame.Format(p)
95 return e.err
96 }
97
98 func (e *wrapError) Unwrap() error {
99 return e.err
100 }
101
102 func fmtError(p *pp, verb rune, err error) (handled bool) {
103 var (
104 sep = " " // separator before next error
105 w = p // print buffer where error text is written
106 )
107 switch {
108 // Note that this switch must match the preference order
109 // for ordinary string printing (%#v before %+v, and so on).
110
111 case p.fmt.sharpV:
112 if stringer, ok := p.arg.(GoStringer); ok {
113 // Print the result of GoString unadorned.
114 p.fmt.fmtS(stringer.GoString())
115 return true
116 }
117 return false
118
119 case p.fmt.plusV:
120 sep = "\n - "
121 w.fmt.fmtFlags = fmtFlags{plusV: p.fmt.plusV} // only keep detail flag
122
123 // The width or precision of a detailed view could be the number of
124 // errors to print from a list.
125
126 default:
127 // Use an intermediate buffer in the rare cases that precision,
128 // truncation, or one of the alternative verbs (q, x, and X) are
129 // specified.
130 switch verb {
131 case 's', 'v':
132 if (!w.fmt.widPresent || w.fmt.wid == 0) && !w.fmt.precPresent {
133 break
134 }
135 fallthrough
136 case 'q', 'x', 'X':
137 w = newPrinter()
138 defer w.free()
139 default:
140 w.badVerb(verb)
141 return true
142 }
143 }
144
145 loop:
146 for {
147 w.fmt.inDetail = false
148 switch v := err.(type) {
149 case errors.Formatter:
150 err = v.FormatError((*errPP)(w))
151 case Formatter:
152 if w.fmt.plusV {
153 v.Format((*errPPState)(w), 'v') // indent new lines
154 } else {
155 v.Format(w, 'v') // do not indent new lines
156 }
157 break loop
158 default:
159 w.fmtString(v.Error(), 's')
160 break loop
161 }
162 if err == nil {
163 break
164 }
165 if !w.fmt.inDetail || !p.fmt.plusV {
166 w.buf.WriteByte(':')
167 }
168 // Strip last newline of detail.
169 if bytes.HasSuffix([]byte(w.buf), detailSep) {
170 w.buf = w.buf[:len(w.buf)-len(detailSep)]
171 }
172 w.buf.WriteString(sep)
173 w.fmt.inDetail = false
174 }
175
176 if w != p {
177 p.fmtString(string(w.buf), verb)
178 }
179 return true
180 }
181
182 var detailSep = []byte("\n ")
183
184 // errPPState wraps a pp to implement State with indentation. It is used
185 // for errors implementing fmt.Formatter.
186 type errPPState pp
187
188 func (p *errPPState) Width() (wid int, ok bool) { return (*pp)(p).Width() }
189 func (p *errPPState) Precision() (prec int, ok bool) { return (*pp)(p).Precision() }
190 func (p *errPPState) Flag(c int) bool { return (*pp)(p).Flag(c) }
191
192 func (p *errPPState) Write(b []byte) (n int, err error) {
193 if !p.fmt.inDetail || p.fmt.plusV {
194 if len(b) == 0 {
195 return 0, nil
196 }
197 if p.fmt.inDetail && p.fmt.needNewline {
198 p.fmt.needNewline = false
199 p.buf.WriteByte(':')
200 p.buf.Write(detailSep)
201 if b[0] == '\n' {
202 b = b[1:]
203 }
204 }
205 k := 0
206 for i, c := range b {
207 if c == '\n' {
208 p.buf.Write(b[k:i])
209 p.buf.Write(detailSep)
210 k = i + 1
211 }
212 }
213 p.buf.Write(b[k:])
214 p.fmt.needNewline = !p.fmt.inDetail
215 }
216 return len(b), nil
217 }
218
219 // errPP wraps a pp to implement an errors.Printer.
220 type errPP pp
221
222 func (p *errPP) Print(args ...interface{}) {
223 if !p.fmt.inDetail || p.fmt.plusV {
224 if p.fmt.plusV {
225 Fprint((*errPPState)(p), args...)
226 } else {
227 (*pp)(p).doPrint(args)
228 }
229 }
230 }
231
232 func (p *errPP) Printf(format string, args ...interface{}) {
233 if !p.fmt.inDetail || p.fmt.plusV {
234 if p.fmt.plusV {
235 Fprintf((*errPPState)(p), format, args...)
236 } else {
237 (*pp)(p).doPrintf(format, args)
238 }
239 }
240 }
241
242 func (p *errPP) Detail() bool {
243 p.fmt.inDetail = true
244 return p.fmt.plusV
245 }