Skip to content

Commit 131ed6b

Browse files
authored
feat: add support to json marshal the module output (#143)
1 parent fa5e815 commit 131ed6b

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

preview.go

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"github.com/aquasecurity/trivy/pkg/iac/scanners/terraform/parser"
1212
"github.com/hashicorp/hcl/v2"
1313
"github.com/zclconf/go-cty/cty"
14+
ctyjson "github.com/zclconf/go-cty/cty/json"
1415

1516
"github.com/coder/preview/hclext"
1617
"github.com/coder/preview/types"
@@ -31,14 +32,35 @@ type Output struct {
3132
// ModuleOutput is any 'output' values from the terraform files. This has 0
3233
// effect on the parameters, tags, etc. It can be helpful for debugging, as it
3334
// allows exporting some terraform values to the caller to review.
34-
ModuleOutput cty.Value
35+
//
36+
// JSON marshalling is handled in the custom methods.
37+
ModuleOutput cty.Value `json:"-"`
3538

36-
Parameters []types.Parameter
37-
WorkspaceTags types.TagBlocks
39+
Parameters []types.Parameter `json:"parameters"`
40+
WorkspaceTags types.TagBlocks `json:"workspace_tags"`
3841
// Files is included for printing diagnostics.
39-
// TODO: Is the memory impact of this too much? Should we render diagnostic source code
40-
// into the diagnostics up front? and remove this?
41-
Files map[string]*hcl.File
42+
// They can be marshalled, but not unmarshalled. This is a limitation
43+
// of the HCL library.
44+
Files map[string]*hcl.File `json:"-"`
45+
}
46+
47+
// MarshalJSON includes the ModuleOutput and files in the JSON output. Output
48+
// should never be unmarshalled. Marshalling to JSON is strictly useful for
49+
// debugging information.
50+
func (o Output) MarshalJSON() ([]byte, error) {
51+
// Do not make this a fatal error, as it is supplementary information.
52+
modOutput, _ := ctyjson.Marshal(o.ModuleOutput, o.ModuleOutput.Type())
53+
54+
type Alias Output
55+
return json.Marshal(&struct {
56+
ModuleOutput json.RawMessage `json:"module_output"`
57+
Files map[string]*hcl.File `json:"files"`
58+
Alias
59+
}{
60+
ModuleOutput: modOutput,
61+
Files: o.Files,
62+
Alias: (Alias)(o),
63+
})
4264
}
4365

4466
func Preview(ctx context.Context, input Input, dir fs.FS) (output *Output, diagnostics hcl.Diagnostics) {

0 commit comments

Comments
 (0)