-
Notifications
You must be signed in to change notification settings - Fork 163
/
error.go
331 lines (294 loc) · 8.92 KB
/
error.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
321
322
323
324
325
326
327
328
329
330
331
package actionlint
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"sort"
"strings"
"sync"
"text/template"
"github.com/fatih/color"
"github.com/mattn/go-runewidth"
)
var (
bold = color.New(color.Bold)
green = color.New(color.FgGreen)
yellow = color.New(color.FgYellow)
gray = color.New(color.FgHiBlack)
)
// Error represents an error detected by actionlint rules
type Error struct {
// Message is an error message.
Message string
// Filepath is a file path where the error occurred.
Filepath string
// Line is a line number where the error occurred. This value is 1-based.
Line int
// Column is a column number where the error occurred. This value is 1-based.
Column int
// Kind is a string to represent kind of the error. Usually rule name which found the error.
Kind string
}
// Error returns summary of the error as string.
func (e *Error) Error() string {
return fmt.Sprintf("%s:%d:%d: %s [%s]", e.Filepath, e.Line, e.Column, e.Message, e.Kind)
}
func (e *Error) String() string {
return e.Error()
}
func errorAt(pos *Pos, kind string, msg string) *Error {
return &Error{
Message: msg,
Line: pos.Line,
Column: pos.Col,
Kind: kind,
}
}
func errorfAt(pos *Pos, kind string, format string, args ...interface{}) *Error {
return &Error{
Message: fmt.Sprintf(format, args...),
Line: pos.Line,
Column: pos.Col,
Kind: kind,
}
}
// GetTemplateFields fields for formatting this error with Go template.
func (e *Error) GetTemplateFields(source []byte) *ErrorTemplateFields {
snippet := ""
end := e.Column
if len(source) > 0 && e.Line > 0 {
if l, ok := e.getLine(source); ok {
snippet = l
if len(l) >= e.Column-1 {
if i := e.getIndicator(l); i != "" {
snippet += "\n" + i
end = len(i) // Byte length can be used here because this line only contains ASCII
}
}
}
}
return &ErrorTemplateFields{
Message: e.Message,
Filepath: e.Filepath,
Line: e.Line,
Column: e.Column,
Kind: e.Kind,
Snippet: snippet,
EndColumn: end,
}
}
// PrettyPrint prints the error with user-friendly way. It prints file name, source position, error
// message with colorful output and source snippet with indicator. When nil is set to source, no
// source snippet is not printed. To disable colorful output, set true to fatih/color.NoColor.
func (e *Error) PrettyPrint(w io.Writer, source []byte) {
yellow.Fprint(w, e.Filepath)
gray.Fprint(w, ":")
fmt.Fprint(w, e.Line)
gray.Fprint(w, ":")
fmt.Fprint(w, e.Column)
gray.Fprint(w, ": ")
bold.Fprint(w, e.Message)
gray.Fprintf(w, " [%s]\n", e.Kind)
if len(source) == 0 || e.Line <= 0 {
return
}
line, ok := e.getLine(source)
if !ok || len(line) < e.Column-1 {
return
}
lnum := fmt.Sprintf("%d | ", e.Line)
indent := strings.Repeat(" ", len(lnum)-2)
gray.Fprintf(w, "%s|\n", indent)
gray.Fprint(w, lnum)
fmt.Fprintln(w, line)
gray.Fprintf(w, "%s| ", indent)
green.Fprintln(w, e.getIndicator(line))
}
func (e *Error) getLine(source []byte) (string, bool) {
s := bufio.NewScanner(bytes.NewReader(source))
l := 0
for s.Scan() {
l++
if l == e.Line {
return s.Text(), true
}
}
return "", false
}
func (e *Error) getIndicator(line string) string {
if e.Column <= 0 {
return ""
}
start := e.Column - 1 // Column is 1-based
// Count width of non-space characters after '^' for underline
uw := 0
r := strings.NewReader(line[start:])
for {
c, s, err := r.ReadRune()
if err != nil || s == 0 || c == ' ' || c == '\t' || c == '\n' || c == '\r' {
break
}
uw += runewidth.RuneWidth(c)
}
if uw > 0 {
uw-- // Decrement for place for '^'
}
// Count width of spaces before '^'
sw := runewidth.StringWidth(line[:start])
return fmt.Sprintf("%s^%s", strings.Repeat(" ", sw), strings.Repeat("~", uw))
}
// ByErrorPosition is predicate for sort.Interface. It sorts errors slice by file path, line, and
// column.
type ByErrorPosition []*Error
func (by ByErrorPosition) Len() int {
return len(by)
}
func (by ByErrorPosition) Less(i, j int) bool {
if c := strings.Compare(by[i].Filepath, by[j].Filepath); c != 0 {
return c < 0
}
if by[i].Line == by[j].Line {
return by[i].Column < by[j].Column
}
return by[i].Line < by[j].Line
}
func (by ByErrorPosition) Swap(i, j int) {
by[i], by[j] = by[j], by[i]
}
// ErrorTemplateFields holds all fields to format one error message.
type ErrorTemplateFields struct {
// Message is error message body.
Message string `json:"message"`
// Filepath is a canonical relative file path. This is empty when input was read from stdin.
// When encoding into JSON, this field may be omitted when the file path is empty.
Filepath string `json:"filepath,omitempty"`
// Line is a line number of error position.
Line int `json:"line"`
// Column is a column number of error position.
Column int `json:"column"`
// Kind is a rule name the error belongs to.
Kind string `json:"kind"`
// Snippet is a code snippet and indicator to indicate where the error occurred.
// When encoding into JSON, this field may be omitted when the snippet is empty.
Snippet string `json:"snippet,omitempty"`
// EndColumn is a column number where the error indicator (^~~~~~~) ends. When no indicator
// can be shown, EndColumn is equal to Column.
EndColumn int `json:"end_column"`
}
func unescapeBackslash(s string) string {
// https://golang.org/ref/spec#Rune_literals
r := strings.NewReplacer(
`\a`, "\a",
`\b`, "\b",
`\f`, "\f",
`\n`, "\n",
`\r`, "\r",
`\t`, "\t",
`\v`, "\v",
`\\`, "\\",
)
return r.Replace(s)
}
func toPascalCase(s string) string {
ss := strings.FieldsFunc(s, func(r rune) bool {
return !('a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' || '0' <= r && r <= '9')
})
for i, s := range ss {
var c rune
for _, c = range s {
break
}
if 'a' <= c && c <= 'z' {
ss[i] = strings.ToUpper(s[:1]) + s[1:]
}
}
return strings.Join(ss, "")
}
type ruleTemplateFields struct {
Name string
Description string
}
type byRuleNameField []*ruleTemplateFields
func (by byRuleNameField) Len() int {
return len(by)
}
func (by byRuleNameField) Less(i, j int) bool {
return strings.Compare(by[i].Name, by[j].Name) < 0
}
func (by byRuleNameField) Swap(i, j int) {
by[i], by[j] = by[j], by[i]
}
// ErrorFormatter is a formatter to format a slice of ErrorTemplateFields. It is used for
// formatting error messages with -format option.
type ErrorFormatter struct {
temp *template.Template
rules map[string]*ruleTemplateFields
rulesMu sync.Mutex
}
// NewErrorFormatter creates new ErrorFormatter instance. Given format must contain at least one
// {{ }} placeholder. Escaped characters like \n in the format string are unescaped.
func NewErrorFormatter(format string) (*ErrorFormatter, error) {
if !strings.Contains(format, "{{") {
return nil, fmt.Errorf("template to format error messages must contain at least one {{ }} placeholder: %s", format)
}
r := map[string]*ruleTemplateFields{
"syntax-check": {"syntax-check", "Checks for GitHub Actions workflow syntax"},
}
funcs := template.FuncMap(map[string]interface{}{
"json": func(data interface{}) (string, error) {
var b strings.Builder
enc := json.NewEncoder(&b)
if err := enc.Encode(data); err != nil {
return "", fmt.Errorf("could not encode template value into JSON: %w", err)
}
return b.String(), nil
},
"replace": func(s string, oldnew ...string) string {
return strings.NewReplacer(oldnew...).Replace(s)
},
"toPascalCase": toPascalCase,
"getVersion": getCommandVersion,
"allKinds": func() []*ruleTemplateFields {
ret := make([]*ruleTemplateFields, 0, len(r))
for _, e := range r {
ret = append(ret, e)
}
sort.Sort(byRuleNameField(ret))
return ret
},
})
t, err := template.New("error formatter").Funcs(funcs).Parse(unescapeBackslash(format))
if err != nil {
return nil, fmt.Errorf("template %q to format error messages could not be parsed: %w", format, err)
}
return &ErrorFormatter{t, r, sync.Mutex{}}, nil
}
// Print formats the slice of template fields and prints it with given writer.
func (f *ErrorFormatter) Print(out io.Writer, t []*ErrorTemplateFields) error {
if err := f.temp.Execute(out, t); err != nil {
return fmt.Errorf("could not format error messages: %w", err)
}
return nil
}
// PrintErrors prints the errors after formatting them with template.
func (f *ErrorFormatter) PrintErrors(out io.Writer, errs []*Error, src []byte) error {
t := make([]*ErrorTemplateFields, 0, len(errs))
for _, err := range errs {
t = append(t, err.GetTemplateFields(src))
}
return f.Print(out, t)
}
// RegisterRule registers the rule. Registered rules are used to get description and index of error
// kinds when you use `kindDescription` or `kindIndex` functions in an error format template. This
// method can be called multiple times safely in parallel.
func (f *ErrorFormatter) RegisterRule(r Rule) {
// Synchronize access to f.rules (#370)
f.rulesMu.Lock()
defer f.rulesMu.Unlock()
n := r.Name()
if _, ok := f.rules[n]; !ok {
f.rules[n] = &ruleTemplateFields{n, r.Description()}
}
}