|
| 1 | +package diag |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + "github.com/hashicorp/terraform-plugin-go/internal/logging" |
| 7 | + "github.com/hashicorp/terraform-plugin-go/tfprotov5" |
| 8 | +) |
| 9 | + |
| 10 | +// Diagnostics is a collection of Diagnostic. |
| 11 | +type Diagnostics []*tfprotov5.Diagnostic |
| 12 | + |
| 13 | +// ErrorCount returns the number of error severity diagnostics. |
| 14 | +func (d Diagnostics) ErrorCount() int { |
| 15 | + var result int |
| 16 | + |
| 17 | + for _, diagnostic := range d { |
| 18 | + if diagnostic == nil { |
| 19 | + continue |
| 20 | + } |
| 21 | + |
| 22 | + if diagnostic.Severity != tfprotov5.DiagnosticSeverityError { |
| 23 | + continue |
| 24 | + } |
| 25 | + |
| 26 | + result++ |
| 27 | + } |
| 28 | + |
| 29 | + return result |
| 30 | +} |
| 31 | + |
| 32 | +// Log will log every diagnostic: |
| 33 | +// |
| 34 | +// - Error severity at ERROR level |
| 35 | +// - Warning severity at WARN level |
| 36 | +// - Invalid/Unknown severity at WARN level |
| 37 | +// |
| 38 | +func (d Diagnostics) Log(ctx context.Context) { |
| 39 | + for _, diagnostic := range d { |
| 40 | + if diagnostic == nil { |
| 41 | + continue |
| 42 | + } |
| 43 | + |
| 44 | + diagnosticFields := map[string]interface{}{ |
| 45 | + logging.KeyDiagnosticDetail: diagnostic.Detail, |
| 46 | + logging.KeyDiagnosticSeverity: diagnostic.Severity.String(), |
| 47 | + logging.KeyDiagnosticSummary: diagnostic.Summary, |
| 48 | + } |
| 49 | + |
| 50 | + if diagnostic.Attribute != nil { |
| 51 | + diagnosticFields[logging.KeyDiagnosticAttribute] = diagnostic.Attribute.String() |
| 52 | + } |
| 53 | + |
| 54 | + switch diagnostic.Severity { |
| 55 | + case tfprotov5.DiagnosticSeverityError: |
| 56 | + logging.ProtocolError(ctx, "Response contains error diagnostic", diagnosticFields) |
| 57 | + case tfprotov5.DiagnosticSeverityWarning: |
| 58 | + logging.ProtocolWarn(ctx, "Response contains warning diagnostic", diagnosticFields) |
| 59 | + default: |
| 60 | + logging.ProtocolWarn(ctx, "Response contains unknown diagnostic", diagnosticFields) |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +// WarningCount returns the number of warning severity diagnostics. |
| 66 | +func (d Diagnostics) WarningCount() int { |
| 67 | + var result int |
| 68 | + |
| 69 | + for _, diagnostic := range d { |
| 70 | + if diagnostic == nil { |
| 71 | + continue |
| 72 | + } |
| 73 | + |
| 74 | + if diagnostic.Severity != tfprotov5.DiagnosticSeverityWarning { |
| 75 | + continue |
| 76 | + } |
| 77 | + |
| 78 | + result++ |
| 79 | + } |
| 80 | + |
| 81 | + return result |
| 82 | +} |
0 commit comments