github.com/nextlinux/gosbom@v0.81.1-0.20230627115839-1ff50c281391/gosbom/formats/common/cyclonedxhelpers/cpe.go (about)

     1  package cyclonedxhelpers
     2  
     3  import (
     4  	"github.com/CycloneDX/cyclonedx-go"
     5  	"github.com/nextlinux/gosbom/gosbom/cpe"
     6  	"github.com/nextlinux/gosbom/gosbom/pkg"
     7  	"github.com/nextlinux/gosbom/internal/log"
     8  )
     9  
    10  func encodeSingleCPE(p pkg.Package) string {
    11  	// Since the CPEs in a package are sorted by specificity
    12  	// we can extract the first CPE as the one to output in cyclonedx
    13  	if len(p.CPEs) > 0 {
    14  		return cpe.String(p.CPEs[0])
    15  	}
    16  	return ""
    17  }
    18  
    19  func encodeCPEs(p pkg.Package) (out []cyclonedx.Property) {
    20  	for i, c := range p.CPEs {
    21  		// first CPE is "most specific" and already encoded as the component CPE
    22  		if i == 0 {
    23  			continue
    24  		}
    25  		out = append(out, cyclonedx.Property{
    26  			Name:  "gosbom:cpe23",
    27  			Value: cpe.String(c),
    28  		})
    29  	}
    30  	return
    31  }
    32  
    33  func decodeCPEs(c *cyclonedx.Component) (out []cpe.CPE) {
    34  	if c.CPE != "" {
    35  		cp, err := cpe.New(c.CPE)
    36  		if err != nil {
    37  			log.Warnf("invalid CPE: %s", c.CPE)
    38  		} else {
    39  			out = append(out, cp)
    40  		}
    41  	}
    42  
    43  	if c.Properties != nil {
    44  		for _, p := range *c.Properties {
    45  			if p.Name == "gosbom:cpe23" {
    46  				cp, err := cpe.New(p.Value)
    47  				if err != nil {
    48  					log.Warnf("invalid CPE: %s", p.Value)
    49  				} else {
    50  					out = append(out, cp)
    51  				}
    52  			}
    53  		}
    54  	}
    55  
    56  	return
    57  }