Thanks to visit codestin.com
Credit goes to github.com

Skip to content

fix: add json unmarshal support for diagnostics #116

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions types/diagnostics.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
36 changes: 36 additions & 0 deletions types/diagnostics_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
Loading