github.com/anchore/syft@v1.4.2-0.20240516191711-1bec1fc5d397/syft/format/syftjson/encoder.go (about)

     1  package syftjson
     2  
     3  import (
     4  	"encoding/json"
     5  	"io"
     6  
     7  	"github.com/anchore/syft/internal"
     8  	"github.com/anchore/syft/syft/sbom"
     9  )
    10  
    11  var _ sbom.FormatEncoder = (*encoder)(nil)
    12  
    13  const ID sbom.FormatID = "syft-json"
    14  
    15  type EncoderConfig struct {
    16  	Legacy bool // transform the output to the legacy syft-json format (pre v1.0 changes, enumerated in the README.md)
    17  	Pretty bool // don't include spaces and newlines; same as jq -c
    18  }
    19  
    20  type encoder struct {
    21  	cfg EncoderConfig
    22  }
    23  
    24  func NewFormatEncoder() sbom.FormatEncoder {
    25  	enc, err := NewFormatEncoderWithConfig(DefaultEncoderConfig())
    26  	if err != nil {
    27  		panic(err)
    28  	}
    29  	return enc
    30  }
    31  
    32  func NewFormatEncoderWithConfig(cfg EncoderConfig) (sbom.FormatEncoder, error) {
    33  	return encoder{
    34  		cfg: cfg,
    35  	}, nil
    36  }
    37  
    38  func DefaultEncoderConfig() EncoderConfig {
    39  	return EncoderConfig{
    40  		Legacy: false,
    41  		Pretty: false,
    42  	}
    43  }
    44  
    45  func (e encoder) ID() sbom.FormatID {
    46  	return ID
    47  }
    48  
    49  func (e encoder) Aliases() []string {
    50  	return []string{
    51  		"json",
    52  		"syft",
    53  	}
    54  }
    55  
    56  func (e encoder) Version() string {
    57  	return internal.JSONSchemaVersion
    58  }
    59  
    60  func (e encoder) Encode(writer io.Writer, s sbom.SBOM) error {
    61  	doc := ToFormatModel(s, e.cfg)
    62  
    63  	enc := json.NewEncoder(writer)
    64  
    65  	enc.SetEscapeHTML(false)
    66  
    67  	if e.cfg.Pretty {
    68  		enc.SetIndent("", " ")
    69  	}
    70  
    71  	return enc.Encode(&doc)
    72  }