forked from rhysd/actionlint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
248 lines (221 loc) · 6.76 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
package actionlint
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
"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 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 formating this error with Go template.
func (e *Error) GetTemplateFields(source []byte) *ErrorTemplateFields {
var snippet string
if len(source) > 0 && e.Line > 0 {
if l, ok := e.getLine(source); ok {
snippet = l
if i := e.getIndicator(l); i != "" {
snippet += "\n" + i
}
}
}
return &ErrorTemplateFields{
Message: e.Message,
Filepath: e.Filepath,
Line: e.Line,
Column: e.Column,
Kind: e.Kind,
Snippet: snippet,
}
}
// 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 type for sort.Interface. It sorts errors slice in line and column order.
type ByErrorPosition []*Error
func (by ByErrorPosition) Len() int {
return len(by)
}
func (by ByErrorPosition) Less(i, j int) bool {
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"`
}
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)
}
// 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
}
// 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)
}
funcs := 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)
},
}
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}, 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)
}