-
Notifications
You must be signed in to change notification settings - Fork 9
/
format.go
320 lines (268 loc) · 8.9 KB
/
format.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// Pretty-printing of various namespace errors.
// Needs to be in a separate package to access error types from elsewhere in the codebase
// without introducing import cycles (e.g. tasks -> fnerrors -> tasks).
package format
import (
"bufio"
"errors"
"fmt"
"io"
"strings"
cueerrors "cuelang.org/go/cue/errors"
"github.com/kr/text"
"namespacelabs.dev/foundation/internal/cli/fncobra/name"
"namespacelabs.dev/foundation/internal/console/colors"
"namespacelabs.dev/foundation/internal/console/consolesink"
"namespacelabs.dev/foundation/internal/fnerrors"
ghenv "namespacelabs.dev/foundation/internal/github/env"
"namespacelabs.dev/foundation/std/tasks"
)
type FormatOptions struct {
// true to use ANSI style.
style colors.Style
// If true, we show the chain of foundation errors
// leading to the root cause.
tracing bool
// If true, we show the chain of actions leading to the failed action.
actionTracing bool
}
type FormatOption func(*FormatOptions)
func WithStyle(style colors.Style) FormatOption {
return func(opts *FormatOptions) {
opts.style = style
}
}
func WithTracing(tracing bool) FormatOption {
return func(opts *FormatOptions) {
opts.tracing = tracing
}
}
func WithActionTrace(tracing bool) FormatOption {
return func(opts *FormatOptions) {
opts.actionTracing = tracing
}
}
func Format(w io.Writer, err error, args ...FormatOption) {
opts := &FormatOptions{style: colors.NoColors, tracing: false}
for _, opt := range args {
opt(opts)
}
fmt.Fprint(w, opts.style.ErrorHeader.Apply("Failed: "))
if opts.tracing {
fmt.Fprintln(w)
w = indent(w)
}
var actionError *fnerrors.ActionError
cause := err
curr := err
// Keep unwrapping to get the root fnError.
for {
// Keep looking for the innermost action error
errors.As(cause, &actionError)
curr = errors.Unwrap(curr)
if curr == nil {
break
}
if !fnerrors.IsNamespaceError(curr) {
// Also traverse through non-Namespace errors (e.g. fmt.wrapError) to find the root cause.
continue
}
if opts.tracing {
format(w, cause, opts)
writeSourceFileAndLine(w, cause, opts.style)
w = indent(w)
}
cause = curr
}
if opts.actionTracing && actionError != nil {
// Print the sequence of actions/tasks leading to the error.
if !opts.tracing {
fmt.Fprintln(w) // Break the line after Failed:
w = indent(w)
}
trace := actionError.Trace()
for i := len(trace) - 1; i >= 0; i-- {
consolesink.LogAction(w, opts.style, tasks.EventDataFromProto("", trace[i]))
w = indent(w)
}
}
format(w, cause, opts)
// XXX TODO write stacktrace out if requested.
// writeSourceFileAndLine(w, cause, opts.style)
}
func writeSourceFileAndLine(w io.Writer, err error, colors colors.Style) {
if st, ok := err.(fnerrors.StackTracer); ok {
stack := st.StackTrace()
if len(stack) == 0 {
return
}
frame := stack[0]
sourceInfo := fmt.Sprintf("%s:%d", frame.File(), frame.Line())
fmt.Fprintf(w, "%s\n", colors.Header.Apply(sourceInfo))
}
}
func format(w io.Writer, err error, opts *FormatOptions) {
if err == nil {
return
}
switch x := err.(type) {
case *fnerrors.UsageErr:
formatUsageError(w, x, opts)
case *fnerrors.BaseError:
formatUserError(w, x, opts)
case *fnerrors.InvocationErr:
formatInvocationError(w, &x.BaseError, opts)
case *fnerrors.ErrWithLogs:
formatErrWithLogs(w, x, opts)
case cueerrors.Error:
formatCueError(w, x, opts)
case *fnerrors.DependencyFailedError:
formatDependencyFailedError(w, x, opts)
case *fnerrors.CodegenError:
formatCodegenError(w, opts, x.Error(), x.What, x.PackageName)
case *fnerrors.CodegenMultiError:
formatCodegenMultiError(w, x, opts)
case *fnerrors.PermissionDeniedErr:
formatPermissionDeniedError(w, x, opts)
default:
fmt.Fprintf(w, "%s\n", x.Error())
}
}
func formatErrWithLogs(w io.Writer, err *fnerrors.ErrWithLogs, opts *FormatOptions) {
colors := opts.style
fmt.Fprintf(w, "%s\n", colors.LogCategory.Apply("Captured logs: "))
const limitLines = 10
lines := make([]string, 0, limitLines)
scanner := bufio.NewScanner(err.ReaderF())
truncated := false
for scanner.Scan() {
if len(lines) < limitLines {
lines = append(lines, scanner.Text())
} else {
truncated = true
lines = append(lines[1:], scanner.Text())
}
}
if truncated {
fmt.Fprintf(w, "%s%d%s\n", colors.LessRelevant.Apply("... (truncated to last "), limitLines, colors.LessRelevant.Apply(" lines) ..."))
}
for _, line := range lines {
fmt.Fprintf(w, "%s\n", line)
}
fmt.Fprintln(w)
}
func formatUsageError(w io.Writer, err *fnerrors.UsageErr, opts *FormatOptions) {
// XXX don't wordwrap if terminal is below 80 chars in width.
errTxt := text.Wrap(err.Why, 80)
fmt.Fprintf(w, "%s\n\n %s\n", errTxt, opts.style.Highlight.Apply(err.What))
}
func formatInvocationError(w io.Writer, err *fnerrors.BaseError, opts *FormatOptions) {
fmt.Fprintf(w, "%s: %s\n", opts.style.LogResult.Apply("invocation error"), err.OriginalErr.Error())
fmt.Fprintln(w)
fmt.Fprintf(w, "This was unexpected, but could be transient. Please try again.\nAnd if it persists, %s\n", askForSupport())
errorReportRequest(w)
}
func formatPermissionDeniedError(w io.Writer, err *fnerrors.PermissionDeniedErr, opts *FormatOptions) {
var cmd string
switch {
case ghenv.IsRunningInActions():
cmd = "auth exchange-github-token"
default:
cmd = "login"
}
suggestion := fmt.Sprintf("%s %s", name.CmdName, cmd)
fmt.Fprintf(w, "%s\n\nTry running `%s`.\nIf this does not help %s\n", err.Why, opts.style.Highlight.Apply(suggestion), askForSupport())
}
func formatCueError(w io.Writer, err cueerrors.Error, opts *FormatOptions) {
errclean := cueerrors.Sanitize(err)
for _, e := range cueerrors.Errors(errclean) {
positions := cueerrors.Positions(e)
if len(positions) == 0 {
fmt.Fprintln(w, e.Error())
} else {
for _, p := range positions {
pos := p.Position()
fmt.Fprintln(w, e.Error(), opts.style.Header.Apply(pos.String()))
}
}
}
}
func formatDependencyFailedError(w io.Writer, err *fnerrors.DependencyFailedError, opts *FormatOptions) {
depName := opts.style.LogResult.Apply(err.Name)
depType := opts.style.LogError.Apply(fmt.Sprintf("(%s)", err.Type))
if opts.tracing {
fmt.Fprintf(w, "failed to compute %s %s\n", depName, depType)
} else {
fmt.Fprintf(w, "failed to compute %s %s: %s\n", depName, depType, err.OriginalErr)
}
}
func formatUserError(w io.Writer, err *fnerrors.BaseError, opts *FormatOptions) {
switch err.Kind {
case fnerrors.Kind_INTERNAL, fnerrors.Kind_BADINPUT, fnerrors.Kind_BADDATA:
fmt.Fprintf(w, "%s: %s\n", opts.style.LogResult.Apply("internal error"), err.OriginalErr.Error())
fmt.Fprintln(w)
fmt.Fprintf(w, "This was unexpected, %s\n", askForSupport())
errorReportRequest(w)
case fnerrors.Kind_EXTERNAL:
fmt.Fprintf(w, "%s: %s\n", opts.style.LogResult.Apply("component error"), err.OriginalErr.Error())
fmt.Fprintln(w)
fmt.Fprintf(w, "This was unexpected, %s\n", askForSupport())
errorReportRequest(w)
case fnerrors.Kind_TRANSIENT:
formatInvocationError(w, err, opts)
default:
if err.Location != nil {
loc := opts.style.LogResult.Apply(err.Location.ErrorLocation())
fmt.Fprintf(w, "%s at %s\n", err.OriginalErr.Error(), loc)
} else {
fmt.Fprintf(w, "%s\n", err.OriginalErr.Error())
}
}
}
func formatCodegenError(w io.Writer, opts *FormatOptions, err, what string, pkgnames ...string) {
phase := opts.style.LessRelevant.Apply(what)
pkgnamesdisplay := opts.style.LogScope.Apply(strings.Join(pkgnames, ", "))
fmt.Fprintf(w, "%s during %s, for %s %s\n", err, phase, plural(len(pkgnames), "package", "packages"), pkgnamesdisplay)
}
func formatCodegenMultiError(w io.Writer, err *fnerrors.CodegenMultiError, opts *FormatOptions) {
// Print aggregated errors.
for commonErr, whatpkgs := range err.CommonErrs {
for what, pkgs := range whatpkgs {
var pkgnames []string
for p := range pkgs {
pkgnames = append(pkgnames, p)
}
formatCodegenError(w, opts, commonErr, what, pkgnames...)
}
}
for _, generr := range err.UniqGenErrs {
formatCodegenError(w, opts, generr.Error(), generr.What, generr.PackageName)
}
}
func plural(count int, singular, plural string) string {
if count == 1 {
return singular
}
return plural
}
func errorReportRequest(w io.Writer) {
fmt.Fprintln(w)
fmt.Fprintf(w, "Please include,\n")
fmt.Fprintf(w, "- the full command line you've used.\n")
fmt.Fprintf(w, "- the full output that %s produced\n", name.CmdName)
if name.CmdName == "ns" {
fmt.Fprintf(w, "- the output of `ns doctor`\n")
}
}
func askForSupport() string {
switch name.CmdName {
case "ns", "nsdev":
return "please run `ns doctor` and file a bug at https://github.com/namespacelabs/foundation/issues"
default:
return "please reach out to support@namespacelabs.com"
}
}
func indent(w io.Writer) io.Writer { return text.NewIndentWriter(w, []byte(" ")) }