-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreview.go
181 lines (159 loc) · 4.7 KB
/
preview.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package preview
import (
"context"
"encoding/json"
"fmt"
"io/fs"
"path/filepath"
"github.com/aquasecurity/trivy/pkg/iac/scanners/terraform/parser"
"github.com/hashicorp/hcl/v2"
"github.com/zclconf/go-cty/cty"
"github.com/coder/preview/hclext"
"github.com/coder/preview/types"
)
type Input struct {
// PlanJSONPath is an optional path to a plan file. If PlanJSON isn't
// specified, and PlanJSONPath is, then the file will be read and treated
// as if the contents were passed in directly.
PlanJSONPath string
PlanJSON json.RawMessage
ParameterValues map[string]string
Owner types.WorkspaceOwner
}
type Output struct {
// ModuleOutput is any 'output' values from the terraform files. This has 0
// effect on the parameters, tags, etc. It can be helpful for debugging, as it
// allows exporting some terraform values to the caller to review.
ModuleOutput cty.Value
Parameters []types.Parameter
WorkspaceTags types.TagBlocks
// Files is included for printing diagnostics.
// TODO: Is the memory impact of this too much? Should we render diagnostic source code
// into the diagnostics up front? and remove this?
Files map[string]*hcl.File
}
func Preview(ctx context.Context, input Input, dir fs.FS) (output *Output, diagnostics hcl.Diagnostics) {
// The trivy package works with `github.com/zclconf/go-cty`. This package is
// similar to `reflect` in its usage. This package can panic if types are
// misused. To protect the caller, a general `recover` is used to catch any
// mistakes. If this happens, there is a developer bug that needs to be resolved.
defer func() {
if r := recover(); r != nil {
diagnostics = hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Panic occurred in preview. This should not happen, please report this to Coder.",
Detail: fmt.Sprintf("panic in preview: %+v", r),
},
}
}
}()
// TODO: Fix logging. There is no way to pass in an instanced logger to
// the parser.
//slog.SetLogLoggerLevel(slog.LevelDebug)
//slog.SetDefault(slog.New(log.NewHandler(os.Stderr, nil)))
varFiles, err := tfVarFiles("", dir)
if err != nil {
return nil, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Files not found",
Detail: err.Error(),
},
}
}
planHook, err := planJSONHook(dir, input)
if err != nil {
return nil, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Parsing plan JSON",
Detail: err.Error(),
},
}
}
ownerHook, err := workspaceOwnerHook(dir, input)
if err != nil {
return nil, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Workspace owner hook",
Detail: err.Error(),
},
}
}
var _ = ownerHook
// moduleSource is "" for a local module
p := parser.New(dir, "",
parser.OptionStopOnHCLError(false),
parser.OptionWithDownloads(false),
parser.OptionWithSkipCachedModules(true),
parser.OptionWithTFVarsPaths(varFiles...),
parser.OptionWithEvalHook(planHook),
parser.OptionWithEvalHook(ownerHook),
parser.OptionWithEvalHook(parameterContextsEvalHook(input)),
)
err = p.ParseFS(ctx, ".")
if err != nil {
return nil, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Parse terraform files",
Detail: err.Error(),
},
}
}
modules, _, err := p.EvaluateAll(ctx)
if err != nil {
return nil, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Evaluate terraform files",
Detail: err.Error(),
},
}
}
outputs := hclext.ExportOutputs(modules)
diags := make(hcl.Diagnostics, 0)
rp, rpDiags := parameters(modules)
tags, tagDiags := workspaceTags(modules, p.Files())
// Add warnings
diags = diags.Extend(warnings(modules))
return &Output{
ModuleOutput: outputs,
Parameters: rp,
WorkspaceTags: tags,
Files: p.Files(),
}, diags.Extend(rpDiags).Extend(tagDiags)
}
func (i Input) RichParameterValue(key string) (string, bool) {
p, ok := i.ParameterValues[key]
return p, ok
}
// tfVarFiles extracts any .tfvars files from the given directory.
// TODO: Test nested directories and how that should behave.
func tfVarFiles(path string, dir fs.FS) ([]string, error) {
dp := "."
entries, err := fs.ReadDir(dir, dp)
if err != nil {
return nil, fmt.Errorf("read dir %q: %w", dp, err)
}
files := make([]string, 0)
for _, entry := range entries {
if entry.IsDir() {
subD, err := fs.Sub(dir, entry.Name())
if err != nil {
return nil, fmt.Errorf("sub dir %q: %w", entry.Name(), err)
}
newFiles, err := tfVarFiles(filepath.Join(path, entry.Name()), subD)
if err != nil {
return nil, err
}
files = append(files, newFiles...)
}
if filepath.Ext(entry.Name()) == ".tfvars" {
files = append(files, filepath.Join(path, entry.Name()))
}
}
return files, nil
}