Skip to content

Instantly share code, notes, and snippets.

@spiffcs
Last active November 3, 2023 17:38
Show Gist options
  • Save spiffcs/3027638b7ba904d07e482a712bc00d3d to your computer and use it in GitHub Desktop.
Save spiffcs/3027638b7ba904d07e482a712bc00d3d to your computer and use it in GitHub Desktop.
syft as a library
package main
import (
"fmt"
"os"
"github.com/anchore/syft/cmd/syft/cli/options"
"github.com/anchore/syft/syft"
"github.com/anchore/syft/syft/format"
"github.com/anchore/syft/syft/pkg/cataloger"
"github.com/anchore/syft/syft/sbom"
"github.com/anchore/syft/syft/source"
)
func main() {
// this takes a shortcut using the source dection functions to build a source from what
// the typical user input would be. There are other ways from the source package this can be
// constructed to do dir/file analysis. Because this is the Detect function one could also
// pass a local tar path ex: `alpine.tar` or `/tmp/alpine.tar`
detection, err := source.Detect("alpine:latest", source.DefaultDetectConfig())
if err != nil {
fmt.Println(err)
return
}
src, err := detection.NewSource(source.DefaultDetectionSourceConfig())
if err != nil {
fmt.Println(err)
return
}
collection, relationships, release, err := syft.CatalogPackages(src, cataloger.DefaultConfig())
if err != nil {
fmt.Println(err)
return
}
sbom := sbom.SBOM{
Artifacts: sbom.Artifacts{
Packages: collection,
LinuxDistribution: release,
},
Relationships: relationships,
Source: src.Describe(),
Descriptor: sbom.Descriptor{
Name: "my-program", // Your Program rather than syft
Version: "my-programs-version",
// the application configuration can be persisted here
Configuration: map[string]string{
"config-key": "config-value",
},
},
}
opts := options.DefaultOutput()
encoderList, err := opts.Encoders()
if err != nil {
fmt.Println(err)
return
}
encoders := format.NewEncoderCollection(encoderList...)
// you could build a loop of all encoder types here and
// output all of them if you wanted - this shows spdx-json
// as the example and uses os.Stdout as the io.Writer
formatEncoder := encoders.GetByString("spdx-json")
if formatEncoder == nil {
fmt.Println("no encoder found")
return
}
if err := formatEncoder.Encode(os.Stdout, sbom); err != nil {
fmt.Println(err)
return
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment