Debian Codegraph @

build/error.go

raw symbols SCIP
1 package build
2
3 import (
4 "errors"
5 "fmt"
6 "log"
7
8 "github.com/mmcloughlin/avo/internal/stack"
9 "github.com/mmcloughlin/avo/src"
10 )
11
12 // Error represents an error during building, optionally tagged with the position at which it happened.
13 type Error struct {
14 Position src.Position
15 Err error
16 }
17
18 // exterr constructs an Error with position derived from the first frame in the
19 // call stack outside this package.
20 func exterr(err error) Error {
21 e := Error{Err: err}
22 if f := stack.ExternalCaller(); f != nil {
23 e.Position = src.FramePosition(*f).Relwd()
24 }
25 return e
26 }
27
28 func (e Error) Error() string {
29 msg := e.Err.Error()
30 if e.Position.IsValid() {
31 return e.Position.String() + ": " + msg
32 }
33 return msg
34 }
35
36 // ErrorList is a collection of errors for a source file.
37 type ErrorList []Error
38
39 // Add appends an error to the list.
40 func (e *ErrorList) Add(err Error) {
41 *e = append(*e, err)
42 }
43
44 // AddAt appends an error at position p.
45 func (e *ErrorList) AddAt(p src.Position, err error) {
46 e.Add(Error{p, err})
47 }
48
49 // addext appends an error to the list, tagged with the first external position
50 // outside this package.
51 func (e *ErrorList) addext(err error) {
52 e.Add(exterr(err))
53 }
54
55 // Err returns an error equivalent to this error list.
56 // If the list is empty, Err returns nil.
57 func (e ErrorList) Err() error {
58 if len(e) == 0 {
59 return nil
60 }
61 return e
62 }
63
64 // Error implements the error interface.
65 func (e ErrorList) Error() string {
66 switch len(e) {
67 case 0:
68 return "no errors"
69 case 1:
70 return e[0].Error()
71 }
72 return fmt.Sprintf("%s (and %d more errors)", e[0], len(e)-1)
73 }
74
75 // LogError logs a list of errors, one error per line, if the err parameter is
76 // an ErrorList. Otherwise it just logs the err string. Reports at most max
77 // errors, or unlimited if max is 0.
78 func LogError(l *log.Logger, err error, max int) {
79 var list ErrorList
80 if errors.As(err, &list) {
81 for i, e := range list {
82 if max > 0 && i == max {
83 l.Print("too many errors")
84 return
85 }
86 l.Printf("%s\n", e)
87 }
88 } else if err != nil {
89 l.Printf("%s\n", err)
90 }
91 }