Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Plugin: Add example for SPDX SBOM generator plugin #307

Open
wants to merge 1 commit into
base: experimental
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions examples/pomtospdx/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Plugin Example: Parse a pom.xml file and generate an SPDX 2.3 JSON document

## Writing the Plugin

In this example, we will parse an example pom.xml file and create an SPDX document with the data. The plugin is called `mvnpom`. We use an existing pom.xml parser to get the data. We have restricted parsing to only SPDX 2.3 as the SPDX version and JSON as the data format, but other versions and formats can be supported.

The required function to implement for the plugin is the `GetSpdxDocument` method. This must return an object of type `AnyDocument`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you think about it, the plugin's job is not to return the document. The plugin should only return a data structure representing the data it knows about (probably a package representing the code and its dependencies). That structure may be part of a document with more than one code repository, for example.


In order to make this plugin "discoverable", the `init` function must be implemented. This function should use the `plugin` module's `Register` function, giving the name of the plugin. In this case, the name is "mvnpom".

## Using the Plugin

In the `main.go` program, we use an empty import to import the plugin `mvnpom`. We first get the plugin object. Then we call the object's `GetSpdxDocument()` function. From here we can create a JSON string using the `Marshal` function which takes care of creating an SPDX JSON document.
25 changes: 25 additions & 0 deletions examples/pomtospdx/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package main

import (
"encoding/json"
"fmt"

_ "github.com/spdx/spdx-sbom-generator/examples/pomtospdx/mvnpom"
"github.com/spdx/spdx-sbom-generator/pkg/plugin"
)

func main() {
pg, err := plugin.GetPlugin("mvnpom")
if err != nil {
fmt.Println(err)
}
spdxdoc, err2 := pg.GetSpdxDocument()
if err2 != nil {
fmt.Println(err2)
}
spdxdocjson, err3 := json.Marshal(spdxdoc)
if err3 != nil {
fmt.Println(err3)
}
fmt.Println(string(spdxdocjson))
}
171 changes: 171 additions & 0 deletions examples/pomtospdx/mvnpom/mvnpom.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
// package mvnpom implements the plugin.Plugin interface
package mvnpom

import (
"errors"
"fmt"
"path/filepath"
"time"

"github.com/spdx/spdx-sbom-generator/pkg/plugin"

purl "github.com/package-url/packageurl-go"
c "github.com/spdx/tools-golang/spdx/common"
v2 "github.com/spdx/tools-golang/spdx/v2/common"
"github.com/spdx/tools-golang/spdx/v2/v2_3"
"github.com/vifraa/gopom"
"golang.org/x/exp/slices"
)

// name is used to register this plugin
var name = "mvnpom"

// supportedSpdxVersions contains all supported SPDX versions for MvnPomPlugin
var supportedSpdxVersions = [1]string{"2.3"}

// supportedFormats contains all supported formats for MvnPomPlugin
var supportedFormats = [1]string{"json"}

var topSPDXPackageId v2.ElementID = "SPDXRef-0"

// MvnPomPlugin implements Plugin
type MvnPomPlugin struct {
PluginPath string // this Plugin requires a path to the pom.xml file
SpdxVersion string // this Plugin requires an SPDX spec version
SpdxFormat string // this Plugin requires an SPDX format

}

// NewMvnPomPlugin returns a pointer to an MvnPomPlugin
// object with default values
// Ideally, this struct will also contain command line options
// for which a NewWithOptions function may be used
func NewMvnPomPlugin() *MvnPomPlugin {
return &MvnPomPlugin{
PluginPath: ".",
SpdxVersion: "2.3",
SpdxFormat: "json",
}
}

// GetSpdxDocument returns an SPDX document of supported format
func (mpp MvnPomPlugin) GetSpdxDocument() (c.AnyDocument, error) {
// return an error if the SPDX version is not supported
s := supportedSpdxVersions[:]
f := supportedFormats[:]
if !slices.Contains(s, mpp.SpdxVersion) {
return nil, errors.New("unsupported SPDX version")
}
if !slices.Contains(f, mpp.SpdxFormat) {
return nil, errors.New("unsupported SPDX format")
}
// read the pom.xml file
pomPath := filepath.Join(mpp.PluginPath, "pom.xml")
parsedPom, err := gopom.Parse(pomPath)
if err != nil {
return nil, err
}
// create all structs
// doc CreationInfo
cinfo := v2_3.CreationInfo{
Creators: getDocCreators(),
Created: getDocTimestamp(),
}
doc := v2_3.Document{
SPDXVersion: v2_3.Version,
DataLicense: v2_3.DataLicense,
SPDXIdentifier: "SPDXRef-DOCUMENT",
DocumentName: "example_mvn_pom_spdx",
DocumentNamespace: fmt.Sprintf("http://spdx.org/documents/%s-%s", *parsedPom.ArtifactID, *parsedPom.Version),
CreationInfo: &cinfo,
Packages: getPomPackages(parsedPom),
}
return doc, nil
}

// init registers this plugin
func init() {
mpp := NewMvnPomPlugin()
if name != "" {
plugin.Register(name, mpp)
}
}

// unexported functions

func getDocCreators() []v2.Creator {
var creators []v2.Creator
tc := v2.Creator{
Creator: "pomtospdx",
CreatorType: "Tool",
}
creators = append(creators, tc)
return creators
}

func getDocTimestamp() string {
t := time.Now()
return fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
}

func getPomPackages(p *gopom.Project) []*v2_3.Package {
var packages []*v2_3.Package
// get the top package first
tsupplier := v2.Supplier{
Supplier: *p.Organization.Name,
SupplierType: "Organization",
}
tdl := purl.NewPackageURL("maven",
*p.GroupID,
*p.Name,
*p.Version,
nil,
"")
tpackage := v2_3.Package{
IsUnpackaged: false,
PackageName: *p.Name,
PackageSPDXIdentifier: topSPDXPackageId,
PackageVersion: *p.Version,
PackageSupplier: &tsupplier,
PackageDownloadLocation: tdl.ToString(),
FilesAnalyzed: false,
PackageLicenseDeclared: "NOASSERTION",
PrimaryPackagePurpose: "APPLICATION",
}
packages = append(packages, &tpackage)
// get declared dependencies
for i, d := range *p.Dependencies {
if d.Scope == nil {
spdxid := fmt.Sprintf("SPDXRef-%d", i+1)
pkg := v2_3.Package{
PackageName: *d.ArtifactID,
PackageSPDXIdentifier: v2.ElementID(spdxid),
PackageVersion: *d.Version,
PackageSupplier: getDepSupplier(d),
PackageDownloadLocation: getDepPurl(d),
FilesAnalyzed: false,
}
packages = append(packages, &pkg)
}

}
return packages
}

func getDepSupplier(d gopom.Dependency) *v2.Supplier {
return &v2.Supplier{
Supplier: *d.GroupID,
SupplierType: "Organization",
}
}

func getDepPurl(d gopom.Dependency) string {
ddl := purl.NewPackageURL("maven",
*d.GroupID,
*d.ArtifactID,
*d.Version,
nil,
"")
return ddl.ToString()
}
Loading
Loading