Skip to content

Commit db24679

Browse files
committed
add more error context
1 parent cfc2017 commit db24679

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

types/convert.go

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
package types
22

33
import (
4+
"fmt"
5+
6+
"github.com/aquasecurity/trivy/pkg/iac/terraform"
47
"github.com/hashicorp/hcl/v2"
58
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
9+
"github.com/zclconf/go-cty/cty"
10+
hcty "github.com/hashicorp/go-cty/cty"
11+
hctyjson "github.com/hashicorp/go-cty/cty/json"
12+
ctyjson "github.com/zclconf/go-cty/cty/json"
613

714
"github.com/coder/terraform-provider-coder/v2/provider"
815
)
@@ -44,27 +51,42 @@ func providerOption(opt *ParameterOption) provider.Option {
4451
}
4552
}
4653

47-
func hclDiagnostics(diagnostics diag.Diagnostics) hcl.Diagnostics {
54+
func hclDiagnostics(diagnostics diag.Diagnostics, source *terraform.Block) hcl.Diagnostics {
4855
cpy := make(hcl.Diagnostics, 0, len(diagnostics))
4956
for _, d := range diagnostics {
50-
cpy = append(cpy, hclDiagnostic(d))
57+
cpy = append(cpy, hclDiagnostic(d, source))
5158
}
5259
return cpy
5360
}
5461

55-
func hclDiagnostic(d diag.Diagnostic) *hcl.Diagnostic {
62+
func hclDiagnostic(d diag.Diagnostic, source *terraform.Block) *hcl.Diagnostic {
5663
sev := hcl.DiagInvalid
5764
switch d.Severity {
5865
case diag.Error:
5966
sev = hcl.DiagError
6067
case diag.Warning:
6168
sev = hcl.DiagWarning
6269
}
70+
71+
// This is an imperfect way to finding the source code of the error. There is 2
72+
// different `cty` types at place here, the hashicorp fork and the original. So a
73+
// more general solution is difficult. This is good enough for now to add more
74+
// context to an error.
75+
var subject *hcl.Range
76+
if len(d.AttributePath) == 1 && source != nil {
77+
if attr, ok := d.AttributePath[0].(hcty.GetAttrStep); ok {
78+
src := source.GetAttribute(attr.Name)
79+
if src != nil {
80+
subject = &(src.HCLAttribute().Range)
81+
}
82+
}
83+
}
84+
6385
return &hcl.Diagnostic{
6486
Severity: sev,
6587
Summary: d.Summary,
6688
Detail: d.Detail,
67-
Subject: nil,
89+
Subject: subject,
6890
Context: nil,
6991
Expression: nil,
7092
EvalContext: nil,

types/parameter.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ func (r *ParameterData) Valid() hcl.Diagnostics {
113113
if diag.HasError() {
114114
// TODO: We can take the attr path and decorate the error with
115115
// source information.
116-
return hclDiagnostics(diag)
116+
return hclDiagnostics(diag, source)
117117
}
118118
return nil
119119
}

0 commit comments

Comments
 (0)