github.com/turbot/steampipe@v1.7.0-rc.0.0.20240517123944-7cef272d4458/pkg/control/controldisplay/control_exporter.go (about)

     1  package controldisplay
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"github.com/turbot/steampipe/pkg/contexthelpers"
     7  	"github.com/turbot/steampipe/pkg/control/controlexecute"
     8  	"github.com/turbot/steampipe/pkg/export"
     9  )
    10  
    11  var contextKeyFormatterPurpose = contexthelpers.ContextKey("formatter_purpose")
    12  
    13  const formatterPurposeExport = "export"
    14  
    15  type ControlExporter struct {
    16  	formatter Formatter
    17  }
    18  
    19  func NewControlExporter(formatter Formatter) *ControlExporter {
    20  	return &ControlExporter{formatter}
    21  }
    22  
    23  func (e *ControlExporter) Export(ctx context.Context, input export.ExportSourceData, destPath string) error {
    24  
    25  	// tell the formatter it is being used for export
    26  	// this is a tactical mechanism used to ensure that exported snapshots are unindented
    27  	// whereas display snapshots are indented
    28  	exportCtx := context.WithValue(ctx, contextKeyFormatterPurpose, formatterPurposeExport)
    29  
    30  	// input must be control execution tree
    31  	tree, ok := input.(*controlexecute.ExecutionTree)
    32  	if !ok {
    33  		return fmt.Errorf("ControlExporter input must be *controlexecute.ExecutionTree")
    34  	}
    35  	res, err := e.formatter.Format(exportCtx, tree)
    36  	if err != nil {
    37  		return err
    38  	}
    39  
    40  	return export.Write(destPath, res)
    41  }
    42  
    43  func (e *ControlExporter) FileExtension() string {
    44  	return e.formatter.FileExtension()
    45  }
    46  
    47  func (e *ControlExporter) Name() string {
    48  	return e.formatter.Name()
    49  }
    50  
    51  func (e *ControlExporter) Alias() string {
    52  	return e.formatter.Alias()
    53  }