github.com/lineaje-labs/syft@v0.98.1-0.20231227153149-9e393f60ff1b/syft/format/text/encoder.go (about)

     1  package text
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"text/tabwriter"
     7  
     8  	"github.com/anchore/syft/syft/sbom"
     9  	"github.com/anchore/syft/syft/source"
    10  )
    11  
    12  const ID sbom.FormatID = "syft-text"
    13  
    14  type encoder struct {
    15  }
    16  
    17  func NewFormatEncoder() sbom.FormatEncoder {
    18  	return encoder{}
    19  }
    20  
    21  func (e encoder) ID() sbom.FormatID {
    22  	return ID
    23  }
    24  
    25  func (e encoder) Aliases() []string {
    26  	return []string{
    27  		"text",
    28  	}
    29  }
    30  
    31  func (e encoder) Version() string {
    32  	return sbom.AnyVersion
    33  }
    34  
    35  func (e encoder) Encode(writer io.Writer, s sbom.SBOM) error {
    36  	// init the tabular writer
    37  	w := new(tabwriter.Writer)
    38  	w.Init(writer, 0, 8, 0, '\t', tabwriter.AlignRight)
    39  
    40  	switch metadata := s.Source.Metadata.(type) {
    41  	case source.DirectorySourceMetadata:
    42  		fmt.Fprintf(w, "[Path: %s]\n", metadata.Path)
    43  	case source.FileSourceMetadata:
    44  		fmt.Fprintf(w, "[Path: %s]\n", metadata.Path)
    45  	case source.StereoscopeImageSourceMetadata:
    46  		fmt.Fprintln(w, "[Image]")
    47  
    48  		for idx, l := range metadata.Layers {
    49  			fmt.Fprintln(w, " Layer:\t", idx)
    50  			fmt.Fprintln(w, " Digest:\t", l.Digest)
    51  			fmt.Fprintln(w, " Size:\t", l.Size)
    52  			fmt.Fprintln(w, " MediaType:\t", l.MediaType)
    53  			fmt.Fprintln(w)
    54  			w.Flush()
    55  		}
    56  	default:
    57  		return fmt.Errorf("unsupported source: %T", s.Source.Metadata)
    58  	}
    59  
    60  	// populate artifacts...
    61  	rows := 0
    62  	for _, p := range s.Artifacts.Packages.Sorted() {
    63  		fmt.Fprintf(w, "[%s]\n", p.Name)
    64  		fmt.Fprintln(w, " Version:\t", p.Version)
    65  		fmt.Fprintln(w, " Type:\t", string(p.Type))
    66  		fmt.Fprintln(w, " Found by:\t", p.FoundBy)
    67  		fmt.Fprintln(w)
    68  		w.Flush()
    69  		rows++
    70  	}
    71  
    72  	if rows == 0 {
    73  		fmt.Fprintln(writer, "No packages discovered")
    74  		return nil
    75  	}
    76  
    77  	return nil
    78  }