diff --git a/types/diagnostics.go b/types/diagnostics.go index 41d18b7..3ae0955 100644 --- a/types/diagnostics.go +++ b/types/diagnostics.go @@ -10,6 +10,28 @@ import ( // Data is lost when doing a json marshal. type Diagnostics hcl.Diagnostics +func (d *Diagnostics) UnmarshalJSON(data []byte) error { + cpy := make([]FriendlyDiagnostic, 0) + if err := json.Unmarshal(data, &cpy); err != nil { + return err + } + + *d = make(Diagnostics, 0, len(cpy)) + for _, diag := range cpy { + severity := hcl.DiagError + if diag.Severity == DiagnosticSeverityWarning { + severity = hcl.DiagWarning + } + + *d = append(*d, &hcl.Diagnostic{ + Severity: severity, + Summary: diag.Summary, + Detail: diag.Detail, + }) + } + return nil +} + func (d Diagnostics) MarshalJSON() ([]byte, error) { cpy := make([]FriendlyDiagnostic, 0, len(d)) for _, diag := range d { diff --git a/types/diagnostics_test.go b/types/diagnostics_test.go new file mode 100644 index 0000000..82a4845 --- /dev/null +++ b/types/diagnostics_test.go @@ -0,0 +1,36 @@ +package types_test + +import ( + "encoding/json" + "testing" + + "github.com/hashicorp/hcl/v2" + "github.com/stretchr/testify/require" + + "github.com/coder/preview/types" +) + +func TestDiagnosticsJSON(t *testing.T) { + + diags := types.Diagnostics{ + { + Severity: hcl.DiagWarning, + Summary: "Some summary", + Detail: "Some detail", + }, + { + Severity: hcl.DiagError, + Summary: "Some summary", + Detail: "Some detail", + }, + } + + data, err := json.Marshal(diags) + require.NoError(t, err, "marshal") + + var newDiags types.Diagnostics + err = json.Unmarshal(data, &newDiags) + require.NoError(t, err, "unmarshal") + + require.Equal(t, diags, newDiags) +}