Debian Codegraph @

common/herrors/file_error.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable lfmtaw or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package herrors
15
16 import (
17 "encoding/json"
18 "errors"
19 "fmt"
20 "io"
21 "path/filepath"
22
23 "github.com/bep/godartsass/v2"
24 "github.com/bep/golibsass/libsass/libsasserrors"
25 "github.com/gohugoio/hugo/common/paths"
26 "github.com/gohugoio/hugo/common/text"
27 "github.com/pelletier/go-toml/v2"
28 "github.com/spf13/afero"
29 "github.com/tdewolff/parse/v2"
30 )
31
32 // FileError represents an error when handling a file: Parsing a config file,
33 // execute a template etc.
34 type FileError interface {
35 error
36
37 // ErrorContext holds some context information about the error.
38 ErrorContext() *ErrorContext
39
40 text.Positioner
41
42 // UpdatePosition updates the position of the error.
43 UpdatePosition(pos text.Position) FileError
44
45 // UpdateContent updates the error with a new ErrorContext from the content of the file.
46 UpdateContent(r io.Reader, linematcher LineMatcherFn) FileError
47
48 // SetFilename sets the filename of the error.
49 SetFilename(filename string) FileError
50 }
51
52 // Unwrapper can unwrap errors created with fmt.Errorf.
53 type Unwrapper interface {
54 Unwrap() error
55 }
56
57 var (
58 _ FileError = (*fileError)(nil)
59 _ Unwrapper = (*fileError)(nil)
60 )
61
62 func (fe *fileError) SetFilename(filename string) FileError {
63 fe.position.Filename = filename
64 return fe
65 }
66
67 func (fe *fileError) UpdatePosition(pos text.Position) FileError {
68 oldFilename := fe.Position().Filename
69 if pos.Filename != "" && fe.fileType == "" {
70 _, fe.fileType = paths.FileAndExtNoDelimiter(filepath.Clean(pos.Filename))
71 }
72 if pos.Filename == "" {
73 pos.Filename = oldFilename
74 }
75 fe.position = pos
76 return fe
77 }
78
79 func (fe *fileError) UpdateContent(r io.Reader, linematcher LineMatcherFn) FileError {
80 if linematcher == nil {
81 linematcher = SimpleLineMatcher
82 }
83
84 var (
85 posle = fe.position
86 ectx *ErrorContext
87 )
88
89 if posle.LineNumber <= 1 && posle.Offset > 0 {
90 // Try to locate the line number from the content if offset is set.
91 ectx = locateError(r, fe, func(m LineMatcher) int {
92 if posle.Offset >= m.Offset && posle.Offset < m.Offset+len(m.Line) {
93 lno := posle.LineNumber - m.Position.LineNumber + m.LineNumber
94 m.Position = text.Position{LineNumber: lno}
95 return linematcher(m)
96 }
97 return -1
98 })
99 } else {
100 ectx = locateError(r, fe, linematcher)
101 }
102
103 if ectx.ChromaLexer == "" {
104 if fe.fileType != "" {
105 ectx.ChromaLexer = chromaLexerFromType(fe.fileType)
106 } else {
107 ectx.ChromaLexer = chromaLexerFromFilename(fe.Position().Filename)
108 }
109 }
110
111 fe.errorContext = ectx
112
113 if ectx.Position.LineNumber > 0 && ectx.Position.LineNumber > fe.position.LineNumber {
114 fe.position.LineNumber = ectx.Position.LineNumber
115 }
116
117 if ectx.Position.ColumnNumber > 0 && ectx.Position.ColumnNumber > fe.position.ColumnNumber {
118 fe.position.ColumnNumber = ectx.Position.ColumnNumber
119 }
120
121 return fe
122 }
123
124 type fileError struct {
125 position text.Position
126 errorContext *ErrorContext
127
128 fileType string
129
130 cause error
131 }
132
133 func (e *fileError) ErrorContext() *ErrorContext {
134 return e.errorContext
135 }
136
137 // Position returns the text position of this error.
138 func (e fileError) Position() text.Position {
139 return e.position
140 }
141
142 func (e *fileError) Error() string {
143 return fmt.Sprintf("%s: %s", e.position, e.causeString())
144 }
145
146 func (e *fileError) causeString() string {
147 if e.cause == nil {
148 return ""
149 }
150 switch v := e.cause.(type) {
151 // Avoid repeating the file info in the error message.
152 case godartsass.SassError:
153 return v.Message
154 case libsasserrors.Error:
155 return v.Message
156 default:
157 return v.Error()
158 }
159 }
160
161 func (e *fileError) Unwrap() error {
162 return e.cause
163 }
164
165 // NewFileError creates a new FileError that wraps err.
166 // It will try to extract the filename and line number from err.
167 func NewFileError(err error) FileError {
168 // Filetype is used to determine the Chroma lexer to use.
169 fileType, pos := extractFileTypePos(err)
170 return &fileError{cause: err, fileType: fileType, position: pos}
171 }
172
173 // NewFileErrorFromName creates a new FileError that wraps err.
174 // The value for name should identify the file, the best
175 // being the full filename to the file on disk.
176 func NewFileErrorFromName(err error, name string) FileError {
177 // Filetype is used to determine the Chroma lexer to use.
178 fileType, pos := extractFileTypePos(err)
179 pos.Filename = name
180
181 if fileType == "" {
182 _, fileType = paths.FileAndExtNoDelimiter(filepath.Clean(name))
183 }
184
185 return &fileError{cause: err, fileType: fileType, position: pos}
186 }
187
188 // NewFileErrorFromPos will use the filename and line number from pos to create a new FileError, wrapping err.
189 func NewFileErrorFromPos(err error, pos text.Position) FileError {
190 // Filetype is used to determine the Chroma lexer to use.
191 fileType, _ := extractFileTypePos(err)
192 if fileType == "" {
193 _, fileType = paths.FileAndExtNoDelimiter(filepath.Clean(pos.Filename))
194 }
195 return &fileError{cause: err, fileType: fileType, position: pos}
196 }
197
198 func NewFileErrorFromFileInErr(err error, fs afero.Fs, linematcher LineMatcherFn) FileError {
199 fe := NewFileError(err)
200 pos := fe.Position()
201 if pos.Filename == "" {
202 return fe
203 }
204
205 f, realFilename, err2 := openFile(pos.Filename, fs)
206 if err2 != nil {
207 return fe
208 }
209
210 pos.Filename = realFilename
211 defer f.Close()
212 return fe.UpdateContent(f, linematcher)
213 }
214
215 func NewFileErrorFromFileInPos(err error, pos text.Position, fs afero.Fs, linematcher LineMatcherFn) FileError {
216 if err == nil {
217 panic("err is nil")
218 }
219 f, realFilename, err2 := openFile(pos.Filename, fs)
220 if err2 != nil {
221 return NewFileErrorFromPos(err, pos)
222 }
223 pos.Filename = realFilename
224 defer f.Close()
225 return NewFileErrorFromPos(err, pos).UpdateContent(f, linematcher)
226 }
227
228 // NewFileErrorFromFile is a convenience method to create a new FileError from a file.
229 func NewFileErrorFromFile(err error, filename string, fs afero.Fs, linematcher LineMatcherFn) FileError {
230 if err == nil {
231 panic("err is nil")
232 }
233 f, realFilename, err2 := openFile(filename, fs)
234 if err2 != nil {
235 return NewFileErrorFromName(err, realFilename)
236 }
237 defer f.Close()
238 fe := NewFileErrorFromName(err, realFilename)
239 fe = fe.UpdateContent(f, linematcher)
240 return fe
241 }
242
243 func openFile(filename string, fs afero.Fs) (afero.File, string, error) {
244 realFilename := filename
245
246 // We want the most specific filename possible in the error message.
247 fi, err2 := fs.Stat(filename)
248 if err2 == nil {
249 if s, ok := fi.(interface {
250 Filename() string
251 }); ok {
252 realFilename = s.Filename()
253 }
254 }
255
256 f, err2 := fs.Open(filename)
257 if err2 != nil {
258 return nil, realFilename, err2
259 }
260
261 return f, realFilename, nil
262 }
263
264 // Cause returns the underlying error, that is,
265 // it unwraps errors until it finds one that does not implement
266 // the Unwrap method.
267 // For a shallow variant, see Unwrap.
268 func Cause(err error) error {
269 type unwrapper interface {
270 Unwrap() error
271 }
272
273 for err != nil {
274 cause, ok := err.(unwrapper)
275 if !ok {
276 break
277 }
278 err = cause.Unwrap()
279 }
280 return err
281 }
282
283 // Unwrap returns the underlying error or itself if it does not implement Unwrap.
284 func Unwrap(err error) error {
285 if u := errors.Unwrap(err); u != nil {
286 return u
287 }
288 return err
289 }
290
291 // UnwrapFileErrors returns all FileError contained in err.
292 func UnwrapFileErrors(err error) []FileError {
293 if err == nil {
294 return nil
295 }
296 errs := Errors(err)
297 var fileErrors []FileError
298 for _, e := range errs {
299 if v, ok := e.(FileError); ok {
300 fileErrors = append(fileErrors, v)
301 }
302 fileErrors = append(fileErrors, UnwrapFileErrors(errors.Unwrap(e))...)
303 }
304 return fileErrors
305 }
306
307 // UnwrapFileErrorsWithErrorContext tries to unwrap all FileError in err that has an ErrorContext.
308 func UnwrapFileErrorsWithErrorContext(err error) []FileError {
309 errs := UnwrapFileErrors(err)
310 var n int
311 for _, e := range errs {
312 if e.ErrorContext() != nil {
313 errs[n] = e
314 n++
315 }
316 }
317 return errs[:n]
318 }
319
320 // Errors returns the list of errors contained in err.
321 func Errors(err error) []error {
322 if err == nil {
323 return nil
324 }
325
326 type unwrapper interface {
327 Unwrap() []error
328 }
329 if u, ok := err.(unwrapper); ok {
330 return u.Unwrap()
331 }
332 return []error{err}
333 }
334
335 func extractFileTypePos(err error) (string, text.Position) {
336 err = Unwrap(err)
337
338 var fileType string
339
340 // LibSass, DartSass
341 if pos := extractPosition(err); pos.LineNumber > 0 || pos.Offset > 0 {
342 _, fileType = paths.FileAndExtNoDelimiter(pos.Filename)
343 return fileType, pos
344 }
345
346 // Default to line 1 col 1 if we don't find any better.
347 pos := text.Position{
348 Offset: -1,
349 LineNumber: 1,
350 ColumnNumber: 1,
351 }
352
353 // JSON errors.
354 offset, typ := extractOffsetAndType(err)
355 if fileType == "" {
356 fileType = typ
357 }
358
359 if offset >= 0 {
360 pos.Offset = offset
361 }
362
363 // The error type from the minifier contains line number and column number.
364 if line, col := extractLineNumberAndColumnNumber(err); line >= 0 {
365 pos.LineNumber = line
366 pos.ColumnNumber = col
367 return fileType, pos
368 }
369
370 // Look in the error message for the line number.
371 if lno, col := commonLineNumberExtractor(err); lno > 0 {
372 pos.ColumnNumber = col
373 pos.LineNumber = lno
374 }
375
376 if fileType == "" && pos.Filename != "" {
377 _, fileType = paths.FileAndExtNoDelimiter(pos.Filename)
378 }
379
380 return fileType, pos
381 }
382
383 // UnwrapFileError tries to unwrap a FileError from err.
384 // It returns nil if this is not possible.
385 func UnwrapFileError(err error) FileError {
386 for err != nil {
387 switch v := err.(type) {
388 case FileError:
389 return v
390 default:
391 err = errors.Unwrap(err)
392 }
393 }
394 return nil
395 }
396
397 func extractOffsetAndType(e error) (int, string) {
398 switch v := e.(type) {
399 case *json.UnmarshalTypeError:
400 return int(v.Offset), "json"
401 case *json.SyntaxError:
402 return int(v.Offset), "json"
403 default:
404 return -1, ""
405 }
406 }
407
408 func extractLineNumberAndColumnNumber(e error) (int, int) {
409 switch v := e.(type) {
410 case *parse.Error:
411 return v.Line, v.Column
412 case *toml.DecodeError:
413 return v.Position()
414
415 }
416
417 return -1, -1
418 }
419
420 func extractPosition(e error) (pos text.Position) {
421 switch v := e.(type) {
422 case godartsass.SassError:
423 span := v.Span
424 start := span.Start
425 filename, _ := paths.UrlStringToFilename(span.Url)
426 pos.Filename = filename
427 pos.Offset = start.Offset
428 pos.ColumnNumber = start.Column
429 case libsasserrors.Error:
430 pos.Filename = v.File
431 pos.LineNumber = v.Line
432 pos.ColumnNumber = v.Column
433 }
434 return
435 }
436
437 // TextSegmentError is an error with a text segment attached.
438 type TextSegmentError struct {
439 Segment string
440 Err error
441 }
442
443 func (e TextSegmentError) Unwrap() error {
444 return e.Err
445 }
446
447 func (e TextSegmentError) Error() string {
448 return e.Err.Error()
449 }