@@ -209,3 +209,70 @@ func tfVarFiles(path string, dir fs.FS) ([]string, error) {
209209 }
210210 return files , nil
211211}
212+
213+ func PreviewPresets (ctx context.Context , dir fs.FS ) ([]types.Preset , hcl.Diagnostics ) {
214+ // The trivy package works with `github.com/zclconf/go-cty`. This package is
215+ // similar to `reflect` in its usage. This package can panic if types are
216+ // misused. To protect the caller, a general `recover` is used to catch any
217+ // mistakes. If this happens, there is a developer bug that needs to be resolved.
218+ var diagnostics hcl.Diagnostics
219+ defer func () {
220+ if r := recover (); r != nil {
221+ diagnostics .Extend (hcl.Diagnostics {
222+ {
223+ Severity : hcl .DiagError ,
224+ Summary : "Panic occurred in preview. This should not happen, please report this to Coder." ,
225+ Detail : fmt .Sprintf ("panic in preview: %+v" , r ),
226+ },
227+ })
228+ }
229+ }()
230+
231+ logger := slog .New (slog .DiscardHandler )
232+
233+ varFiles , err := tfVarFiles ("" , dir )
234+ if err != nil {
235+ return nil , hcl.Diagnostics {
236+ {
237+ Severity : hcl .DiagError ,
238+ Summary : "Files not found" ,
239+ Detail : err .Error (),
240+ },
241+ }
242+ }
243+
244+ // moduleSource is "" for a local module
245+ p := parser .New (dir , "" ,
246+ parser .OptionWithLogger (logger ),
247+ parser .OptionStopOnHCLError (false ),
248+ parser .OptionWithDownloads (false ),
249+ parser .OptionWithSkipCachedModules (true ),
250+ parser .OptionWithTFVarsPaths (varFiles ... ),
251+ )
252+
253+ err = p .ParseFS (ctx , "." )
254+ if err != nil {
255+ return nil , hcl.Diagnostics {
256+ {
257+ Severity : hcl .DiagError ,
258+ Summary : "Parse terraform files" ,
259+ Detail : err .Error (),
260+ },
261+ }
262+ }
263+
264+ modules , err := p .EvaluateAll (ctx )
265+ if err != nil {
266+ return nil , hcl.Diagnostics {
267+ {
268+ Severity : hcl .DiagError ,
269+ Summary : "Evaluate terraform files" ,
270+ Detail : err .Error (),
271+ },
272+ }
273+ }
274+
275+ rp , rpDiags := parameters (modules )
276+ presets , presetDiags := presets (modules , rp )
277+ return presets , diagnostics .Extend (rpDiags ).Extend (presetDiags )
278+ }
0 commit comments