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