/
diagnostics.go
81 lines (64 loc) · 1.85 KB
/
diagnostics.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
package diag
import (
"context"
"github.com/hashicorp/terraform-plugin-go/internal/logging"
"github.com/hashicorp/terraform-plugin-go/tfprotov5"
)
// Diagnostics is a collection of Diagnostic.
type Diagnostics []*tfprotov5.Diagnostic
// ErrorCount returns the number of error severity diagnostics.
func (d Diagnostics) ErrorCount() int {
var result int
for _, diagnostic := range d {
if diagnostic == nil {
continue
}
if diagnostic.Severity != tfprotov5.DiagnosticSeverityError {
continue
}
result++
}
return result
}
// Log will log every diagnostic:
//
// - Error severity at ERROR level
// - Warning severity at WARN level
// - Invalid/Unknown severity at WARN level
func (d Diagnostics) Log(ctx context.Context) {
for _, diagnostic := range d {
if diagnostic == nil {
continue
}
diagnosticFields := map[string]interface{}{
logging.KeyDiagnosticDetail: diagnostic.Detail,
logging.KeyDiagnosticSeverity: diagnostic.Severity.String(),
logging.KeyDiagnosticSummary: diagnostic.Summary,
}
if diagnostic.Attribute != nil {
diagnosticFields[logging.KeyDiagnosticAttribute] = diagnostic.Attribute.String()
}
switch diagnostic.Severity {
case tfprotov5.DiagnosticSeverityError:
logging.ProtocolError(ctx, "Response contains error diagnostic", diagnosticFields)
case tfprotov5.DiagnosticSeverityWarning:
logging.ProtocolWarn(ctx, "Response contains warning diagnostic", diagnosticFields)
default:
logging.ProtocolWarn(ctx, "Response contains unknown diagnostic", diagnosticFields)
}
}
}
// WarningCount returns the number of warning severity diagnostics.
func (d Diagnostics) WarningCount() int {
var result int
for _, diagnostic := range d {
if diagnostic == nil {
continue
}
if diagnostic.Severity != tfprotov5.DiagnosticSeverityWarning {
continue
}
result++
}
return result
}