@@ -2,6 +2,7 @@ package hclutils
2
2
3
3
import (
4
4
"bytes"
5
+ "errors"
5
6
"fmt"
6
7
7
8
"github.com/hashicorp/hcl2/hcl"
@@ -17,7 +18,7 @@ import (
17
18
// ParseHclInterface is used to convert an interface value representing a hcl2
18
19
// body and return the interpolated value. Vars may be nil if there are no
19
20
// variables to interpolate.
20
- func ParseHclInterface (val interface {}, spec hcldec.Spec , vars map [string ]cty.Value ) (cty.Value , hcl.Diagnostics ) {
21
+ func ParseHclInterface (val interface {}, spec hcldec.Spec , vars map [string ]cty.Value ) (cty.Value , hcl.Diagnostics , [] error ) {
21
22
evalCtx := & hcl.EvalContext {
22
23
Variables : vars ,
23
24
Functions : GetStdlibFuncs (),
@@ -29,27 +30,29 @@ func ParseHclInterface(val interface{}, spec hcldec.Spec, vars map[string]cty.Va
29
30
err := enc .Encode (val )
30
31
if err != nil {
31
32
// Convert to a hcl diagnostics message
32
- return cty .NilVal , hcl .Diagnostics ([]* hcl.Diagnostic {
33
- {
33
+ errorMessage := fmt .Sprintf ("Label encoding failed: %v" , err )
34
+ return cty .NilVal ,
35
+ hcl .Diagnostics ([]* hcl.Diagnostic {{
34
36
Severity : hcl .DiagError ,
35
- Summary : "Failed to JSON encode value" ,
36
- Detail : fmt .Sprintf ("JSON encoding failed: %v" , err ),
37
- }})
37
+ Summary : "Failed to encode label value" ,
38
+ Detail : errorMessage ,
39
+ }}),
40
+ []error {errors .New (errorMessage )}
38
41
}
39
42
40
43
// Parse the json as hcl2
41
44
hclFile , diag := hjson .Parse (buf .Bytes (), "" )
42
45
if diag .HasErrors () {
43
- return cty .NilVal , diag
46
+ return cty .NilVal , diag , formattedDiagnosticErrors ( diag )
44
47
}
45
48
46
49
value , decDiag := hcldec .Decode (hclFile .Body , spec , evalCtx )
47
50
diag = diag .Extend (decDiag )
48
51
if diag .HasErrors () {
49
- return cty .NilVal , diag
52
+ return cty .NilVal , diag , formattedDiagnosticErrors ( diag )
50
53
}
51
54
52
- return value , diag
55
+ return value , diag , nil
53
56
}
54
57
55
58
// GetStdlibFuncs returns the set of stdlib functions.
@@ -72,3 +75,18 @@ func GetStdlibFuncs() map[string]function.Function {
72
75
"upper" : stdlib .UpperFunc ,
73
76
}
74
77
}
78
+
79
+ // TODO: update hcl2 library with better diagnostics formatting for streamed configs
80
+ // - should be arbitrary labels not JSON https://github.com/hashicorp/hcl2/blob/4fba5e1a75e382aed7f7a7993f2c4836a5e1cd52/hcl/json/structure.go#L66
81
+ // - should not print diagnostic subject https://github.com/hashicorp/hcl2/blob/4fba5e1a75e382aed7f7a7993f2c4836a5e1cd52/hcl/diagnostic.go#L77
82
+ func formattedDiagnosticErrors (diag hcl.Diagnostics ) []error {
83
+ var errs []error
84
+ for _ , d := range diag {
85
+ if d .Summary == "Extraneous JSON object property" {
86
+ d .Summary = "Invalid label"
87
+ }
88
+ err := errors .New (fmt .Sprintf ("%s: %s" , d .Summary , d .Detail ))
89
+ errs = append (errs , err )
90
+ }
91
+ return errs
92
+ }
0 commit comments