github.com/noqcks/syft@v0.0.0-20230920222752-a9e2c4e288e5/syft/formats/syftjson/decoder.go (about)

     1  package syftjson
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  
     8  	"github.com/Masterminds/semver"
     9  
    10  	"github.com/anchore/syft/internal"
    11  	"github.com/anchore/syft/internal/log"
    12  	"github.com/anchore/syft/syft/formats/syftjson/model"
    13  	"github.com/anchore/syft/syft/sbom"
    14  )
    15  
    16  func decoder(reader io.Reader) (*sbom.SBOM, error) {
    17  	dec := json.NewDecoder(reader)
    18  
    19  	var doc model.Document
    20  	err := dec.Decode(&doc)
    21  	if err != nil {
    22  		return nil, fmt.Errorf("unable to decode syft-json: %w", err)
    23  	}
    24  
    25  	if err := checkSupportedSchema(doc.Schema.Version, internal.JSONSchemaVersion); err != nil {
    26  		log.Warn(err)
    27  	}
    28  
    29  	return toSyftModel(doc)
    30  }
    31  
    32  func checkSupportedSchema(documentVerion string, parserVersion string) error {
    33  	documentV, err := semver.NewVersion(documentVerion)
    34  	if err != nil {
    35  		return fmt.Errorf("error comparing document schema version with parser schema version: %w", err)
    36  	}
    37  
    38  	parserV, err := semver.NewVersion(parserVersion)
    39  	if err != nil {
    40  		return fmt.Errorf("error comparing document schema version with parser schema version: %w", err)
    41  	}
    42  
    43  	if documentV.GreaterThan(parserV) {
    44  		return fmt.Errorf("document has schema version %s, but parser has older schema version (%s)", documentVerion, parserVersion)
    45  	}
    46  
    47  	return nil
    48  }