Skip to content

Commit 30c41e8

Browse files
authored
Add DiagsToWarnings function. Closes #474
1 parent 06e780a commit 30c41e8

File tree

2 files changed

+58
-46
lines changed

2 files changed

+58
-46
lines changed

plugin/diags.go

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package plugin
2+
3+
import (
4+
"fmt"
5+
"strings"
6+
7+
"github.com/hashicorp/hcl/v2"
8+
)
9+
10+
// DiagsToError converts tfdiags diags into an error
11+
func DiagsToError(prefix string, diags hcl.Diagnostics) error {
12+
if !diags.HasErrors() {
13+
return nil
14+
}
15+
errStrings := diagsToString(diags, hcl.DiagError)
16+
17+
var res string
18+
if len(errStrings) > 0 {
19+
res = strings.Join(errStrings, "\n")
20+
if len(errStrings) > 1 {
21+
res += "\n"
22+
}
23+
return fmt.Errorf("%s\n%s", prefix, res)
24+
}
25+
26+
return diags.Errs()[0]
27+
}
28+
29+
// DiagsToWarning converts warning diags into a list of warning strings
30+
func DiagsToWarnings(diags hcl.Diagnostics) []string {
31+
return diagsToString(diags, hcl.DiagWarning)
32+
}
33+
34+
func diagsToString(diags hcl.Diagnostics, severity hcl.DiagnosticSeverity) []string { // convert the first diag into an error
35+
// store list of messages (without the range) and use for deduping (we may get the same message for multiple ranges)
36+
var msgMap = make(map[string]struct{})
37+
var strs []string
38+
for _, diag := range diags {
39+
if diag.Severity == severity {
40+
str := fmt.Sprintf("%s", diag.Summary)
41+
if diag.Detail != "" {
42+
str += fmt.Sprintf(": %s", diag.Detail)
43+
}
44+
45+
if _, ok := msgMap[str]; !ok {
46+
msgMap[str] = struct{}{}
47+
// now add in the subject and add to the output array
48+
if diag.Subject != nil && len(diag.Subject.Filename) > 0 {
49+
str += fmt.Sprintf("\n(%s)", diag.Subject.String())
50+
}
51+
52+
strs = append(strs, str)
53+
}
54+
}
55+
}
56+
57+
return strs
58+
}

plugin/diags_to_error.go

-46
This file was deleted.

0 commit comments

Comments
 (0)