Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/river/diag/diag.go
4096 views
1
// Package diag exposes error types used throughout River and a method to
2
// pretty-print them to the screen.
3
package diag
4
5
import (
6
"fmt"
7
8
"github.com/grafana/agent/pkg/river/token"
9
)
10
11
// Severity denotes the severity level of a diagnostic. The zero value of
12
// severity is invalid.
13
type Severity int
14
15
// Supported severity levels.
16
const (
17
SeverityLevelWarn Severity = iota + 1
18
SeverityLevelError
19
)
20
21
// Diagnostic is an individual diagnostic message. Diagnostic messages can have
22
// different levels of severities.
23
type Diagnostic struct {
24
// Severity holds the severity level of this Diagnostic.
25
Severity Severity
26
27
// StartPos refers to a position in a file where this Diagnostic starts.
28
StartPos token.Position
29
30
// EndPos refers to an optional position in a file where this Diagnostic
31
// ends. If EndPos is the zero value, the Diagnostic should be treated as
32
// only covering a single character (i.e., StartPos == EndPos).
33
//
34
// When defined, EndPos must have the same Filename value as the StartPos.
35
EndPos token.Position
36
37
Message string
38
Value string
39
}
40
41
// As allows d to be interpreted as a list of Diagnostics.
42
func (d Diagnostic) As(v interface{}) bool {
43
switch v := v.(type) {
44
case *Diagnostics:
45
*v = Diagnostics{d}
46
return true
47
}
48
49
return false
50
}
51
52
// Error implements error.
53
func (d Diagnostic) Error() string {
54
return fmt.Sprintf("%s: %s", d.StartPos, d.Message)
55
}
56
57
// Diagnostics is a collection of diagnostic messages.
58
type Diagnostics []Diagnostic
59
60
// Add adds an individual Diagnostic to the diagnostics list.
61
func (ds *Diagnostics) Add(d Diagnostic) {
62
*ds = append(*ds, d)
63
}
64
65
// Error implements error.
66
func (ds Diagnostics) Error() string {
67
switch len(ds) {
68
case 0:
69
return "no errors"
70
case 1:
71
return ds[0].Error()
72
default:
73
return fmt.Sprintf("%s (and %d more diagnostics)", ds[0], len(ds)-1)
74
}
75
}
76
77
// ErrorOrNil returns an error interface if the list diagnostics is non-empty,
78
// nil otherwise.
79
func (ds Diagnostics) ErrorOrNil() error {
80
if len(ds) == 0 {
81
return nil
82
}
83
return ds
84
}
85
86
// HasErrors reports whether the list of Diagnostics contain any error-level
87
// diagnostic.
88
func (ds Diagnostics) HasErrors() bool {
89
for _, d := range ds {
90
if d.Severity == SeverityLevelError {
91
return true
92
}
93
}
94
return false
95
}
96
97